Python只有在范围内才能输入 [英] Python excepting input only if in range

查看:179
本文介绍了Python只有在范围内才能输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从用户那里得到一个数字,只有在一定范围内的输入才能使用。

Hi I want to get a number from user and only except input within a certain range.

以下内容似乎正常工作,但我是一个noob并且认为作品无疑是一个更优雅的例子,只是想不要陷入坏习惯!

The below appears to work but I am a noob and thought whilst it works there is no doubt a more elegant example... just trying not to fall into bad habits!

我注意到的一件事是当我运行程序CTL + C不会让我脱离循环,而是引发异常。

One thing I have noticed is when I run the program CTL+C will not break me out of the loop and raises the exception instead.

while True:
  try:
    input = int(raw_input('Pick a number in range 1-10 >>> '))
    # Check if input is in range
    if input in range(1,10):
      break
    else:
      print 'Out of range. Try again'
  except:
    print ("That's not a number")



All help greatly appreciated.

推荐答案

Ctrl + C引发 KeyboardInterruptException ,您的尝试...除了块捕获这个:

Ctrl+C raises a KeyboardInterruptException, your try … except block catches this:

while True:
   try:
       input = int(raw_input('Pick a number in range 1-10 >>> '))
   except ValueError: # just catch the exceptions you know!
       print 'That\'s not a number!'
   else:
       if 1 <= input < 10: # this is faster
           break
       else:
           print 'Out of range. Try again'

一般来说,你应该只是捕捉你期望发生的异常(所以没有副作用出现,像你的Ctrl + C问题)。另外你也应该保持 try ...除了块以外,尽可能的短。

Generally, you should just catch the exceptions you expect to happen (so no side effects appear, like your Ctrl+C problem). Also you should keep the try … except block as short as possible.

这篇关于Python只有在范围内才能输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