2014-10-10 85 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的列表中,然后格式化问题并计算代码本身的输出。