2017-10-04 112 views
-2

我新的編程,我學會了基本的命令,現在我試圖創造一些像QUIZZ,所以這裏是我的代碼這讓我頭疼......If and Else help;蟒蛇

prvo =input("How much is 5+5? ") 
if (prvo)==10: 
    print("Correct!") 
else: 
    print ("Sorry, but the answer isn't correct!") 
    sys.exit() 

當我進入10它說: 「對不起,但答案不正確!」,與其他數字相同,請幫助。你能解釋我有什麼不對嗎,因爲我真的很想學:) :)

+0

'如果普羅沃== '10':'因爲你比較'provo'(串)對''10''的字符串。如果你嘗試'10 == 10'將是真的,但是做'10'== 10'將是錯誤的,因爲它們是不同的數據類型(https://docs.python.org/2 /library/functions.html#str)。 – Torxed

+0

將prvo轉換爲int。應該是'prvo = int(input(「多少是5 + 5?」))' – AndMar

+0

@AndMar如果輸入是'moo',會引發異常。 – Torxed

回答

2

你可以試着if prvo == str(10): 以上使用prvo = int(input("How much is 5 + 5? "))

的原因是因爲你目前正在比較兩個不同的數據類型爲提及。這不起作用,所以你需要確保你比較的數據類型是相同的類型。

0

輸入總是返回一個字符串。

嘗試轉換10字符串你比較它的輸入之前:

prvo = input("How much is 5+5? ") 
if prvo == str(10): 
    print("Correct!") 
else: 
    print ("Sorry, but the answer isn't correct!") 
1

input函數將字符串作爲輸入,所以從input返回值應轉換爲類型int和比較。在您的第一行代碼應該是

prvo = int(input("How much is 5+5? "))

0

你正在比較一個整數與一個字符串(默認情況下,input()接受一個字符串)。

您可以輕鬆地與類型()檢查:

prvo = input("How much is 5+5? ") 
print(type(prvo)) 

這將返回:

<class 'str'> 

海峽意義的字符串。

爲了簡單起見,我只是把10放在引號中,使它成爲一個字符串。當您啓動if語句時,您也不需要將prvo放在括號中。

因此,像這樣:

import sys 

prvo = input("How much is 5+5? ") 

if prvo == "10": 
    print("Correct!") 
else: 
    print ("Sorry, but the answer isn't correct!") 
    sys.exit()