首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >简单问答程序

简单问答程序
EN

Code Review用户
提问于 2013-02-17 12:25:37
回答 4查看 94.4K关注 0票数 3

我一直在尝试用Python做一个简单的“测试”程序。我打算做的是,比如说,一个三轮测验,每一轮都有三个问题。在每一轮结束时,该程序将提示用户是否参加“奖金”问题。

代码语言:javascript
复制
print("Mathematics Quiz")
question1 = "Who is president of USA?"
options1 = "a.Myslef\nb. His dad\nc. His mom\nd. Barack Obama\n"
print(question1)
print(options1)

while True:
    response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n")

    if response == "d":
        break
    else:
        print("Incorrect!!! Try again.")

        while True:
            response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n")

            if response == "d":
                stop = True
                break
            else:
                print("Incorrect!!! You ran out of your attempts")
                stop = True
                break
        if stop:
            break

# DO the same for the next questions of your round (copy-paste-copy-paste).
# At the end of the round, paste the following code for the bonus question.

# Now the program will ask the user to go for the bonus question or not

while True:
    bonus = input("Would you like to give a try to the bonus question?\nHit 'y' for yes and 'n' for no.\n")

    if bonus == "y":
        print("Who invented Facebook?")
        print("a. Me\nb. His dad\nc. Mark Zuckerberg\nd. Aliens")

        while True:
            response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n")

            if response == "c":
                break
            else:
                print("Incorrect!!! Try again.")

            while True:
                response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n")


                if response == "c":
                    stop = True
                    break
                else:
                    print("Incorrect!!! You ran out of your attempts")
                    stop = True
                    break
            if stop:
                break
        break
    elif bonus == "n":
        break
    else:
        print("INVALID INPUT!!! Only hit 'y' or 'n' for your response")

# Now do the same as done above for the next round and another bonus question.

现在,这段代码对于一个问题来说是非常长的,我不认为这是“真正的”编程。我不想一遍又一遍地复制粘贴它。我想知道是否有任何方法可以使用class或定义函数之类的方法来缩短代码?

EN

回答 4

Code Review用户

回答已采纳

发布于 2013-02-17 14:13:41

代码语言:javascript
复制
import string

NUMBER_OF_ATTEMPTS = 2
ENTER_ANSWER = 'Hit %s for your answer\n'
TRY_AGAIN = 'Incorrect!!! Try again.'
NO_MORE_ATTEMPTS = 'Incorrect!!! You ran out of your attempts'

def question(message, options, correct, attempts=NUMBER_OF_ATTEMPTS):
    '''
    message - string 
    options - list
    correct - int (Index of list which holds the correct answer)
    attempts - int
    '''
    optionLetters = string.ascii_lowercase[:len(options)]
    print message
    print ' '.join('%s: %s' % (letter, answer) for letter, answer in zip(optionLetters, options))
    while attempts > 0:
        response = input(ENTER_ANSWER % ', '.join(optionLetters)) # For python 3
        #response = raw_input(ENTER_ANSWER % ', '.join(optionLetters)) # For python 2
        if response == optionLetters[correct]:
            return True
        else:
            attempts -= 1
            print TRY_AGAIN

    print NO_MORE_ATTEMPTS
    return False


print("Mathematics Quiz")

# question1 and question2 will be 'True' or 'False' 
question1 = question('Who is president of USA?', ['myself', 'His Dad', 'His Mom', 'Barack Obama'], 3)
question2 = question('Who invented Facebook?', ['Me', 'His Dad', 'Mark Zuckerberg', 'Aliens', 'Someone else'], 2)

我不知道你在用哪条蟒蛇。尝试第20行或第21行,看看哪一行最适合您。

总的来说,这个函数允许你输入问题,你想要多少回答多少,它会为你做剩下的。

祝好运。

票数 4
EN

Code Review用户

发布于 2016-09-30 11:08:19

您也可以使用字典来准备问题,然后简单地按某种顺序提问(在这种情况下是随机的):

代码语言:javascript
复制
import random

# Dictionary of questions and answers

questions = {
            'Who is president of USA?':
            ('\na. Myslef\nb. His dad\nc. His mom\nd. Barack Obama\n', 'd'),
            'What is the capital of USA?':
            ('\na. Zimbabwe\nb. New York\nc. Washington\nd. Do not exist', 'c')
            }

def ask_question(questions):
    '''Asks random question from 'questions 'dictionary and returns
       players's attempt and correct answer.'''

    item = random.choice(list(questions.items()))
    question = item[0]
    (variants, answer) = item[1]
    print(question, variants)
    attempt = input('\nHit \'a\', \'b\', \'c\' or \'d\' for your answer\n')
    return (attempt, answer)

# Questions loop
tries = 0
for questions_number in range(5):
    while True: # Asking 1 question
        attempt, answer = ask_question(questions)
        if attempt not in {'a', 'b', 'c', 'd'}:
            print('INVALID INPUT!!! Only hit \'y\' or \'n\' for your response')
        elif attempt == answer:
            print('Correct')
            stop_asking = False
            break
        elif tries == 1: # Specify the number of tries to fail the answer        
            print('Incorrect!!! You ran out of your attempts')
            stop_asking = True
            break
        else:
            tries += 1
            print('Incorrect!!! Try again.')
    if stop_asking:
        break

您可以使用它作为模板,并修改一些代码以添加额外的检查,或者将部分循环封装在另一个函数中,该函数将在主循环中调用。

此外,通过小编辑,您可以从文本文件中导入问题和答案。

票数 3
EN

Code Review用户

发布于 2013-02-17 12:31:41

代码语言:javascript
复制
asking = True
attempts = 0
while asking == True:
    response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n")

    if response == "d":
        asking = False
    else:
        if attempts < 1: # 1 = Max Attempts
            print("Incorrect!!! Try again.")
            attempts += 1
        else:
            print("Incorrect!!! You ran out of your attempts")
            asking = False

第二部分遵循同样的模式,作为一个很好的练习。

这里主要要注意的是,您正在将while循环链接到循环,而不是实际让while循环循环。:)

票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/22822

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档