【问题标题】:How to make Python to check is variable a number or letter?如何让 Python 检查变量是数字还是字母?
【发布时间】:2021-05-08 22:05:44
【问题描述】:

您好,我有一个问题...

作为一名 Python 初学者,我想问一下如何让我的代码检查是来自用户数字字母输入 ?


if age == int or float:
    print("Ok, zavrsili smo sa osnovnim informacijama! Da li zelite da ih uklopimo i pokazemo Vase osnovne informacije? DA ili NE ?")

elif age == False:
    print("Hej, to nije broj... Pokusaj ponovo")

这是我遇到问题的代码的一部分。我想声明如果用户输入他的年龄作为数字,代码继续。但是,如果用户输入的不是数字,代码会告诉他从头开始(所有打印语句都是用塞尔维亚语编写的,希望你不要介意:D)

【问题讨论】:

  • 您可以使用函数isnumeric 来检查输入是否为整数。 This answer 展示了如何使用它来创建一个函数来检查字符串是 int、float 还是非数字字符串。
  • 欢迎来到 Stack Overflow!该网站适用于您已经tried to find the answer yourself 提出的特定问题。最好先Google您的问题,看看是否容易找到答案。
  • 可接受的数值范围是多少,即正实数、全实数、任何仅由数字组成的序列?
  • 我不确定我的表达是否正确。当用户键入不是数字的东西时,我需要我的代码来打印错误消息,例如。字母...

标签: python


【解决方案1】:

最简单的方法是在while循环中提示用户输入,try 将其转换为float,如果成功则break

while True:
    try:
        age = float(input("Please enter your age as a number: "))
        break
    except ValueError:
        print("That's not a number, please try again!")

# age is guaranteed to be a numeric value (float) -- proceed!

【讨论】:

  • 恕我直言,这是最干净的解决方案,可通过try/except 解决
【解决方案2】:

假设您通过 input(..) 调用从用户那里获取值“年龄”,然后检查 age 是否为数字:

age = input('Provide age >')
if age.isnumeric():
    age = int(age)
    print("Ok, zavrsili smo sa osnovnim informacijama! Da li zelite da ih uklopimo i pokazemo Vase osnovne informacije? DA ili NE ?")
else:
     print("Hej, to nije broj... Pokusaj ponovo")

【讨论】:

    【解决方案3】:
    isinstance(x, int) # True
    

    或者你可以试试

    使用断言语句

    assert <condition>,<error message>
    

    例如

    assert type(x) == int, "error"
    

    【讨论】:

    • 既然这应该是一个逻辑检查,那么我想大多数开发者会说assert在这里是错误的。
    • 不确定,因为这里指定了自定义消息
    • 与消息无关 - 断言用于调试,也许是单元测试 - 断言很容易禁用,这就是为什么它们不应该用于实际的最终用户报告或程序逻辑。
    • 他可以使用 isinstance(x, int) than ,要求很清楚
    • 这取决于代码如何收集变量 - 如果变量来自 input(...) 它将是一个字符串 - 所以使用 .isnumeric() 方法可能更好(因为 isinstance 检查将在字符串上失败,使其工作的唯一方法是将字符串传递给int() - 然后您必须担心异常。isnumeric() 避免了这种情况。
    【解决方案4】:

    使用函数检查字符串的类型

    def get_type(s):
        ''' Detects type of string s
        
           Return int if int, float if float, or None for non-numeric string '''
        if s.isnumeric():
            return int      # only digits
        elif s.replace('.', '', 1).isnumeric():
            return float    # single decimal
        else:
            return None     # returns None for non-numeric string
    
    
    # Using function
    age = input("What is your age?")
    if not get_type(age) is None:
        print(f'Valid age {age}')
    else:
        print(f'Value {age} is not a valid age')
    

    示例运行

    What is your age?25
    Valid age 25
    
    What is your age?12.5
    Valid age 12.5
    
    What is your age?12.3.5
    Value 12.3.5 is not a valid age
    

    【讨论】:

      猜你喜欢
      • 2012-12-23
      • 2020-03-20
      • 2011-09-01
      • 2013-10-09
      • 1970-01-01
      • 2013-08-05
      • 2015-03-31
      • 1970-01-01
      • 2017-10-12
      相关资源
      最近更新 更多