组if-else语句然后执行随机集

时间:2017-10-09 07:20:50

标签: python python-3.x if-statement random python-3.6

我正在制作一个程序,它将生成一个随机的琐事测验,在每个问题中包含if-else语句和变量。需要知道如何对每个集合进行分组并每次生成一个随机集合, import random 或者如果还有其他方法可以建议我。

我的代码:

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")

2 个答案:

答案 0 :(得分:1)

首先考虑经常性问题"提出问题并检查答案"图案:

{
    "jy-id-1_radio_0":{ "label":"alternativ 1", "reference":"jy-id-1" },
    "jy-id-1_radio_1":{ "label":"alternativ 2", "reference":"jy-id-1" },
    "jy-id-2":{ "label":"kryssruta", "reference":"jy-id-2" },
    "jy-id-3":{ "label":"kryssruta", "reference":"jy-id-3" }
}

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

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

然后你只需要一个main函数来运行整个事情:

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)) 上调用random.choice() ...

答案 1 :(得分:0)

使用key = question和value = answers创建一个字典,并列出所有问题。然后导入随机和randint一个介于0和len之间的数字(question_list)并向用户显示该问题 - 并检查他的答案是否是字典中键是给定问题的值。就在我的脑海里