【Python】随机数和 列表 python3随机数
off999 2024-12-20 17:55 16 浏览 0 评论
Python 随机模块方法
randint(a, b):
返回介于 a 和 b 之间(含两者)的随机整数。如果 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!
相关推荐
- 全网第一个讲清楚CPK如何计算的Step by stepExcel和Python同时实现
-
在网上搜索CPK的计算方法,几乎全是照搬教材的公式,在实际工作做作用不大,甚至误导人。比如这个又比如这个:CPK=min((X-LSL/3s),(USL-X/3s))还有这个,很规范的公式,也很清晰很...
- [R语言] R语言快速入门教程(r语言基础操作)
-
本文主要是为了从零开始学习和理解R语言,简要介绍了该语言的最重要部分,以快速入门。主要参考文章:R-TutorialR语言程序的编写需要安装R或RStudio,通常是在RStudio中键入代码。但是R...
- Python第123题:计算直角三角形底边斜边【PythonTip题库300题】
-
1、编程试题:编写一个程序,找出已知面积和高的直角三角形的另外两边(底边及斜边)。定义函数find_missing_sides(),有两个参数:area(面积)和height(高)。在函数内,计算另外...
- Tensor:Pytorch神经网络界的Numpy
-
TensorTensor,它可以是0维、一维以及多维的数组,你可以将它看作为神经网络界的Numpy,它与Numpy相似,二者可以共享内存,且之间的转换非常方便。但它们也不相同,最大的区别就是Numpy...
- python多进程编程(python多进程进程池)
-
forkwindows中是没有fork函数的,一开始直接在Windows中测试,直接报错importosimporttimeret=os.fork()ifret==0:...
- 原来Python的协程有2种实现方式(python协程模型)
-
什么是协程在Python中,协程(Coroutine)是一种轻量级的并发编程方式,可以通过协作式多任务来实现高效的并发执行。协程是一种特殊的生成器函数,通过使用yield关键字来挂起函数的执行...
- ob混淆加密解密,新版大众点评加密解密
-
1目标:新版大众点评接口参数_token加密解密数据获取:所有教育培训机构联系方式获取难点:objs混淆2打开大众点评网站,点击教育全部,打开页面,切换到mobile模式,才能找到接口。打开开发者工具...
- python并发编程-同步锁(python并发和并行)
-
需要注意的点:1.线程抢的是GIL锁,GIL锁相当于执行权限,拿到执行权限后才能拿到互斥锁Lock,其他线程也可以抢到GIL,但如果发现Lock仍然没有被释放则阻塞,即便是拿到执行权限GIL也要立刻...
- 10分钟学会Python基础知识(python基础讲解)
-
看完本文大概需要8分钟,看完后,仔细看下代码,认真回一下,函数基本知识就OK了。最好还是把代码敲一下。一、函数基础简单地说,一个函数就是一组Python语句的组合,它们可以在程序中运行一次或多次运行。...
- Python最常见的170道面试题全解析答案(二)
-
60.请写一个Python逻辑,计算一个文件中的大写字母数量答:withopen(‘A.txt’)asfs:count=0foriinfs.read():ifi.isupper...
- Python 如何通过 threading 模块实现多线程。
-
先熟悉下相关概念多线程是并发编程的一种方式,多线程在CPU密集型任务中无法充分利用多核性能,但在I/O操作(如文件读写、网络请求)等待期间,线程会释放GIL,此时其他线程可以运行。GIL是P...
- Python的设计模式单例模式(python 单例)
-
单例模式,简单的说就是确保只有一个实例,我们知道,通常情况下类其实可以有很多实例,我们这么来保证唯一呢,全局访问。如配置管理、数据库连接池、日志处理器等。classSingleton: ...
- 更安全的加密工具:bcrypt(bcrypt加密在线)
-
作为程序员在开发工作中经常会使用加密算法,比如,密码、敏感数据等。初学者经常使用md5等方式对数据进行加密,但是作为严谨开发的程序员,需要掌握一些相对安全的加密方式,今天给大家介绍下我我在工作中使用到...
- 一篇文章搞懂Python协程(python协程用法)
-
前引之前我们学习了线程、进程的概念,了解了在操作系统中进程是资源分配的最小单位,线程是CPU调度的最小单位。按道理来说我们已经算是把cpu的利用率提高很多了。但是我们知道无论是创建多进程还是创建多线...
- Python开发必会的5个线程安全技巧
-
点赞、收藏、加关注,下次找我不迷路一、啥是线程安全?假设你开了一家包子铺,店里有个公共的蒸笼,里面放着刚蒸好的包子。现在有三个顾客同时来拿包子,要是每个人都随便伸手去拿,会不会出现混乱?比如第一个顾...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python字典遍历 (54)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (60)
- python读取文件夹下所有文件 (59)
- java调用python脚本 (56)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)