需要有关随机答案的简单测验的帮助

时间:2014-10-10 12:18:28

标签: python

这是我的代码,为什么它对我不起作用?它询问了问题,但错过了我创建的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 个答案:

答案 0 :(得分:2)

ques始终等于完整列表,而不是列表中的单个元素。 如果您想使用此方法,我建议您执行以下操作:

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

elif ...

此外,您只需要执行一次导入,因此只有一行说import time会这样做;)

答案 1 :(得分:1)

除了MrHug发现的关键错误之外,您的代码还存在以下问题:

  1. 大量不必要的重复;
  2. 错误使用import;
  3. 大量不必要的重复;
  4. 对字符串格式化的一种坦率的令人困惑的尝试;和
  5. 大量不必要的重复。
  6. 请注意,以下代码执行您尝试执行的操作,但采用更合理的方式:

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