选择测验选择

时间:2017-10-16 20:58:50

标签: python-3.x

这是一个基本的测验程序,允许用户回答有关主题的问题并为该主题选择难度。

正如您所看到的,编码本身非常长,因此可能会花费大量时间,因为由于if和elif语句,代码本质上会重复。有没有一种方法来压缩这段代码?

choices = input ("Choose 'c' for capital city's or 's' for songs:")
mode = input ("Choose 'e' for easy , 'm' for medium , 'h' for hard: ")

if choices == "c" and mode == "e":
    q = input ("What is the capital of China?")
    qTwo = input ("What is the capital city of Denmark?")

elif choices == "c" and mode == "m":
    qThree = input("Is there a capital city of antartica?")
    qFour = input("What is the current capital of India?")

elif choices == "c" and mode == "h":
    qFive = int(input("How many capitals are their in the world?")
    qSix = input("What was the old capital of China called?")

1 个答案:

答案 0 :(得分:1)

我建议将问题和答案放入列表中,然后将所选列表分配给一个变量,在该变量上循环使用for循环来获取当前的问题和答案。

import random

# First put the questions into separate lists.
# The lists contain tuples of the question and the answer.
capital_questions_easy = [
    ("What is the capital of China?", "Beijing"),
    ("What is the capital city of Denmark?", "Copenhagen"),
    ]

capital_questions_medium = [
    ("Is there a capital city of Antartica?", "No"),
    ("What is the current capital of India?", "New Delhi"),
    ]

capital_questions_hard = [
    ("How many capitals are their in the world?", "206"),
    ("What was the old capital of China called?", "No distinct answer"),
    ]

# A while loop to handle incorrect user input.
while True:
    mode = input("Choose 'e' for easy , 'm' for medium , 'h' for hard: ")
    if mode in ("e", "m", "h"):
        break
    else:
        print("Invalid input.")

# Assign the chosen list to another variable. You could
# use a dictionary here as well.
if mode == "e":
    questions = capital_questions_easy
elif mode == "m":
    questions = capital_questions_medium
elif mode == "h":
    questions = capital_questions_hard

# Randomize the questions. Note that `questions` is just a reference
# to the original list, so it is shuffled as well. Create a copy
# if you want to avoid this.
random.shuffle(questions)

score = 0

# Now ask the questions in a for loop. I unpack the
# (question, answer) tuples directly in the head of the
# loop into the variables `question` and `answer`.
for question, answer in questions:
    user_input = input(question + ' ')
    if user_input == answer:
        score += 1
        print('Correct. Score:', score)
    else:
        print('Incorrect. The correct answer is:', answer)