Python中if语句后是否必须加else 不改动现有Yahtzee骰子程序
解答结论
Python语法不强制要求if语句必须搭配else分支,你当前的代码不需要做任何修改就能正常运行,完全不会影响现有逻辑。
具体说明
- if分支的本质是「仅当条件成立时,执行块内代码」,条件不成立时解释器会直接跳过整个if块,继续执行后续代码,不会出现语法报错。
- 只有当你需要明确处理「条件不成立」的场景时,才有必要添加else分支。比如你想在没掷出三个相同点数时打印
No match提示,才需要补else块;按照你现在的需求——只在匹配成功时计数、打匹配标记,非匹配场景不需要额外操作,只写if就是最简洁正确的写法,强行加else反而冗余。
你现有可正常运行的代码参考
#Program 2# #create a Yatzhee dice program# import random print("--------------------") print("Yatzhee dice program") print("--------------------") print("") print("Welcome to the Yatzhee Dice Program") print("In this program the dice will get rolled 50 times and at the end we tell you how many matches you got.") print("") # before loop # rolls = 50 total_matches = 0 # --- loop --- for i in range(rolls): #randomise 50 times# die1 = random.randint(1, 6) die2 = random.randint(1, 6)#chooses a number from 1 to 6# die3 = random.randint(1, 6) print(die1, "|", die2, "|", die3) if die1 == die2 == die3:#If all three are the same.# print("****MATCH*****")#If statement inside for-loop so it adds up how many matches there were# total_matches += 1 #increases no. of matches by 1 each time there is a match# #after loop# print("") print("The total number of matches was:", total_matches)#tells user how many matches there were#
小备注:常规Yahtzee规则使用5枚骰子,你当前用3枚属于自定义规则,只要符合你的设计预期就不需要调整。
内容的提问来源于stack exchange,提问作者Harry
相关产品推荐
相关产品推荐

