zoukankan      html  css  js  c++  java
  • 怎样判断用户输入的是否为数字 续

    判断输入是否为数字 续

    这里用到了检测与处理异常的try-except语句。
    下面是一个例子,在Python交互环境执行的:
    >>> a = int(raw_input('Please input an integer ... '))
    Please input an int number ... t
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: 't'

    那么,如果使用了try-except语句,结果就是这样的。
    >>> try:
    ...     a = int(raw_input('Please input an integer ... '))
    ... except ValueError, error_info:
    ...     print error_info
    ...
    Please input an int number ... t
    invalid literal for int() with base 10: 't'

    我们可以把这段代码更加完善成,如果用户没有输入数字,就一直叫用户重新尝试。

    >>> trigger = True
    >>> while trigger:
    ...     try:
    ...             trigger = False
    ...             a = int(raw_input('Please input an integer ... '))
    ...     except ValueError:
    ...             trigger = True
    ...             print 'You did not input an integer, try again ... '
    ...
    Please input an integer ... a
    You did not input an integer, try again ...
    Please input an integer ... 1.1
    You did not input an integer, try again ...
    Please input an integer ... *
    You did not input an integer, try again ...
    Please input an integer ... @
    You did not input an integer, try again ...
    Please input an integer ... 0.
    You did not input an integer, try again ...
    Please input an integer ... 0
    >>>

    这里有个新问题,程序会把数字0.也认为不是一个整数。会有更好的处理办法吗?

    下面是检测与处理异常的try-except语句的一个典型例子。能帮助你理解try-except语句。

    >>> 1/0
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ZeroDivisionError: integer division or modulo by zero


    >>> try:
    ...     1/0
    ... except ZeroDivisionError, e:
    ...     print e
    ...
    integer division or modulo by zero
    >>>

  • 相关阅读:
    C,LINUX,数据结构部分
    LINUX应用开发工程师职位(含答案)
    INT32 System_UserKeyFilter(NVTEVT evt, UINT32 paramNum, UINT32 *paramArray)
    屏幕调试
    1.ARM嵌入式体系结构与接口技术(Cortex-A8版)
    NT9666X调试log
    DemoKit编译过程错误
    selenium 代理设置
    pandas 轮询dataframe
    Spring 定时任务
  • 原文地址:https://www.cnblogs.com/balian/p/1940591.html
Copyright © 2011-2022 走看看