import random
for i in range(3):
user = str(input("Please enter your choice: "))
if (random.randrange(3)) == 0 :
print("Computer chooses Rock")
if user == "scissors" :
print("computer wins")
elif user == "paper" :
print("player wins")
else :
print("tie")
elif (random.randrange(3)) == 1 :
print("Computer chooses Paper")
if user == "rock" :
print("computer wins")
elif user == "scissors" :
print("player wins")
else :
print("tie")
elif (random.randrange(3)) == 2 :
print("Computer chooses Scissors")
if user == "paper" :
print("computer wins")
elif user == "rock" :
print("player wins")
else :
print("tie")
这里的格式有点奇怪(以前没有使用过这个网站)。我不知道原因,但我不知道为什么这段代码有时会跳过结果。如果有人可以提供帮助,那就太好了。
这是运行几次时产生的结果
enter your choice: scissors
Computer chooses Rock
computer wins
enter your choice: scissors
Computer chooses Scissors
tie
enter your choice: scissors
Computer chooses Rock
computer wins
================================ RESTART ================================
Please enter your choice: scissors
Please enter your choice: rock
Computer chooses Rock
tie
Please enter your choice: rock
Computer chooses Rock
tie
我不明白为什么它会跳过结果。似乎是随机发生的
最佳答案
你不应该使用 random.randrange(3)
三次。这可能例如给你以下数字:1、2,然后是 0。所以执行的代码是:
if (1 == 0):
...
elif (2 == 1):
...
elif (0 == 2):
...
并且不会执行 if 语句的任何条件块。
而是做这样的事情:
computerChoice = random.randrange(3)
...
if computerCoice == 0:
...
elif computerChoice == 1:
...
elif computerChoice == 2:
...
else
raise Exception("something is definitively wrong here")
关于python - 石头剪刀布,跳过结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27080157/