[英]Try/except - how to continue
So there is a part in my program where I ask the user to enter a number.所以我的程序中有一部分要求用户输入一个数字。 I use try/exept as:我使用 try/exept 作为:
limits=True
while limits:
try:
limits=int(input("Put your limit:"))
return limits
except(ValueError):
print("Thats not a number!")
My question is if the user does put in a number how can I continue to use the variable limits
that contains the users input later on in my code?我的问题是,如果用户确实输入了一个数字,我该如何继续使用包含用户稍后在我的代码中输入的变量limits
?
After that the try/except part runs and when the user to put in a number it just stops, doesn't continue with the code.之后 try/except 部分运行,当用户输入一个数字时,它会停止,不会继续执行代码。
You do not need limits
at all in your code:您的代码中根本不需要limits
:
def get_limit():
while True:
try:
return int(input("Enter your limit: "))
except(ValueError):
print("That's not a number!")
To use the value later in your code, just assign the return value from the function to some variable:要稍后在代码中使用该值,只需将函数的返回值分配给某个变量:
limit = get_limit()
What is this I don't even.这是什么我什至不知道。
You're trying to make limits both a boolean for the while loop, and an integer for something else.您正在尝试为 while 循环设置一个布尔值,并为其他内容设置一个整数。
Try one of these methods:尝试以下方法之一:
tl;dr replace while limits with while true . tl;dr 用while true替换while 限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.