简体   繁体   English

如何让 Python 检查变量是数字还是字母?

[英]How to make Python to check is variable a number or letter?

Hi I have a question...你好我有一个问题...

As a Python beginner I want to ask how do I make my code to check is input from a user a number or a letter ?作为一名 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")

This is part of my code that I'm having issues with.这是我遇到问题的代码的一部分。 I want to make statement if user inputs his age as number, the code continues .如果用户输入他的年龄作为数字,我想发表声明,代码继续 But, if user inputs something that is not a number, code tells him to start all over ( all print statements are written in Serbian, I hope you don't mind:D)但是,如果用户输入的不是数字,代码会告诉他重新开始(所有打印语句都是用塞尔维亚语编写的,我希望你不介意:D)

The easiest way to do this is to prompt the user for input in a while loop, try to convert it to a float , and break if you're successful.最简单的方法是在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!
isinstance(x, int) # True

Or you can try或者你可以试试

Use assert statement使用断言语句

assert <condition>,<error message>

for example例如

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

Assuming that you are getting the value 'age' from the user via an input(..) call then to check if the age is a number then:假设您通过 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")

Using function to check type of string使用 function 检查字符串类型

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

Example runs示例运行

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM