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

  • 相关阅读:
    翻译MDN里js的一些方法属性
    ajax相关
    我的面试错题
    写代码通用思路
    工厂模式
    cookie & session
    X-UA-Compatible设置IE浏览器兼容模式
    [转]IE6/IE7/IE8/IE9中tbody的innerHTML不能赋值的完美解决方案
    EasyUseCase 一款脑图转化 Excel 测试用例工具 (1.2 版本升级)
    XMind2TestCase:一个高效测试用例设计的解决方案!
  • 原文地址:https://www.cnblogs.com/balian/p/1940591.html
Copyright © 2011-2022 走看看