卡在 while 循环中

时间:2021-03-16 16:50:54

标签: python loops while-loop

我创建了一个 Heads and Tails 程序,它被困在一个选择选项中。 如果选择“y”或“n”,它应该会中断,但它仍然要求按 y 继续或 n 跳过。

逻辑似乎没问题。任何人都可以给我一个提示我做错了什么?

import random 
resp = 'y'
while resp == 'y':
 n = random.randint(0,1)
 if n == 0:
    print('HEADS')
 else:
    print('TAILS')
 resp = str(input("Press y to continue or n to skip )).lower()
  while resp != 'y' or resp != 'n':
     resp = str(input("Press y to continue or n to skip ")).lower()
  if resp == 'n':
     break

2 个答案:

答案 0 :(得分:0)

标准编码遵循DRY 代码。那是DO NOT REPEAT你自己。

看起来你的代码有太多重复的工作。

此外,无需将响应转换为字符串,因为输入函数会将所有内容都转换为字符串,

resp = str(input("Press y to continue or n to skip )).lower()

正确的缩进,应该是4 spaces

import random
while True:
     resp = input("Press y to continue or n to skip : " ).lower()
     if resp == 'n':
        break
     n = random.randint(0,1)
     if n == 0:
        print('HEADS')
     else:
        print('TAILS')

答案 1 :(得分:0)

首先,这里缺少一个引用:

str(input("Press y to continue or n to skip )).lower()

如果我输入y,那么resp != n将为true,如果我输入n,则resp != y将为true。所以只要我输入 y 或 n 它就会循环。

while resp != 'y' or resp != 'n':

所以应该是:

while resp != 'y' and resp != 'n':