[英]Calling a function inside itself to check for wrong input with if statement, if statement never breaks and loops indefinitely
我正在写一个抛硬币函数,仅接受“ h”和“ t”作为输入。
为此,我使用一条if语句来检查输入是否为“ h”,并在其中嵌套一个以检查其是否为“ t”。
如果两个条件都不满足,它将再次调用该函数。
问题是,即使第一个输入是“ t”或“ h”,无论我做什么,它仍会调用该函数?
def coin_flip():
player_coin = raw_input("Choose heads (h) or tails (t)!: ").lower
if player_coin != "h":
if player_coin != "t":
coin_flip()
coin = randint(1, 2)
if coin == 1:
coin = "h"
else:
coin = "t"
if player_coin == coin:
print "You won the coin toss! You get to go first!"
player_turn()
else:
print "You guessed the wrong answer! The Computer goes first!"
comp_turn()
无需再次调用该函数,只需将该部分粘在while
循环中并满足以下条件:
player_coin = None
while player_coin not in ('h', 't'):
player_coin = raw_input("Choose heads (h) or tails (t)!: ").lower()
我x in tuple
使用x in tuple
而不是多次检查,并确保您正在调用lower()
因为它不在您的示例中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.