Skip to main content
 首页 » 编程设计

python之无法结束多 if 语句以捕获所有

2025年05月04日12sky-heaven

我目前正在尝试用 Python 编写我的第一个程序/应用程序,方法是创建一个工具供我的合作伙伴在我们玩纸牌游戏时使用。我刚刚开始认真学习编程,所以这可能是我错过的一个菜鸟错误,但我似乎无法通过输入捕捉到“其他任何东西”来转移用户的 react 。

这是我的代码:

def counting_up (): 
round_total = 0 
while True : 
    global game_level 
    cards = input("Enter Card: \n") 
    if cards.upper() == "A" or cards == "2" : 
        round_total += 20 
    if cards == "3" : 
        round_total += 3 
    if cards == "4": 
        round_total += 4 
    if cards == "5" : 
        round_total += 5 
    if cards == "6" :  
        round_total += 6 
    if cards == "7" : 
        round_total += 7 
    if cards == "8" : 
        round_total += 8 
    if cards == "9" : 
        round_total += 9 
    if cards == "10" or cards.upper() == "J" or cards.upper() == "Q" or cards.upper() == "K" : 
        round_total += 10 
    if cards == "0" :  
        game_level += 1 
    if cards.upper() == "END" : 
        game_state = 1 
        break 
    else :  
        print (f"{cards}, is not a valid value, please enter a valid value!") 
 
print ("Your score this round was " + str(round_total)) 
return round_total 

在测试时,它似乎在得出其无效值的结论之前没有经过先前的逻辑检查。请注意,这整个功能都按预期工作,如果我在最后删除 else: 语句,它也会正常工作。 python 中是否有类似于 java 中的 case 语句的东西可以工作?

提前致谢

请您参考如下方法:

在同一层有多个if 语句,python 将检查每个条件语句。如果您希望它在满足前一个语句时忽略后续语句,请使用 elif:

def counting_up(game_state, game_level, round_total=0): 
    """Request and add input card face value to score repeatedly till end.""" 
    while True: 
        cards = input("Enter Card: \n") 
        if cards.upper() == "END": 
            game_state = 1; break 
        elif cards == "0":  
            game_level += 1 
        elif cards.upper() in ("A", "2"): 
            round_total += 20 
        elif cards.isnumeric(): 
            round_total += int(cards) 
        elif cards.upper() in ("J","Q","K"): 
            round_total += 10 
        else:  
            print(f"{cards}, is not a valid value, please enter a valid value!") 
 
    print(f"Your score this round was {round_total}.") 
    return round_total