对编码非常陌生,并试图自学。我正在尝试编写一段简单的代码来掷各种类型的典型骰子。我尝试使用 while 循环,以便可以连续多次使用它,而不必为每次掷骰子重新运行程序。为了决定是继续循环还是中断,我使用了字符串输入,其中 y 继续,n 中断。
我在循环中使用了以下代码:
from random import randint
print('Hello, and welcome to Rowan\'s Dice Set')
continuation = input('Would you like to start? (y/n)')
while continuation == 'Y' or 'y':
dice_type = input('What kind of dice would you like to roll? Please type D20, D12, D10, D8, D6, D4 or D2: ')
if dice_type == "D20" or "d20":
print(randint(1,20))
elif dice_type == "D12" or "d12":
print(randint(1,12))
elif dice_type == "D10" or "d10":
print(randint(1,10))
elif dice_type == "D8" or 'd8':
print(randint(1,8))
elif dice_type == "D6" or 'd6':
print(randint(1,6))
elif dice_type == "D4" or 'd4':
print(randint(1,4))
elif dice_type == "D2" or 'd2':
print(randint(1,2))
else:
print('invalid selection')
print ('thanks')
continuation = input('would you like to continue?(y/n)')
if continuation == 'n' or 'N':
break
我的目标是让它继续循环,直到他们在循环结束时将延续变量更新为 n 或 N。然而,无论我最后输入什么,循环都会中断,即使既没有输入“n”也没有输入“N”
关于如何让代码在选择 y 或 Y 时循环回 dice_type 输入的任何建议都将是伟大的:))
您的表情,例如,
continuation == 'Y' or 'y':
没有做你认为他们正在做的事情。这并不测试
continuation
是否等于 'Y'
或 continuation
等于 'y'
,它只是测试其中第一个,并且表达式将 'y'
本身计算为 True
。您需要明确执行以下操作:
while continuation == 'Y' or continuation == 'y':
...
if continuation == 'n' or continuation == 'N':
upper
方法来确保它是大写的,例如:
while continuation.upper() == 'Y':
...
if continuation.upper() == 'N':
或者,您可以测试延续性是否包含在可接受值的列表中,例如,
while continuation in ['Y', 'y']:
...
if continuation in ['N', 'n']: