![](/img/trans.png)
[英]I'm trying to make a user input dictionary for extra credit in my class and I can't figure out how to properly end the program
[英]Hi, I'm a beginner coder. I'm facing a problem of figuring out how do I make my program read 2 of while loops in order to function properly
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 循环,以提供正确的 output。(我正在构建一个游戏,用户需要列出尽可能多的单词原词。)
例如:极端
游戏目标:用户能够给出的单词越多,得分就越高。
我认为您误解了如何应用 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
您要做的实际上是将条件嵌套在循环中。
此外,您永远不需要在“+ 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 循环来访问当时可能发生的所有不同路径。
只需要 1 个 while 循环,里面有 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)
预计 output
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.