百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

【Python】随机数和 列表 python3随机数

off999 2024-12-20 17:55 27 浏览 0 评论



Python 随机模块方法

randint(a, b):

返回介于 ab 之间(含两者)的随机整数。如果 a > b,这也会引发 ValueError

import random

random_int = random.randint(1,10)
print(random_int)

>>
PS \Python> python .\random_int.py
4
PS \Python> python .\random_int.py
10
PS \Python> python .\random_int.py
3

可以创建自己的模块并导入它。

#my_module.py

pi = 3.1415
#random_int.py

import random
import my_module

random_int = random.randint(1,10)
print(random_int)


print(my_module.pi)

>>
PS \Python> python .\random_int.py
8
3.1415

生成 Random 浮点数:

与生成整数类似,也有一些函数可以生成随机浮点序列。

  • random.random() -> 返回介于 [0.0 到 1.0] 之间的下一个随机浮点数
  • random.uniform(a, b) -> 返回一个随机浮点数 N,使得 a <= N <= b 如果 a <= b,b <= N <= a 如果 b < a。
  • random.随机。expovariate(lambda) -> 返回与指数分布对应的数字。
  • random.gauss(mu, sigma) -> 返回与高斯分布相对应的数字。

其他分布也有类似的函数,例如 Normal Distribution、Gamma Distribution 等。

import random


random_int = random.randint(1,10)
print(random_int)

random_flot =  random.random()
print(random_flot)

>>

1
0.041635438063850505

项目 1:爱情评分

import random
print("\n")
print("-------Welcome to Love Calculator-------\n")

name1 =  input("What is your name?\n")
name2 =  input("What is their name?\n")

love_score =  random.randint(1, 100)

print(f"Love score of {name1} and {name2} is {love_score}")

>>

-------Welcome to Love Calculator-------

What is your name?
Lisa
What is their name?
Jack
Love score of Lisa and Jack is 34

项目 2:正面或反面

import random

random_side =  random.randint(0, 1)

if random_side == 1:
    print ("Heads")
else:
    print("Tails")

>>

PS \Python> python.exe .\heads_tails.py
Tails
PS \Python> python.exe .\heads_tails.py
Heads

列表:

检查此列表 : 数据结构

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
print(fruits[2])
print(fruits[-2])

>>

pear
apple
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
print(fruits[2])
print(fruits[-2])

fruits[2] =  "Cheery"   #CHNAGE NAME
print(fruits)

>>

pear
apple
['orange', 'apple', 'Cheery', 'banana', 'kiwi', 'apple', 'banana']

可以将其附加到列表中:

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

fruits.append("Nid")
print(fruits)

>>
['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana', 'Nid']

扩展列表:

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

fruits.extend(["AP", "gy"])
print(fruits)

>>
['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana', 'Nid', 'AP', 'gy']    

检查列表的长度

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

print(len(fruits))

项目 3:谁来支付

names =  input("Enter the names\n")

name_list = names.split(", ")

import random

num_item = len(names)

random_choice = random.randint(0, num_item - 1)
print(names[random_choice])

嵌套列表

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
vegetables = ['Beetroot', 'Carrots', 'Capsicum', 'Ginger', 'Cauliflower']

fridge = [fruits, vegetables]
print(fridge)

>>

[['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'], ['Beetroot', 'Carrots', 'Capsicum', 'Ginger', 'Cauliflower']]

项目 4:藏宝图

line1 = [" ", " "," "]
line2 = [" ", " "," "]
line3 = [" ", " "," "]
map = [line1, line2, line3]

print("\nHiding your treasure! X marks the spot.")
print("There are three rows and coloumes\n")


postion = input("Where do you want to put the treasure?")

letter = postion[0].lower()

abc = ["a", "b", "c"] #Possiable entry 

letter_index = abc.index(letter) 
#Checking if in "letter" (we entry), that is  there in the list or not 
#This will give us number

number_index = int(postion[1]) - 1 
#Whatever position we entered, -1 because list stars from [0]

map[number_index][letter_index] = "X"

print(f"{line1}\n{line2}\n{line3}")
   


>>


Hiding your treasure! X marks the spot.
There are three rows and coloumes

Where do you want to put the treasure?B3
[' ', ' ', ' ']
[' ', ' ', ' ']
[' ', 'X', ' ']

项目 5:石头剪刀布游戏

import random

rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''


game_images = [rock, paper, scissors]
user_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n"))

if user_choice >= 3 or user_choice < 0: 
    print("Number is Invalid, You lose!")

else:
    print(game_images[user_choice])

    computer_choice = random.randint(0, 2)

    print("Compute Choose:")
    print(game_images[computer_choice])

    if user_choice == computer_choice:
        print ("It's a tie!")
    elif (user_choice == 0 and computer_choice == 2) or \
         (user_choice == 1 and computer_choice == 0) or \
         (user_choice == 2 and computer_choice == 1):
        print ("You win!")
    else:
        print ("You lose!")


