我目前正在尝试通过创建一个供我的伴侣在玩纸牌游戏时使用的工具,用Python编写我的第一个程序/应用程序。我刚刚开始认真学习编程知识,所以这可能是我错过的菜鸟错误,但是我似乎无法通过输入捕捉“其他”信息来转移用户响应。
这是我的代码:
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语句类似的东西可以工作吗?
预先感谢
答案 0 :(得分:4)
在同一级别有多个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
答案 1 :(得分:2)
只有第一个'if'应该是'if',其余的'if'语句应替换为'elif'(else if)语句。
答案 2 :(得分:2)
“ else”总是检查最新的“ if”,然后求值。因此,如果仅输入“ END”而没有break语句,则程序将不会转到else语句。因此,您输入的除“ END”外的所有内容都会将结果与else语句的结果一起打印。
因此,对于第一个“ if”语句以外的语句,请使用“ elif”,以便检查条件。如果满意,则打印结果,否则将移至下一条语句
答案 3 :(得分:1)
您可以使用dict
def counting_up ():
round_total = 0
while True :
global game_level
cards = input("Enter Card: \n")
card_dict = {'A':20,'2':20,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}
if cards.upper() in card_dict.keys():
round_total += card_dict[cards.upper()]
elif cards == "0" :
game_level += 1
elif 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