簡體   English   中英

如何根據 Python 3.x 中的輸入類型查找用戶輸入的類型並打印不同的值

[英]How to find type of user input and print different values depending on the type of input in Python 3.x

開發一個 Python function 如果參數是數字,則返回其參數 x 的浮點平方,或者如果參數是字符串,則打印字符串“Sorry Dave,我害怕我做不到”,然后返回0.0。

我究竟做錯了什么? 我是 CS 一年級的學生,以前沒有編程背景。

我創建了一個 function,它接受用戶輸入,評估輸入的類型並打印數字和字符串的不同輸出。

為此,我使用了eval(var)函數。 我還使用type(var) == type來驗證類型和if-else循環。

def findt():
    userin = input("Input: ")       # Takes user input
    inpeval = eval(userin)          # Evaluates input type    

    if type(inpeval) == int:        # If input is an int
        userfloat = float(inpeval)  # Modifies into a float
        print(userfloat ** 2)       # Prints the square of the value
    elif type(inpeval) == float:    # If input is a float
        print(inpreval ** 2)        # Prints the square of the value
    elif type(userin) == str:       # If input is a string
        print("Sorry Dave, I'm afraid I can't do that")   # Print a string
        return 0.0                  # Return 0.0
    else:
        print("Invalid Input")    
findt()

當我運行我的代碼時,當輸入是 int、float 或 char 時效果很好。 但是如果我寫了多個字符,它會返回一個錯誤:

NameError: name 'whateverinput' is not defined.

在您知道需要輸入之前,您正在嘗試eval輸入。 完全擺脫它:

def findt():
    userin = input("Input: ")       # Takes user input

    if type(userin) == int:        # If input is an int
        userfloat = float(userin)  # Modifies into a float
...

根本問題是您無法評估未定義的名稱。 如果您輸入的字符串不是您程序中 object 的名稱,它將失敗。 eval要求定義您提供的所有內容。

這是實現目標的更好方法,方法是使用字符串方法isnumeric()來測試輸入是否為數字。

def findt():
    userin = input("Input: ")

    if userin.isnumeric():
        # userin is numeric
        result = float(userin) ** 2
        print(result)

    else:
        try:
            # userin is a float
            result = float(userin) ** 2
            print(result)
        except ValueError:
            # userin is a string
            print("Sorry Dave, I'm afraid I can't do that")
            return 0.0

findt()

更新:簡潔版本:

def findt():
    userin = input("Input: ")

    try:
        # userin is an int or float
        result = float(userin) ** 2
        print(result)
    except ValueError:
        # userin is a string
        print("Sorry Dave, I'm afraid I can't do that")
        return 0.0

findt()

我找到了解決我的問題的方法。 我這樣做的方式是從用戶那里獲取輸入,然后try將其轉換為浮點數。 如果它是一個數字,它將轉換並打印一個作為輸入平方的浮點數。 如果輸入是字符串,它不能轉換為浮點數並且會給我一個錯誤,所以我使用except ValueError:來打印我想要的字符串並返回 0.0。

def whattype():
    user_input = input(">>> ")
    try:                                                
            user_input = float(user_input)                      
            print(user_input ** 2)
    except ValueError:
            print("Sorry Dave, I'm afraid I can't do that")
            return 0.0

whattype()

謝謝大家的建議和幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM