(Python/PythonAnywhere(我的代码现在:
while True:
try:
Question = input("How are you? (Please answer with: ""Good, or Bad"")");
if Question == ("Good"):
print("Good to hear!");
if Question == ("Bad"):
print("I'm Sorry");
if Question == ("Bad"):
print("Sorry to hear buddy")
break;
except:
if Question == (""):
print("Please type: Good, or Bad")
这是后面的内容:(代码不想包括这个(
name = input("Enter your name: ")
print("Hello", name + "!");
问题是,(据我所知(断裂与印刷相混淆;对不起"当循环中断时,它还会停止打印,继续询问用户名。我试过改变它的打印块,但没有成功,然后我试着改变我缩进的内容,但也无济于事。如果有人知道如何解决这个问题,我很想知道。
(附言:我是一个初学者,所以如果这是一个超级简单的解决方案,不要对我开枪。我只是想学习python,哈哈(
您需要正确缩进,以便独立测试每个条件。
不需要try/except
,因为没有任何东西会引发任何条件(这通常在验证数字输入时使用,因为如果输入不是数字,int()
和float()
会引发异常(。
当他们输入一个有效的选项时,您希望打破循环。
while True:
Question = input("How are you? (Please answer with: ""Good, or Bad"")");
if Question == "Good":
print("Good to hear!");
break
if Question == "Bad":
print("I'm Sorry");
break
print("Please type: Good, or Bad")
您可以阅读Python控制流文档"断裂";,就像它的名字一样,打破循环并完成循环。如果不想看到任何操作,可以使用pass
,也可以使用continue
来推进下一次迭代。
continue
和pass
之间的区别在于循环的类型。例如:
l = [1, 2, 3, 4, 5]
for i in l:
if i > 3:
pass
print(i) # output will be 1 2 3 4 5
让我们用continue:试试这个功能
l = [1, 2, 3, 4, 5]
for i in l:
if i > 3:
continue
print(i) # output will be 1 2 3
总之,您可以通过两种方式使循环工作:
继续:完成循环,不要继续执行下面的代码。
pass:什么都不做,继续循环,继续执行下面的代码。