python3 中的掷骰子重复问题

Dice roller repeat issue in python3

总的来说,我对编程还很陌生,并且在过去一周左右的时间里一直在学习 python3。我尝试构建一个骰子滚轮并 运行 在询问用户是否要重复滚轮或结束程序时遇到问题。

import random as dice

d100 = dice.randint(1,100)
d20 = dice.randint(1,20)
d10 = dice.randint(1,10)
d8 = dice.randint(1,8)
d6 = dice.randint(1,6)
d4 = dice.randint(1,4)
d2 = dice.randint(1,2)

repeat = 'Y'
while repeat == 'Y' or 'y' or 'yes' or 'Yes':
    roll = (input('What would you like to roll? A d100, d20,  d10, d8, d6, d4, or d2?:'))
    quantity = (input('How many would you like to roll?'))
    quantity = int(quantity)
    if roll == 'd100':
        print('You rolled a: ' + str(d100 * quantity) + '!')

    elif roll == 'd20':
        print('You rolled a: ' + str(d20 * quantity) + '!')

    elif roll == 'd10':
        print('You rolled a: ' + str(d10 * quantity) + '!')

    elif roll == 'd8':
        print('You rolled a: ' + str(d8 * quantity) + '!')

    elif roll == 'd6':
        print('You rolled a: ' + str(d6 * quantity) + '!')

    elif roll == 'd4':
        print('You rolled a: ' + str(d4 * quantity) + '!')

    elif roll == 'd2':
        print('You rolled a: ' + str(d2 * quantity) + '!')        

    else:
        print('That is not an available die! Please select a die.')

    repeat = input('Would you like to continue?: ')
    if repeat == 'yes' or 'Y' or 'y' or 'Yes':
        continue

截至目前,无论为 repeat 变量输入什么,它始终会继续,即使它不是“yes”、“Y”、“y”或“Yes”。我确定答案很简单,就在我面前,但我很难过!提前致谢!

这是一个优先级问题:repeat == 'Y' or 'y' or 'yes' or 'Yes' 被解释为 (repeat == 'Y') or 'y' or 'yes' or 'Yes' 然后它会尝试检查 'y' 是否算作 true,确实如此(它是一个非空字符串).

你要的是while repeat in ('Y', 'y', 'yes', 'Yes'):

顺便说一句,你不需要在循环结束时使用 if 语句,因为如果 repeat 不是 'Y',它会自动退出,'y''yes''Yes'

两件事

continue表示走到循环的最前面(然后检查是否重新进入),不保证会再次循环。将它命名为 skip 可能更好,因为它的真正意思是“跳过本次迭代的其余部分”。因此你不需要 if ... continue 因为你已经在迭代结束了。

真正的循环控制是while。您犯了一个常见的错误,即假设 Python 可以将那些 or 运算符分组为与 == 相反的一组选项。它不能。只有第一个字符串与 repeat 进行比较,其他字符串被视为单独的条件。一个字符串本身就是 True 只要它不为空。因此 Python 读作

while repeat is 'Y', or 'y' is not empty, or 'Yes' is not empty, or 'yes' is not empty

由于所有这三个字符串在定义上都不为空,因此 repeat 是否为 'Y' 并不重要,整个条件将始终为 True.

做多个选项相等的方法是

while repeat in ('Yes', 'yes', 'Y', 'y')

这意味着 repeat 必须出现在该选项列表中。

请注意,您可以通过规范化或 casefolding 重复来简化。

while repeat.upper() in ('Y', 'YES')

或者更简单更不严格

while repeat.upper().startswith('Y')

您还应该去除 repeat 以进一步消除用户错误的空格:

while repeat.strip().upper().startswith('Y')

然后您开始获得用户端循环的最佳实践:)