python中鼠标响应事件
Question:
题:
We want to input age which should be greater than 18 and less than 51, gender which should be either "Male" or "Female". If the user inputs an invalid value, the program should ask again for the input.
我们要输入的年龄应大于18岁且小于51岁,性别应为“男性”或“女性”。 如果用户输入了无效值,则程序应再次要求输入。
To solve this question, take the input in an infinite loop (using while True) and when the value is valid, terminate the loop (using break keyword). To handle value errors while reading an integer value – use the try-except block and continue the program's execution (using continue keyword) to the loop to read it again.
要解决此问题,请将输入置于无限循环中( 在True时使用),并在值有效时终止循环(使用break关键字 )。 要在读取整数值时处理值错误 ,请使用try -except块,并继续执行程序(使用continue关键字 )到循环中以再次读取它。
要求用户输入直到有效响应的Python程序 (Python program for asking the user for input until a valid response)
# input age
while True:
try:
age = int(input("Enter age: "))
if age>18 and age<51:
print("Age entered successfully...")
break;
else:
print("Age should be >18 and <51...")
except ValueError:
print("Provide an integer value...")
continue
# input gender
while True:
try:
gender = input("Enter gender: ")
if gender == "Male" or gender == "Female":
print("Gender entered successfully...")
break;
else:
print("Gender should be either Male or Female")
except:
continue
# print age and gender
print("Age is:", age)
print("Gender is:", gender)
Output
输出量
Enter age: 12.5
Provide an integer value...
Enter age: Thirty Two
Provide an integer value...
Enter age: 78
Age should be >18 and <51...
Enter age: 32
Age entered successfully...
Enter gender: I am Male
Gender should be either Male or Female
Enter gender: Don't know
Gender should be either Male or Female
Enter gender: Male
Gender entered successfully...
Age is: 32
Gender is: Male
Recommended posts
推荐的帖子
Asking the user for integer input in Python | Limit the user to input only integer value
How to get the hexadecimal value of a float number in python?
Convert an integer value to the string using str() function in Python
Convert a float value to the string using str() function in Python
Taking multiple inputs from the user using split() method in Python
翻译自: https://www.includehelp.com/python/asking-the-user-for-input-until-a-valid-response-in-python.aspx
python中鼠标响应事件