嗨,我是一名初学者。我面临着一个问题,即如何让我的程序读取 while 循环的 2 个才能正常运行


while userInput in op and userInput != "q":
score += 1
no_words += 1
userInput = input((str(no_words)) + ". ").lower()
while userInput not in op and userInput != "q":
score += 0
no_words += 0
print("Oops! Invalid input")
userInput = input((str(no_words)) + ". ").lower()

我期望当用户给出一个输入时,我的程序将每次读入这两个while循环,以便提供正确的输出。(我正在创建一款游戏,用户需要根据原始单词列出尽可能多的单词。)

例如:极端的

游戏目标:用户能给出的单词越多,得分越高。

你要做的实际上是在循环中嵌套条件。

同样,你也不需要硬编码"+ 0"任何事情。如果它没有改变,您可以简单地省略该行。


userInput = None
while userInput != 'q':
userInput = input((str(no_words)) + ". ").lower()
if userInput in op:
score += 1
no_words += 1
else:
print('Oops! Invalid Input')


编辑:重要的是你不能同时运行两个不同的while循环;第一个在第二个开始的时候结束,直到你掌握了一些更高级的技术。解决方案是找出如何使用单个while循环来访问当时可能发生的所有不同路径。

我想你误解了如何应用while循环。我认为这个解决方案会在你的情况下工作,但是我不完全理解你在做什么,因为这里的一些变量被从你的代码样本中遗漏了。逻辑至少应该可以工作。

while userInput != 'q':
userInput = input((str(no_words)) + ". ").lower()
if userInput in op:
score += 1
no_words += 1
else:
score += 0
no_words += 0

只需要一个while-loop,里面有if-条件。
另外,我还添加了一个列表推导式来检查所有字母是否有效。
这个游戏很有趣。试试下面的代码:

op = 'extreme'
print('Create as many words as possible (repeat letters are allowed) with this string:', op)
score = 0
inputList = []
userInput = ''
while userInput != 'q':
userInput = input('Words created {}:'.format(inputList)).lower()
if all([e in list(op) for e in list(userInput)]) and userInput not in inputList:
score += 1
inputList.append(userInput)
elif userInput != 'q':
print('Oops! Invalid input')

print('Your final score:', score)

预期输出

Create as many words as possible (repeat letters are allowed) with this string: extreme
Words created []: met
Words created ['met']: met
Oops! Invalid input
Words created ['met']: tree
Words created ['met', 'tree']: team
Oops! Invalid input
Words created ['met', 'tree']: q
Your final score: 2

最新更新