简体   繁体   English

调用自身内部的函数以使用if语句检查if输入,如果if语句永不中断且无限循环

[英]Calling a function inside itself to check for wrong input with if statement, if statement never breaks and loops indefinitely

I'm writing a coin toss function that only accepts "h" and "t" as input. 我正在写一个抛硬币函数,仅接受“ h”和“ t”作为输入。

To do this I use an if statement to check if the input is "h", and one nested in it to check if it is "t". 为此,我使用一条if语句来检查输入是否为“ h”,并在其中嵌套一个以检查其是否为“ t”。

If both conditions aren't met, it calls the function again. 如果两个条件都不满足,它将再次调用该函数。

The problem is that even if the first input is "t" or "h", it still calls the function no matter what I do? 问题是,即使第一个输入是“ 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()

Instead of calling the function again, just stick that part in a while loop with the following condition: 无需再次调用该函数,只需将该部分粘在while循环中并满足以下条件:

player_coin = None
while player_coin not in ('h', 't'):
    player_coin = raw_input("Choose heads (h) or tails (t)!: ").lower()

I used x in tuple instead of multiple checks, and made sure you're invoking lower() since it isn't in your example. x in tuple使用x in tuple而不是多次检查,并确保您正在调用lower()因为它不在您的示例中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM