2

我有一个测验,在最后一轮,如果它的值不正确,我希望它结束

我有一个if循环,但我希望我的最终else值有一个转到行号代码,因为它是一个长代码。为了使用此功能,我如何查看行号(我使用Portable Python Scripter)。

print("PLEASE NOTE: Answers are case-sensitive, so start all answers with a capital letter.")
print("Getting full marks (5/5) in each round will allow you to complete the next round.")
#==============================================================================
singer = input("Who is your favourite singer?")
if singer == "Harry Styles" or "Harry":
    print("Great choice!")
else:
    print(singer +" is good, but Harry Styles is better")
#==============================================================================
ans = input("Do you want to do a Harry Styles quiz?")
if ans == "No":
    print("How rude!")
elif ans == "Yes":
#==============================================================================
    q1 = input("What boyband was Harry Styles in?")
    if q1 == "One Direction":
        print("Correct!")
        score = 1
    elif q1 == "1D":
        print("Correct!")
        score = 1
    elif q1 == "White Eskimo":
        print("Correct!")
        score = 1
    else:
        print("Incorrect")
        score = 0
#==============================================================================
    q2 = input("What is Harry's birthday (write in format dd/mm/yyyy)")
    if q2 == "01/02/1990":
        print("Correct!")
        score = score + 1
    else:
        print("Incorrect")
#==============================================================================
    q3 = input("What is Harry's favourite film?")
    if q3 == "Love, Actually":
        print("Correct!")
        score = score + 1
    elif q3 == "Love Actually":
         print("Correct!")
         score = score + 1
    else:
        print("Incorrect")
#==============================================================================
    q4 = input("What war film did Harry star in?")
    if q4 == "Dunkirk":
        print("Correct!")
        score = score + 1
    else:
        print("Incorrect")
#==============================================================================
    q5 = input("What is Harry's mum's first name?")
    if q5 == "Anne":
        print("Correct!")
        score = score + 1
    else:
        print("Incorrect")
#==============================================================================
    if score < 5:
        ps = str(score)
        print("You achieved " + ps)
    if score ==  5:
        print("Well done! You got everything correct!")
        print("Entering quickfire round...")
#==============================================================================
        score =  0
        print("Instructions:")
        print("Your score has been reset to 0")
        print("If you get a question incorrect, you will lose 1 point")
        print("If you achieve below 0, you wil end the game.")
#==============================================================================
        while score <= 0:
            qf1 = input("What is Harry's 2nd album called?")
            if qf1 == "Fine Line":
                print("Correct")
                score = score + 1
                print(score)
            else:
                print("Incorrect")
                score = score - 1
                print(score)
#==============================================================================
            qf2 = input("How old was Harry when he went on the X-Factor?")
            if qf2 == "16":
                print("Correct")
                score = score + 1
                print(score)
            elif qf2 == "Sixteen":
                print("Correct")
                score = score + 1
                print(score)
            else:
                print("Incorrect")
                score = score - 1
                print(score)
#==============================================================================
            qf3 = input("Finish the quote: 'This is a family show. _________?'")
            if qf3 == "Or is it?":
                print("Correct")
                score = score + 1
                print(score)
            elif qf3 == "Or is it":
                print("Correct")
                score = score + 1
                print(score)
            else:
                print("Incorrect")
                score = score - 1
                print(score)
#==============================================================================
            qf4 = input("What is Harry's middle name?'")
            if qf4 == "Edward":
                print("Correct")
                score = score + 1
                print(score)
            else:
                print("Incorrect")
                score = score - 1
                print(score)
#==============================================================================
            qf5 = input("What is Harry's blood type?'")
            if qf5 == "B+":
                print("Correct")
                score = score + 1
                print(score)
            elif qf5 == "B positive":
                print("Correct")
                score = score + 1
                print(score)
            else:
                print("Incorrect")
                score = score - 1
                print(score)
#==============================================================================
        if score < 0:
            print("GAME OVER!")
#==============================================================================
        if score > 0:
            if score < 5:
                ps = str(score)
        if score == 5:
            print("Wow, that's full marks! Well done!")
#==============================================================================
            print("Entering Death Row...")
            score =  0
            print("Instructions:")
            print("Your score has been reset to 0")
            print("If you get a question incorrect, you will end the game")
#==============================================================================
            d1 = input("What characer does Harry play in the MCU (Marvel Cinematic Universe)?")
            if d1 == "Starfox" or "Eros":
                print("Correct!")
                score = score + 1
#==============================================================================
                d2 = input("What does Harry say the best thing a girl can wear is?")
                if d2 == "A smile" or "Smile":
                    print("Correct!")
                    score = score + 1
#==============================================================================
                    d3 = input("What did Harry dress up as for 2021's 'Harryween'?")
                    if d3 == "Alice" or "Alice in Wonderland" or "A clown" or "Clown":
                        print("Correct!")
                        score = score + 1
#==============================================================================
                        d4 = input("Which singer does Harry have a crush on?")
                        if d4 == "Adele":
                            print("Correct!")
                            score = score + 1
#==============================================================================
                            d5 = input("How many nipples does Harry have?")
                            if d5 == "Four" or "4":
                                print("Correct!")
                                score = score + 1
#==============================================================================
                                if score == 5:
                                    print("Oh ma gawd! You got everything correct!")
                                    print("I think you dropped this []")
                                    print("Get your certificate here: [https://drive.google.com/file/d/1k-PJEQmqW_rv56vSId0PDo6etuC_up_G/view]")
#==============================================================================
                            else:
                                ps = str(score)
                                print("Incorrect")
                                print("You achieved " + score)
                        else:
                            ps = str(score)
                            print("Incorrect")
                            print("You achieved " + score)
                    else:
                        ps = str(score)
                        print("Incorrect")
                        print("You achieved " + score)
                else:
                    ps = str(score)
                    print("Incorrect")
                    print("You achieved " + score)
            else:
                print("Incorrect")
#==============================================================================
else:
    termination = (ans.upper())
    print("ERROR! CANNOT COMPUTE! UNKNOWN VARIABLE: [" + termination +"]")
    print("TERMINATING QUIZ!") ```
4

1 回答 1

2

使用循环和函数可以帮助您缩短这段代码,并消除大量复制+粘贴 if/else 的需要。这是对初始测验部分的快速重写,其中包含一个main()函数的大纲,以提供您的想法:

def first_round():
    """Ask the first round questions, return cumulative score."""
    score = 0
    for question, answers in [
        ("What boyband was Harry Styles in?",
            {"One Direction", "White Eskimo"}),
        ("What is Harry's birthday (write in format dd/mm/yyy)",
            {"01/02/1990"}),
        ("What is Harry's favourite film?",
            {"Love, Actually", "Love Actually"}),
        ("What war film did Harry star in?",
            {"Dunkirk"}),
        ("What is Harry's mum's first name?",
            {"Anne"}),
    ]:
        if input(question) in answers:
            print("Correct!")
            score += 1
        else:
            print("Incorrect")
    return score


def main():
    # do intro stuff here

    score = first_round()
    if score < 5:
        print(f"You achieved {score}")
        return  # Game over!

    print("Well done! You got everything correct!")
    print("Entering quickfire round...")

    # continue on with score = quickfire_round()...


main()

将代码放入函数中意味着当该结束时,您可以return让函数的其余部分在缩进的外层继续,而不必进入越来越深if/elif/else的嵌套语句来继续程序。使用循环(如first_round上面的函数)意味着您不需要一遍又一遍地复制和粘贴相同的代码。

采用上面的模式并将其应用于死亡回合,我们可能会得到类似的结果:

def death_round():
    """Ask the death round questions -- first wrong answer ends it!"""
    score = 0
    for question, answers in [
        ("What characer does Harry play in the MCU (Marvel Cinematic Universe)?",
            {"Starfox", "Eros"}),
        ("What does Harry say the best thing a girl can wear is?",
            {"A smile", "Smile"}),
        ("What did Harry dress up as for 2021's 'Harryween'?",
            {"Alice", "Alice in Wonderland", "A clown", "Clown"}),
        ("Which singer does Harry have a crush on?",
            {"Adelete"}),
        ("How many nipples does Harry have?",
            {"Four", "4"}),
    ]:
        if input(question) in answers:
            print("Correct!")
            score += 1
        else:
            print("Incorrect")
            return score  # sudden death!
    return score

请注意return在“不正确”的情况下,这是此函数与 不同的一种方式,也是导致first_round它的原因,因此您不需要一个goto或五个不同的嵌套else语句来跟踪您可能结束游戏的五个不同时间-- 一旦有错误的答案,函数就会返回,然后main可以查看最终分数并根据其值做不同的事情。

在您进行测验时要考虑的另一件事 - 现在它对准确的措辞大小写非常敏感,即使您提供了多个正确的选项。例如:

What does Harry say the best thing a girl can wear is?Her smile
Incorrect

这是修复它的一种方法,它将使得任何包含“微笑”一词的答案都将被接受,无论大小写如何:

for question, answers in [
    ("What does Harry say the best thing a girl can wear is?",
        {"smile"}),
    ("What did Harry dress up as for 2021's 'Harryween'?",
        {"alice", "clown"}),
]:
    answer = input(question).lower()
    if any(a in answer for a in answers):
        print("Correct!")
    else:
        print("Incorrect")
What does Harry say the best thing a girl can wear is? Just a smile
Correct!
What did Harry dress up as for 2021's 'Harryween'? A fabulous clown
Correct!
于 2021-12-12T18:13:32.107 回答