簡體   English   中英

我在定義基於用戶輸入的變量時遇到了一些 Python 問題

[英]I'm having some Python issues with defining user-input based variables

我知道你以前見過這個,但我真的需要幫助。 我一直在為我的 Tech Ed 創建一個基於 Python 的“數學測試”程序。 類,我一直在努力以數字形式正確定義答案,下面是我的低於標准的 Python 腳本。 如果除了我當前的問題還有其他問題,請告訴我。 下面是導致問題的源代碼。

print("e = 16 , a = 6 | a*10-e ")
answer = input()

if answer = 44:
    print("You got it!")
    print(" n = 186 | 4+n/2")
if answer = 97:
    print("You got it!")
    print(" a = 4 , b = 6 | b^(2)-a")
if answer = 32:
    print(" you got it!")
else:
 print("Sorry, thats incorrect")
 print("please restart the test!")

input返回一個str ,如果你想讓 python 把它當作一個整數做:

answer = int(input())

此外,您的代碼現在的工作方式將接受第一個問題的所有三個答案。 如果答案錯誤,您需要為每個問題設置else ,例如:

if answer == 44:  # Note '==' and not '='
    print("You got it!")
else:
     print("Sorry, thats incorrect")
     print("please restart the test!")
print(" n = 186 | 4+n/2")
# The same for the rest of the questions

這樣一來,每一道題都只有一個正確答案。

你需要一個else:對於每個if ,而不僅僅是最后一個。 問題不應該出現在if ——你這樣做的方式是根據下一個結果檢查上一個問題的答案。 此外,如果比較應該使用 == 。

你必須為每個問題要求輸入,並將其轉換為整數。

print("e = 16 , a = 6 | a*10-e ")
answer = int(input())
if answer == 44:
    print("You got it!")
else:
    print("Sorry, thats incorrect")

print(" n = 186 | 4+n/2")
answer = int(input())
if answer == 97:
    print("You got it!")
else:
    print("Sorry, thats incorrect")

print(" a = 4 , b = 6 | b^(2)-a")
answer = int(input())
if answer == 32:
    print(" you got it!")
else:
    print("Sorry, thats incorrect")

為避免所有這些重復,您可能需要列出問題和答案,並使用循環。

questions = (("e = 16 , a = 6 | a*10-e ", 44),
             (" n = 186 | 4+n/2", 97),
             ("a = 4 , b = 6 | b^(2)-a", 32))
for question, answer in questions:
    response = int(input(question))
    if answer == response:
        print("you got it!")
    else:
        print("Sorry, that's incorrect")

暫無
暫無

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

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