使用python,我必须为学校创建一个用户在电脑上玩的石头剪刀游戏。计算机的选择也必须是随机的。当我尝试运行此代码时,它表示存在语法错误但不是它的位置。有人可以帮忙吗?
import random
print("Welcome to rock paper scissors.")
player = False
while player == False:
print(" ")
print("Press 1 for Rock")
print("Press 2 for Paper")
print("Press 3 for Scissors")
User = int(input("Rock, Paper or Scissors?"))
Com = random.randrange(1,3)
if (User == 1) and (Com == 1):
player = False
print("Its a draw!")
elif (User == 2) and (Com == 1):
player = True
print("You win!")
elif (User == 3) and (Com == 1):
player = True
print("You lose!")
elif (User == 1) and (Com == 2):
player = True
print("You lose!")
elif (User == 2) and (Com == 2):
player = False
print("Its a draw!")
elif (User == 3) and (Com == 2):
player = True
print("You win!")
elif (User == 1) and (Com == 3):
player = True
print("You win!")
elif (User == 2) and (Com == 3):
player = True
print("You lose!")
elif (User == 3) and (Com == 3):
player = False
print("Its a draw! You both entered scissors.")
else:
print("Make sure to enter a number from 1 - 3")
答案 0 :(得分:2)
看这里:
if (User == 1) and (Com == 1):
player = False
print("Its a draw!")
elif (User == 2) and (Com == 1):
player = True
print("You win!")
print("Its a draw!")
的打印声明不属于if
。你不能拥有任何“松散”的东西。在if
和elif
之间。
此外,您的导入是缩进的,但我认为这是格式错误。
它会修复您的错误,但要注意您的命名约定并未对代码进行过多说明。
答案 1 :(得分:0)
就像@jedruniu所说,你的缩进不正确。我还冒昧地清理你的代码,这样就不那么容易混淆了:
import random
print("Welcome to rock paper scissors.")
draw = True
while draw:
print()
print("Press 1 for Rock")
print("Press 2 for Paper")
print("Press 3 for Scissors")
User = int(input("Rock, Paper or Scissors?"))
Com = random.randint(1,3)
if User == Com:
print("Its a draw!")
else:
draw = False #so it doesn't repeat
if (User == 2) and (Com == 1):
print("You win!")
elif (User == 3) and (Com == 1):
print("You lose!")
elif (User == 1) and (Com == 2):
print("You lose!")
elif (User == 3) and (Com == 2):
print("You win!")
elif (User == 1) and (Com == 3):
print("You win!")
elif (User == 2) and (Com == 3):
print("You lose!")
else:
print("Make sure to enter a number from 1 - 3")