如何在“更高或更低”的游戏中正确使用随机数。我只是个初学者

时间:2012-06-12 20:42:04

标签: python random input if-statement

以下是代码:

from random import *
numbers = ['0','1','2','3','4','5','6','7','8','9','10']
r1 = choice (numbers)
r2 = choice (numbers)
print("H = HIGHER ,, L = LOWER ,, S = SAME")
print(r1)
a = input()
print(r2)
if r2 == r1 and a == 's':
     print("well done")
if r2 < r1 and a == 'l':
     print("well done")
if r2 > r1 and a == 'h':
     print("well done")
else:
     print("unlucky")

问题是脚本的最后一部分。一切都完美无缺,除了在打印后的脚本末尾(r2)......一切正常,但答案一直在“做得好”和“不幸”之间切换。有时它会说两者。有谁知道问题是什么?我认为这是因为它是随机的简单原因,并且第一个输出(r1)随着我们沿着脚本移动而改变。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

将您的最后两个if更改为elif s(elif表示其他 - 如果):

if r2 == r1 and a == 's':
     print("well done")

elif r2 < r1 and a == 'l':
     print("well done")

elif r2 > r1 and a == 'h':
     print("well done")

else:
     print("unlucky")

现在只有在没有满足其他条件的情况下才会打印“不幸”。

答案 1 :(得分:2)

这是您的计划的完整功能版本:

from random import choice

numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

r1 = choice(numbers)
r2 = choice(numbers)

print("h = HIGHER ,, l = LOWER ,, s = SAME")
print(r1)
a = raw_input()
print(r2)

if r2 == r1 and a == 's':
    print("well done")
elif r2 < r1 and a == 'l':
    print("well done")
elif r2 > r1 and a == 'h':
    print("well done")
else:
    print("unlucky")

我让PEP8友好了。此外,您应该显示h,l和s ...而不是H,L和S,因为针对a的比较器使用小写。要么是这样,要么改变输入值的大小写。另外,请使用raw_input代替常规input

正如@Blorgbeard所提到的,如果你想要每次选择相同的随机数,那么在你致电choice之前加上这个

import random 
random.seed(1)