我正在练习和学习Python,我有这个想法,将if, else语句与输入合并,但它不起作用。所以,我尝试了break, continue和except命令。
name = input("Hello! What's your name?" )
print("Hello," + name + "!")
age = int(input("How old are you? "))
while age <= 13 or age >= 55:
if age < 13:
print("You are too young!")
continue
if age >= 55:
print("You are too old!")
continue
else:
print("Welcome!")
continue
why = input("Why are you here? ")
print("Welcome!")
所以,我试着去当一个人超过55岁或13岁以下,它会把他们从输入中弹出。但是,当我尝试它时,它只是无限地打印print。
name = input("Hello! What's your name?" )
print("Hello," + name + "!")
age = int(input("How old are you? "))
while age <= 13 or age >= 55:
if age < 13:
print("You are too young!")
break
if age >= 55:
print("You are too old!")
break
else:
print("Welcome!")
continue
why = input("Why are you here? ")
print("Welcome!")
这是另一个,我试着调整它。但事实是,我试着休息一下。它完成了打印,但只是继续执行命令。
有人能给我解释一下为什么会发生这种情况以及如何解决它吗?
我可以发现两个主要问题
- 您应该将第二个
if
替换为elif
语句 - 最后两行没有缩进
对于第一个问题,两个if
语句都可能运行
age = 12
if age < 13: # This is true
print("You are too young!")
break
if age >= 55: # This is false
print("You are too old!")
break
else: # But this will also run
print("Welcome!")
continue
您可以通过将其替换为elif
age = 12
if age < 13: # This is true
print("You are too young!")
break
elif age >= 55: # This won't run
print("You are too old!")
break
else: # This also won't run
print("Welcome!")
continue
(我应该注意,因为每个if
中都有break
语句,所以代码永远不会到达第二个if语句。)
第二个问题来自于Python非常强调制表符的事实。例如,
while True:
print("Hello")
print("World!") # Un-indented code means it's not part of the `while` loop
只会一遍又一遍地打印Hello
。与此同时,
while True:
print("Hello")
print("World!")
将永远打印Hello World!
。将最后两行缩进一个制表符将把语句放入while
循环,这应该可以解决您的问题。希望这对你有帮助!
继续和中断说明
因此,continue
在循环中使用,并将进入循环的下一次迭代(跳过continue
关键字下面的任何其他指令)。这里你使用的是while
循环,因为你没有任何更新age
值的条件,循环将继续重复(无限),因为没有更新使条件(age <= 13 or age >= 55
)为假来终止循环。
break
用于停止循环中的进一步迭代。
你的while
循环是必要的,因为你只检查一次age
的值。
建议使用@Steggy的推荐
if age < 13: # This is true
print("You are too young!")
break
elif age >= 55: # This won't run
print("You are too old!")
break
else: # This also won't run
print("Welcome!")
continue
调试第二段代码
用户输入年龄值小于13:它将打印语句too young
和break
语句将帮助退出while
循环
用户输入年龄值等于13:第一个和第二个if块不满足条件,因此它将运行else块,它将打印welcome,通过执行continue
,您将移动到while循环的下一次迭代. 因此,这个else块一次又一次地运行而while循环趋于无穷大原因你的年龄值是固定的. 你可以把age输入放到else块中这样用户就可以再次输入或者你可以使用break就像你在前两个if中使用的
用户输入age值大于等于55:如果block和break语句帮助终止while循环,它将第二个运行。
如果你的年龄是固定的,我不认为while循环是必要的,你可以直接doif elif..
如果你的年龄不固定。那么你应该在while循环中接受输入。
while True:
# This will take input until age input is less than 13 or age is greater than or equal to 55.
age = int(input("How old are you? "))
if age < 13:
print("You are too young!")
break
elif age >= 55:
print("You are too old!")
break