簡體   English   中英

如何讓 Python 檢查變量是數字還是字母?

[英]How to make Python to check is variable a number or 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")

這是我遇到問題的代碼的一部分。 如果用戶輸入他的年齡作為數字,我想發表聲明,代碼繼續 但是,如果用戶輸入的不是數字,代碼會告訴他重新開始(所有打印語句都是用塞爾維亞語編寫的,我希望你不介意:D)

最簡單的方法是在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

或者你可以試試

使用斷言語句

assert <condition>,<error message>

例如

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

假設您通過 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")

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

示例運行

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