我正在为学校做一个基本的石头剪刀代码,但我的elif陈述没有运行。
def player1(x):
while x != 'rock' and x != 'paper' and x != 'scissors':
print("This is not a valid object selection")
x = input("Player 1? ")
def player2(x):
while x != 'rock' and x != 'paper' and x != 'scissors':
print("This is not a valid object selection")
x = input("Player 2? ")
def winner():
player1(input("Player 1? "))
player2(input("Player 2? "))
if player1 == 'rock' and player2 == 'rock':
print('Tie')
elif player1 == 'paper' and player2 == 'paper':
print('Tie')
elif player1 == 'rock' and player2 == 'paper':
print('Player 2 wins')
elif player1 == 'paper' and player2 == 'rock':
print('Player 1 wins')
elif player1 == 'rock' and player2 == 'scissors':
print('Player 1 wins')
elif player1 == 'scissors' and player2 == 'rock':
print('Player 2 wins')
elif player1 == 'paper' and player2 == 'scissors':
print('Player 2 wins')
elif player1 == 'scissors' and player2 == 'paper':
print('Player 1 wins')
elif player1 == 'scissors' and player2 == 'scissors':
print('Tie')
winner()
当我运行此代码时,它会要求播放器1?'并且除了摇滚,纸张或剪刀之外别无他法。然后它继续为player2做同样的事情。但是,这是代码结束的地方,它不会运行我的elif语句并打印哪个玩家获胜。
编辑:已解决。感谢您帮助初学者。我完全忘记返回字符串并将它们分配给变量。
答案 0 :(得分:1)
分配到player1
内的x并不是在做任何事情。函数返回后,将删除分配给x的值。这意味着你丢弃了你的输入!然后,您将函数 player1
与字符串进行比较,这些字符串可能与您的输入相匹配。
调试建议:每当出现控制流问题时,请打印出控制变量。在这里,如果你打印player1,你会看到令人惊讶的东西。
答案 1 :(得分:0)
您的比较:
elif player1 == "rock" and player2 == "rock":
# etc
总是会失败,因为player1和player2都是函数。
相反,您需要从函数返回并将它们分配给变量。让我们在一分钟内完成验证并稍微减少一点。
def choose(prompt):
return input(prompt)
def winner(a, b):
if a == 'rock':
if b == 'rock': return None
elif b == 'paper': return 2
elif b == 'scissors': return 1
elif a == 'paper':
# etc
def play_game():
p1_choice = choose("Player 1: ")
p2_choice = choose("Player 2: ")
return winner(p1_choice, p2_choice)
请注意,对于这些elif链来说,一个看起来更漂亮的技巧是将它们放在字典中并将索引编入索引。
RESULT_DICT = {"rock": {"rock": None,
"paper": 2,
"scissors": 1},
"paper": {"rock": 1,
"paper": None,
"scissors": 2},
"scissors": {"rock": 2,
"paper": 1,
"scissors": None}}
def winner(a, b):
return RESULT_DICT[a][b]