python中鼠标响应事件_要求用户输入直到Python中的有效响应

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

推荐的帖子

翻译自: https://www.includehelp.com/python/asking-the-user-for-input-until-a-valid-response-in-python.aspx

python中鼠标响应事件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值