>>

What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.
2

    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)

Compute Choose:

    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)

It's a tie!

相关推荐

Kubernetes 核心概念全景图:Pod、Node、Cluster、Control Plane 等

想真正读懂Kubernetes的底层运作,你必须理解它的“权力架构”。Pod是什么?Node是什么?ControlPlane又是做什么的?它们之间有什么关系?怎么协同工作?本篇带你构建一个...

Helm 实战:用 Helm 部署一个 Nginx 应用

这一篇,我们将动手实战:用Helm从零部署一个Nginx应用,并掌握HelmChart的结构和参数化技巧。一、准备环境在开始之前,你需要确保环境中具备以下工具:已部署的Kubernet...

从零开始:如何在 Linux 上搭建 Nginx + Node.js 高性能 Web 服务

在现代互联网服务架构中,Nginx+Node.js已成为轻量级、高性能网站的首选组合。本文将带你从零开始,一步步搭建一个高并发、高可用的Web服务平台,让新手也能轻松掌握生产级部署思路。一、...

NetBox 最新版 4.4.1 完整安装指南

NetBox最新版4.4.1完整安装指南(修正版)by大牛蛙1.系统准备#关闭SELinux和防火墙(仅测试环境)systemctldisable--nowfirewalldse...

Termux 安装 linux 宝塔面板,搭建 Nginx+PHP+Mysql web 网站环境

Termux安装linux宝塔面板,搭建Nginx+PHP+Mysqlweb服务环境,解决启动故障奶妈级教程1.到宝塔面板官网:https://www.bt.cn/new/download...

OpenEuler系统安装Nginx安装配置_openwrt安装nginx

NginxWEB安装时可以指定很多的模块,默认需要安装Rewrite模块,也即是需要系统有PCRE库,安装Pcre支持Rewrite功能。如下为安装NginxWEB服务器方法:源码的路径,而不是编...

多级缓存架构实战:从OpenResty到Redis,打造毫秒级响应系统

在传统的Web架构中,当用户发起请求时,应用通常会直接查询数据库。这种模式在低并发场景下尚可工作,但当流量激增时,数据库很容易成为性能瓶颈。多级缓存通过在数据路径的不同层级设置缓存,可以显著降低数据库...

如何使用 Nginx 缓存提高网站性能 ?

快速加载的站点提供了更好的用户体验并且可以拥有更高的搜索引擎排名。通过Nginx缓存提高你的网站性能是一个有效的方法。Nginx是一个流行的开源web服务器,也可以作为web服务器反向代...

如何构建企业级Docker Registry Server

很多人问我,虚拟机镜像和docker镜像的区别是什么?其实区别非常明显,我们可以通过阅读Dockerfile文件就可以知道这个镜像都做了哪些操作,能提供什么服务;但通过虚拟机镜像,你能一眼看出来虚拟机...

如何解决局域网SSL证书问题?使用mkcert证书生成工具轻松搞定

“局域网里弹出‘不安全’红锁,老板就在身后盯着演示,那一刻只想原地消失。”别笑,九成前端都经历过。自签证书被Chrome标红,客户以为网站被黑,其实只是缺一张被信任的证。mkcert把这事从半小时缩到...

Docker 安全与权限控制:别让你的容器变成“漏洞盒子”

在享受容器带来的轻量与灵活的同时,我们也必须面对一个现实问题:安全隐患。容器并不是天然安全,错误配置甚至可能让攻击者“越狱”入侵主机!本篇将带你从多个层面强化Docker的安全防护,构建真正可放心...

Kubernetes生产级管理指南(2025版)

在云原生技术持续演进的2025年,Kubernetes已成为企业数字化转型的核心引擎。然而,生产环境中的集群管理仍面临基础设施配置、安全漏洞、运维复杂度攀升等挑战。本文将结合最新行业实践,从基础设施即...

云原生工程师日常使用最多的工具和100条高频命令

在云原生时代,工程师不仅要熟悉容器化、编排和服务网格,还要掌握大量工具和命令来进行日常运维与开发。本文将从工具篇和命令篇两个角度,详细介绍云原生工程师每天都会用到的核心技能。一、云原生工程师常...

用 Jenkins 实现自动化 CI/CD_jenkins api自动执行

场景设定(可替换为你的技术栈)语言:Node.js(示例简单,任何语言思路一致)制品:Docker镜像(推送到DockerHub/Harbor)运行环境:Kubernetes(staging...

5款好用开源云笔记虚拟主机部署项目推荐

在个人数据管理与协同办公场景中,开源云笔记项目凭借可自主部署、数据可控的优势,成为众多用户的首选。以下推荐5款适配虚拟主机部署、功能完善的开源项目,附核心特性与部署要点,助力快速搭建专属云笔记系统。...

取消回复欢迎 发表评论: