使用另一个函数python中的变量

2024-06-11 05:33:11 发布

您现在位置:Python中文网/ 问答频道 /正文

嘿,这是一个非常基本的概念,我查过了,全局变量对我不起作用。我需要使用变量score,它在另一个名为judgment的函数main中,因此根据这些琐事的评分,我可以告诉用户他们是怎么做的(这就是为什么我在main的最底层调用judgment函数)。在judgment函数中没有定义名称score,这是一个错误。在

代码:

# Trivia Challenge
# Trivia game that reads a plain text file

import sys

def open_file(file_name, mode):
    """Open a file."""
    try:
        the_file = open(file_name, mode)
    except IOError as e:
        print("Unable to open the file", file_name, "Ending program.\n", e)
        input("\n\nPress the enter key to exit.")
        sys.exit()
    else:
        return the_file

def next_line(the_file):
    """Return next line from the trivia file, formatted."""
    line = the_file.readline()
    line = line.replace("/", "\n")
    return line

def next_block(the_file):
    """Return the next block of data from the trivia file."""
    category = next_line(the_file)

    question = next_line(the_file)

    answers = []
    for i in range(4):
        answers.append(next_line(the_file))

    correct = next_line(the_file)
    if correct:
        correct = correct[0]

    explanation = next_line(the_file)

    point = next_line(the_file)


    return category, question, answers, correct, explanation, point

def welcome(title):
    """Welcome the player and get his/her name."""
    print("\t\tWelcome to Trivia Challenge!\n")
    print("\t\t", title, "\n")

def judgement(score):

    if  score > 0 and score <= 5:
            print("You can do better.")
    elif score >= 6 and score <= 10: 
            print("You did okay.")
    elif score >= 11 and score <= 14:
            print("You did average.")
    elif score >= 15 and score <= 19:
            print("You did above average.")
    elif score >= 20 and score <= 24:
            print("You did excellent.")
    else:
        print("Does not exist.")

def main():
    trivia_file = open_file("trivia_points.txt", "r")
    title = next_line(trivia_file)
    welcome(title)
    score = 0

    # get first block
    category, question, answers, correct, explanation, point = next_block(trivia_file)
    while category:
        # ask a question
        print(category)
        print(question)
        for i in range(4):
            print("\t", i + 1, "-", answers[i])

        # get answer
        answer = input("What's your answer?: ")

        # check answer
        if answer == correct:
            print("\nRight!", end=" ")
            score += int(point)
        else:
            print("\nWrong.", end=" ")
        print(explanation)
        print("Score:", score, "\n\n")

        # get next block
        category, question, answers, correct, explanation, point = next_block(trivia_file)

    trivia_file.close()

    print("That was the last question!")
    print("You're final score is", score)

judgement(score)

main()  
input("\n\nPress the enter key to exit.")

琐事内容_点.txt文件:

^{pr2}$

Tags: andtheyoudeflineblockfilenext
2条回答

看起来您在main()(都在脚本的底部)之前调用judgement(score)。为什么不把judgement(score)移到main?然后main的本地副本{}将被复制到{}的本地环境中,并且不需要全局变量。在

您调用的judgement(score)超出了main()函数的范围。score变量在该函数中是局部的。只需将该行缩进以匹配函数indentation。在

在Python中,缩进具有语法意义,因此您不是“在main的最底层调用判断函数”,而是在main函数调用之前。在

相关问题 更多 >