2016-07-27 30 views
-6

我正在爲學校創建作業。如何使用Python 3.x請求用戶輸入?

首先創建僞代碼等

然後寫一個比較函數returns 1 if a > b , 0 if a == b , and -1 if a < b

我已經寫了一部分

def compare(a, b): 

    return (a > b) - (a < b) 

但後來我不得不提示用戶輸入的數字進行比較。

我不知道如何編寫用戶輸入提示。

+0

2.x - > user_input = raw_input()3.x - > user_input = input() – SAMO

+0

哪個版本的Python? – khelwood

+0

我正在使用python 3 – JaneDoe

回答

0

由於您使用的Python 3.x中,你可以使用:

def compare(a, b): 
    a = int(input("Insert value A: ")) 
    b = int(input("Insert value B: ")) 
    return (a > b) - (a < b) 

因爲Python 3.x中不計算和/或轉換數據類型,你必須明確地轉換爲ints,與int(),像這樣:

a = int(input("Insert value A: ")) 

但是,如果你wan't創造良好的功能,你必須驗證PARAMS A和B,以確保你的計劃不接受"one""twelve"作爲投入。

您可以在這裏乘坐更深層面上來看:Asking the user for input until they give a valid response

0

命令:

variable = input("You can write something here:") 

然後,編譯.py文件時,終端將顯示信息:

You can write something here: 

你可以把你的輸入和輸入一樣簡單。

也許,如上所述,您可能希望使用int()或float()函數將輸入轉換爲int或float,以確保獲得有效的輸入。

+0

他說他在使用Python 3.x.在Python 3.x中,input()方法接受任何數據類型。看看[這裏](http://stackoverflow.com/a/20449433/3846228)。 –

+0

寫出來的時候,編輯:) –

相關問題