Python随机掷骰子运势程序每次仅输出首个结果问题求助
错误排查
- 变量名误用:生成的1-6随机数存储在变量
answers中,但后续所有条件判断都使用了初始赋值为True的变量answer。Python中布尔值True等价于整数1,所以每次都会触发第一个answer == 1的分支,输出固定结果。 - 未定义函数调用:代码末尾的
roll()没有提前定义,程序运行到此处会抛出名称错误。 - 循环条件可优化:
while answer的写法等价于死循环,可直接简化为while True更易读。
修正后代码
import random import sys while True: question = input("Roll the di to get your fortune (press enter directly to exit): ") if question == "": sys.exit() answer = random.randint(1,6) if answer == 1: print("You will get a new friend. ") elif answer == 2: print("You will go to disneyland. ") elif answer == 3: print("You will receive kindess.. ") elif answer == 4: print("Your will get a dog. ") elif answer == 5: print("You will suffer. ") elif answer == 6: print("You will have bad luck. ")
内容的提问来源于stack exchange,提问作者Supreme Gucci
相关产品推荐
相关产品推荐

