Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python,仅在范围内时输入除外_Python_Error Handling_User Input - Fatal编程技术网

Python,仅在范围内时输入除外

Python,仅在范围内时输入除外,python,error-handling,user-input,Python,Error Handling,User Input,嗨,我想从用户那里得到一个数字,除了在一定范围内的输入 下面这句话似乎很管用,但我是一个傻瓜,我认为在它起作用的同时,毫无疑问还有一个更优雅的例子。。。只是尽量不要养成坏习惯 我注意到的一件事是,当我运行程序CTL+C时,它不会使我脱离循环,而是引发异常 while True: try: input = int(raw_input('Pick a number in range 1-10 >>> ')) # Check if input is in rang

嗨,我想从用户那里得到一个数字,除了在一定范围内的输入

下面这句话似乎很管用,但我是一个傻瓜,我认为在它起作用的同时,毫无疑问还有一个更优雅的例子。。。只是尽量不要养成坏习惯

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

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")

非常感谢您的帮助。

您的代码中有几项需要改进

(1) 最重要的是,仅仅捕获一个通用异常不是一个好主意,您应该捕获一个您正在寻找的特定异常,并且通常尽可能少的
try
-块

(2) 而且

最好编码为

  if 1 <= input < 10:
如果1Ctrl+C引发a,您的
try…除了
块捕获以下内容外:

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'
为True时:
尝试:
input=int(原始输入('Pick a number in range 1-10>>>'))
除了ValueError:#只需捕获您知道的异常!
打印“那不是一个数字!”
其他:

如果这不是一个问题,它只是一个缓慢的问题,但它是第一个“问题”的有效答案。虽然我个人认为应该删除OPs的第一个“问题”或将其移至单独的问题中,也许是在codereview.SE上。谢谢Levon。你说的每句话都有道理。这似乎是两个完全不同的问题。。。最好一次问一个问题。如果你得到两个答案:一个是第一个问题,另一个是第二个问题,你怎么知道接受哪一个?你知道
范围(1,10)
不包括10吗?您的
raw_input
文本表明您可能希望10是可接受的。是的,我知道10超出范围,我的错误是将其包含在raw_input语句中。抱歉,请快速输入值作为示例。谢谢。这应该是OPI给出的
<10
范围(1,10)
,我一直认为else语句只能跟在if或elif语句之后。我现在知道情况并非如此。@hemmy你知道在某些情况下,
循环吗?@lazyr不知道,但我现在知道了。谢谢链接上的例子也比我几个月前写的素数程序短一百万倍。。。美好的
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'