2014-10-10 83 views
0

這是我的代碼,爲什麼它不適合我?它提出了問題,但錯過了我創建的if聲明。需要關於隨機答案的簡單測驗幫助

print("What is your name?") 
name = input("") 

import time 
time.sleep(1) 

print("Hello", name,(",Welcome to my quiz")) 

import time 
time.sleep(1) 

import random 
ques = ['What is 2 times 2?', 'What is 10 times 7?', 'What is 6 times 2?'] 
print(random.choice(ques)) 

# Please note that these are nested IF statements 

if ques == ('What is 2 times 2?'): 
    print("What is the answer? ") 
    ans = input("") 


    if ans == '4': 
     print("Correct") 

    else: 
     print("Incorrect") 

elif ques == ('What is 10 times 7?'): 
    print("What is the answer? ") 
    ans = input("") 

    if ans == '70': 
     print("Correct") 

    else: 
     print("Incorrect") 

elif ques == ('What is 6 times 2?'): 
    print("What is the answer? ") 
    ans = input("") 

    if ans == '12': 
      print("Correct") 

    else: 
     print("Incorrect") 

import time 
time.sleep(1) 

import random 
ques = ['What is 55 take away 20?', 'What is 60 devided by 2?', 'What is 500 take away 200'] 
print(random.choice(ques)) 


if ques == ('What is 55 take away 20?'): 
    print("What is the answer? ") 
    ans = input("") 

    if ans == '35': 
     print("Correct") 

    else: 
     print("Incorrect") 

elif ques == ('What is 60 devided by 2?'): 
    print("What is the answer? ") 
    ans = input("") 

    if ans == '30': 
     print("Correct") 

    else: 
     print("Incorrect") 

elif ques == ('What is 500 take away 200'): 
    print("What is the answer? ") 
    ans = input("") 

    if ans == '300': 
     print("Correct") 

    else: 
     print("Incorrect") 
+2

爲什麼你多次導入random和time?如果你必須對所有答案進行硬編碼,那麼對問題做一個'random.choice'有什麼意義? – jonrsharpe 2014-10-10 12:22:28

+0

''import time' twice ... – matsjoyce 2014-10-10 12:24:40

+0

不是一個答案,而是:你應該真的試着爲所有這些問題做一個函數,比如'def ask_question(num1,num2,operator)',或者如果這太難了,只是'def ask_question(問題,答案)',所以你不必一遍又一遍地重複這些行。 – 2014-10-10 12:31:33

回答

2

ques始終等於完整列表,而不是列表中的單個元素。 如果你想用這個方法,我建議做以下幾點:

posedQuestion = random.choice(ques) 
print(posedQuestion) 
if posedQuestion == "First question": 

elif ... 

此外,你只需要做你的進口一次,所以只有一條線說import time做到;)

1

還有由MrHug確定的關鍵錯誤,您的代碼存在以下問題:

  1. 大量不必要的重複;
  2. 錯誤地使用import;
  3. 大量不必要的重複;
  4. 字符串格式化的一個坦率撲朔迷離的嘗試;和
  5. 大量的不必要的重複。

注意,下面的代碼做什麼你正在嘗試做的,但在一個更合乎邏輯的方式:

# import once, at the top 
import random 

# use functions to reduce duplication 
def ask_one(questions): 
    question, answer = random.choice(questions): 
    print(question) 
    if input("") == answer: 
     print("Correct") 
    else: 
     print("Incorrect") 

# use proper string formatting 
print("What is your name? ") 
name = input("") 
print("Hello {0}, welcome to my quiz".format(name)) 

# store related information together 
ques = [('What is 2 times 2?', '4'), 
     ('What is 10 times 7?', '70'), 
     ('What is 6 times 2?', '12')] 

ask_one(ques) 

你可以通過存儲的最少信息(即兩個數字和走得更遠運算符)列在ques的列表中,然後格式化問題並計算代碼本身的輸出。