问题描述
限时送ChatGPT账号..这是我的代码:
#Choose Report
def chooseReport():
print "Choose a report."
while True:
choice = raw_input("Enter A or B: ")
if choice == 'a' or choice == 'A':
reportA()
break
elif choice == 'b' or choice == 'B':
reportB()
break
else:
continue
当我输入 a
或 b
时,它只是要求我再次输入 A 或 B"
.它没有执行它应该执行的功能.
When I input either a
or b
, it just asks me to "Enter A or B"
again. It doesn't go to the functions its supposed to.
知道这是为什么吗?
推荐答案
首先,您的代码运行良好,最可能的错误是您编写了错误的输入(例如:输入了更多字符).要解决这个问题,您可以在选择中使用 "a" 或在选择中使用 "A"
.但如果它不起作用……请继续阅读.
First, your code works fine, the most probably error is that you are writing a wrong input (e.g: with more characters). To solve that you could use "a" in choice or "A" in choice
. But if it isn't working... keep reading.
似乎 break
不影响 while 循环
,我没有 python 2 所以我不太确定为什么(在 python 3 [更改后raw_input
到 input
和 print
到 print()
] 你的代码工作完美).所以你应该使用 while
的条件来打破它.
It's seems that break
isn't affecting the while loop
, I don't have python 2 so I am not very sure why (in python 3 [after change raw_input
to input
and print
to print()
] your code works perfect). So you should use the condition of the while
to break it.
while True
理论上永远有效,因为每次执行代码时,它都会检查条件 -True
- 并且因为它为真,它会一直循环.
您可以操纵该条件以中断循环(不允许再次执行其代码).
while True
work theorically for ever because each time the code is executed it checks the condition -True
- and because it's true it keeps looping.
You could manipulate that condition in order to break the loop (don't allow execute again its code).
例如你可以使用这个:
#Choose Report
def chooseReport():
print "Choose a report."
allow = True # allow start as True so the while will work
while allow:
choice = raw_input("Enter A or B: ")
if choice.lower().strip() == "a": # This is better. .lower() make "A" > "a", and .strip() delete " a " to "a", and "a/n" to "a".
reportA()
allow = False # allow now is False, the while won't execute again
elif choice.lower().strip() == "b":
reportB()
allow = False # allow now is False, the while won't execute again
# The else is complete redundant, you don't need it
这篇关于“while循环"不破坏(使用 Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论