[英]using function and random numbers
我有个问题:
当程序运行时,它会随机选择一个 1 到 6 之间的数字。(或者任何其他你喜欢的整数——骰子的边数由你决定。)程序将打印出这个数字。 然后它应该询问您是否要再次滚动。 对于这个项目,您需要设置骰子可以产生的最小和最大数量。 对于平均骰子,这意味着最小为 1,最大为 6。您还需要一个函数来随机获取该范围内的一个数字并打印出来。
这是我到目前为止所做的:
import random
x = random.randint(1,6)
print("You roll a die ", x)
new_try = input("\n\n Do you want to roll a die again?")
if str(new_try) == 'yes':
print("You roll a die ", x)
else:
print("Cool game!")
我仍然得到相同的数字:(
我认为您可以做的是每次运行新尝试时设置不同的种子。
您不会第二次更改 x ,而只是再次打印出来,给出相同的结果。 这是固定版本的代码:
import random
x = random.randint(1, 6)
print("You roll a die", x)
new_try = input("\n\n Do you want to roll again? ")
if new_try == 'yes':
x = random.randint(1, 6)
print("You roll a die", x)
else:
print("Cool game!")
如果你想为它使用一个函数,你可以多次执行:
import random
def roll_dice():
x = random.randint(1, 6)
print("Dice was rolled: " + str(x))
try_again = input("Do you want to try again? ")
if try_again == 'yes':
roll_dice()
roll_dice()
x
不是骰子,即random.randint(1,6)
。 所以在x = random.randint(1,6)
, x
存储了之前发生的单个骰子的结果,并且可以在将来的任何时间提供该单个结果。 所以x
存储一个数字,而不是它应该随机生成的事实。
如果你想要一个掷骰子的函数,那么第一次尝试就是def
:
def diceroll():
return random.randint(1,6)
有了这个函数,任何后续的print(diceroll())
(注意它是一个函数调用, diceroll()
)将打印不同卷的结果(并且结果可能只是巧合)。 或者,您可以再次将单个骰子的结果存储为x=diceroll()
,以便将来可以多次重复使用(假设您想将其与用户的猜测进行比较并打印出来)
旁注:从技术上讲,您也可以将函数存储在变量中, x=diceroll
将存储该函数,因此x
不是数字,而是掷骰子的行为,并且必须作为函数调用,例如print(x())
。
如果要在不同时间产生不同的数字,则必须使用种子值。 这里有一个例子来解释:
import random
random.seed( 3 )
print "Random number with seed 3 :", random.random() #will generate a random number
#if you want to use the same random number once again in your program
random.seed( 3 )
random.random()
我不会为你制作程序。 我已经向你解释了这个概念。 现在只需执行它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.