21点问题:下面的代码不运行else语句,而是再次迭代elif条件

问题描述 投票:-1回答:1
def blackjack(a,b,c):
    nums = (a,b,c)
    for (nums) in range(1,21):
        if (a+b+c)<=21:
            return (a+b+c)
        if (a+b+c)>21 & (a==11 or b==11 or c == 11):
            return(a+b+c-10)
        else:
            return('BUST')
python blackjack
1个回答
0
投票

如果有括号,请在第二个语句中用第一句括起来:

def blackjack(a,b,c):
    nums = (a,b,c)
    for (nums) in range(1,21):
        if (a+b+c)<=21:
            return (a+b+c)
        if ((a+b+c)>21) & (a==11 or b==11 or c == 11): #fixed line
            return(a+b+c-10)
        else:
            return('BUST')  

更有效的方法是使用and运算符。还要考虑使用if-elif-else,因为第一个和第二个if语句不可能同时为True。

找到下面的固定代码:

def blackjack(a,b,c):
    nums = (a,b,c)
    for (nums) in range(1,21):
        if (a+b+c)<=21:
            return (a+b+c)
        elif (a+b+c)>21 and (a==11 or b==11 or c == 11):
            return(a+b+c-10)
        else:
            return('BUST')

© www.soinside.com 2019 - 2024. All rights reserved.