我是初學者,我剛剛開始學習如何撰寫 Python 代碼。我遇到了這個問題。每當我輸入正確的結果時,它仍然顯示它不正確。我想知道我錯過了什么或我做錯了什么。
array1 = ([5, 10, 15, 20, 25])
print("Question 2: What is the reverse of the following array?", array1)
userAns = input("Enter your answer: ")
array1.reverse()
arrayAns = array1
if userAns == arrayAns:
print("You are correct")
else:
print("You are incorrect")
uj5u.com熱心網友回復:
因此,當您使用input()分配的變數時,將默認為 type string,與陣列相比時總是回傳 false。
但是,如果您打算回傳一個字串格式的串列,您應該嘗試使用ast.literal_eval()來評估您作為答案傳遞給輸入函式的字串。
考慮:
import ast
userAns = ast.literal_eval(input("Enter your answer: "))
發送后:
[25,20,15,10,5]
你會得到這樣的結果:
You are correct
因為您作為問題答案傳遞的字串 ('[25,20,15,10,5]') 將被評估并識別為串列,然后在將其與其他變數進行比較時,評估結果為 True。
uj5u.com熱心網友回復:
input只回傳一個str值。您必須將“反轉”陣列轉換為 astr或將輸入轉換為 numpy 陣列。第一個選項似乎更容易,可能是str(array1).
uj5u.com熱心網友回復:
如前所述,您正在嘗試將作為字串的用戶輸入與陣列進行比較,因此在比較時它會出現錯誤。
我的解決方案是:
temp = userAns.split(",")
userAns = [int(item) for item in temp]
首先將字串拆分為串列。這將創建一個字串陣列。接下來通過將每個專案型別從 string 更改為 int 來重新創建陣列。你最終得到一個整數陣列,然后可以進行比較。
uj5u.com熱心網友回復:
正如其他回應者所指出的, input正在回傳一個str. 如果您愿意,您可以要求用戶以逗號分隔格式輸入值,然后使用該split()函式將字串分解為由逗號分隔的陣列,如下所示:
array1 = ([5, 10, 15, 20, 25])
print("Question 2: What is the reverse of the following array?", array1)
userAns = input("Enter your answer (comma delimited, please): ")
array1.reverse()
arrayAns = list(map( str, array1 ) )
if userAns.split(',') == arrayAns:
print("You are correct")
else:
print("You are incorrect")
這是示例輸出:
Question 2: What is the reverse of the following array? [5, 10, 15, 20, 25]
Enter your answer (comma delimited, please): 25,20,15,10,5
You are correct
另一個運行 - 讓我們確保當他們輸入錯誤的值時它可以作業:
Question 2: What is the reverse of the following array? [5, 10, 15, 20, 25]
Enter your answer (comma delimited, please): 25,20,15,10,6
You are incorrect
由于用戶正在輸入字串,我們需要將字串與字串進行比較。因此,我使用map( str, array1)下面的呼叫將 array1 中的每個整數轉換為字串。
您還可以看到我userAns使用split(',').
相反的方法也是可能的。我們可以從 array1 構建一個字串,然后只比較這些字串。在這種情況下,我可以使用該join()函式從陣列構建字串:
arrayString = ','.join( arrayAns )
因此代碼可能如下所示:
array1 = ([5, 10, 15, 20, 25])
print("Question 2: What is the reverse of the following array?", array1)
userAns = input("Enter your answer (comma delimited, please): ")
array1.reverse()
arrayAns = list(map( str, array1 ) )
arrayString = ','.join(arrayAns)
if userAns == arrayString:
print("You are correct")
else:
print("You are incorrect")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/532956.html
