标签:返回 循环 span python练习题 函数 简介 orm source 知识
标签: Python Python练习题 Python知识点
答案:
import random
def guess_number():
true_num = random.randint(1, 100)
user_num = int(input("请输入一个整数:"))
count = 1
while true_num != user_num:
if true_num > user_num:
print("太小了,请重新输入!")
elif true_num < user_num:
print("太大了,请重新输入!")
count += 1
user_num = int(input("请输入一个整数:"))
print("恭喜您,您猜对了!您一共猜了%d次" % count)
guess_number()
Python标准库中的random函数,可以生成随机浮点数、整数、字符串,甚至帮助你随机选择列表序列中的一个元素,打乱一组数据等。
In [2]: import random
In [3]: random.random()
Out[3]: 0.6935051182120364
In [26]: random.uniform(0, 100)
Out[26]: 26.977426505683276
In [28]: random.randint(1,2)
Out[28]: 2
In [29]: random.randint(1,2)
Out[29]: 1
参数为列表时:
In [31]: random.choice([1,2,3])
Out[31]: 3
In [32]: random.choice([1,2,3])
Out[32]: 1
参数为字符串时:
In [38]: random.choice("i am a bad boy")
Out[38]: ‘y‘
In [39]: random.choice("i am a bad boy")
Out[39]: ‘b‘
参数为元祖时:
In [41]: random.choice((1,3,7,4))
Out[41]: 1
In [42]: random.choice((1,3,7,4))
Out[42]: 7
In [49]: list = [1,2,3,4]
In [50]: random.shuffle(list)
In [51]: list
Out[51]: [4, 2, 1, 3]
In [58]: b = (9,9,9,1,2)
In [59]: random.sample(b, 2)
Out[59]: [9, 1]
In [60]: random.sample(b, 2)
Out[60]: [1, 9]
In [61]: random.sample(b, 2)
Out[61]: [1, 9]
In [62]: random.sample(b, 2)
Out[62]: [1, 9]
In [63]: random.sample(b, 2)
Out[63]: [2, 9]
In [64]: list = [1,2,3,5,7,94,2]
In [65]: random.sample(list, 3)
Out[65]: [1, 5, 7]
In [66]: random.sample(list, 3)
Out[66]: [2, 2, 5]
In [67]: random.sample("i am a bad boy", 3)
Out[67]: [‘ ‘, ‘a‘, ‘b‘]
In [68]: random.sample("i am a bad boy", 3)
Out[68]: [‘a‘, ‘y‘, ‘b‘]
random.randint(a, b) # 随机返回闭区间 [a, b] 范围内的整数值
numpy.random.randint(a, b) # 随机返回开区间 [a, b) 范围内的整数值
In [69]: random.randint(0,1)
Out[69]: 0
In [70]: random.randint(0,1)
Out[70]: 1
In [71]: numpy.random.randint(0,1)
Out[71]: 0
In [72]: np.random.randint(0,1)
Out[72]: 0
PYTHON练习题 二. 使用random中的randint函数随机生成一个1~100之间的预设整数让用户键盘输入所猜的数。
标签:返回 循环 span python练习题 函数 简介 orm source 知识
原文地址:https://www.cnblogs.com/halooyan/p/9011839.html