2017-10-09 24 views
0

我正在制作一个程序,该程序将生成一个随机小问答,在每个问题中都包含if-else语句和变量。需要知道我如何分组每个集合并随机生成一个随机集合,随机导入或者请告诉我是否有其他方法可以做到这一点。组if-else语句然后执行一个随机集

我的代码:

c1 = 0 
c2 = 0 
while(1): 
    quiz1 = print("What is Prosciutto?") 
    q = input().lower() 
    if ("italian" in q) or ("dry" in q) or ("ham" in q): 
    print("Correct!") 
    c1 +=1 
    else: 
    print("Not quiet right, Prosciutto is Italian dry-cured ham") 
    c2 +=1 
    input("Press Enter to continue...") 
    quiz2 = print("What is the capital of the US state of Alabama?") 
    q = input().lower() 
    if "montgomery" in q: 
    print("Correct!") 
    c1 +=1 
    else: 
    print("Nope, Montgomery, it is.") 
    c2 +=1 
    input("Press Enter to continue...") 
    quiz3 = print("Which planet spins on a nearly horizontal axis?") 
    q = input().lower() 
    if "uranus" in q: 
    print("Correct!") 
    c1 +=1 
    else: 
    print("Actually it is Uranus!") 
    c2 +=1 
    input("Press Enter to continue...") 
    quiz4 = print("Who invented writing?") 
    q = input().lower() 
    if "sumerian" in q: 
    print("Correct!") 
    c1 +=1 
    else: 
    print("Nope, the Sumerians invented writing") 
    c2 +=1 
    input("Press Enter to continue...") 
    quiz5 = print("What rapper was born Marshall Bruce Mathers III?") 
    q = input().lower() 
    if "eminem" in q: 
    print("Correct!") 
    c1 +=1 
    else: 
    print("He's Eminem") 
    c2 +=1 
    input("Trivia ended, Press Enter to view your result...") 
    break 
print("You've made", c1, "corrects answers and ", c2, "wrong answers") 

回答

1

第一个因素出了经常性“问一个问题,检查答案”模式:

def handle(question, answer, err): 
    print(question) 
    a = input().lower() 
    if a in answer: 
     print("Correct!") 
     return True 
    else: 
     print(err) 
     return False 

然后定义您的问题/答案/错误:

QUIZZES = [ 
    ("What is Prosciutto?", ("italian","cured","dryed","ham"), "Not quiet right, Prosciutto is Italian dry-cured ham"), 
    ("What is the capital of the US state of Alabama?", ("montgomery",), "Nope, Montgomery, it is."), 
    # etc 
    ] 

然后你只需要一个主要功能来运行整件事:

def main(): 
    good = 0 
    wrong = 0 
    for question, answers, err in QUIZZES: 
     ok = handle(question, answers, err) 
     if ok: 
      good += 1 
     else: 
      wrong += 1 
    input("Trivia ended, Press Enter to view your result...") 
    print("You've made {} corrects answers and {} wrong answers".format(good, wrong)) 

一旦你在那里,添加randomi我只想在QUIZZES上拨打random.choice() ...

+0

我试过了,但是它打印了一整套问题,比如*('什么是美国阿拉巴马州的首府?','蒙哥马利', “不,蒙哥马利,它是。')*而不是只是一个问题,然后它再次运行琐事。顺便说一下,我使用了'import random'。 – PL0YP1T1

+0

现在它工作了,在用'while(1):question,answers,err = random.choice(QUIZZES)''替换问题,答案,错误之后:'谢谢你的帮助。 – PL0YP1T1

+0

你可能想跟踪已经提出的问题,以避免重复同样的quizz(提示:使用'set'在你的while循环中存储问题) –

0

创建键=问题与值=答案的字典,也使所有的问题清单。然后导入random和randint一个介于0和len(question_list)之间的数字并显示用户该问题 - 并检查他的答案是否是字典中键的值是给定问题的值。只是从我的头顶