简体   繁体   English

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

[英]Using a variable from another function python

Hey there, this is a very fundamental concept and I've looked it up and global variables are not working for me. 嘿,这是一个非常基本的概念,我查过了,全局变量对我不起作用。 I need to use the variable score which is in the function main in another function called judgment , so based on the score of the trivia, I can tell the user how they did (which is why I called the judgment function at the very bottom of main ). 我需要在另一个称为judgment的函数的函数main函数中使用变量score ,因此基于琐事的得分,我可以告诉用户他们的工作方式(这就是为什么我在函数的最底部调用了judgment函数main )。 It gives error that name score is not defined in judgment function. judgment功能中未定义名称score会产生错误。

Code: 码:

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

Contents of trivia_points.txt file: trivia_points.txt文件的内容:

An Episode You Can't Refuse
Tooth hurts?
Let's say your tooth hurts real bad. Where would you go?
Dentist
Butler
Optical
Pawn Shop
1
Because a dentist deals with teeth
2
Food for pets
Let's say you need to get your sea monster some food. Where is the best place to go?
Kroger
Pet's mart
Walmart
Target
2 
Because you can find food for most pets at pets mart.
2
Get in Shape
If you want to play tennis, where would you go?
Tennis Court
Basketball Court
Beach
Football field
1
Because you can play tennis on a tennis court. 
3
Loving Animals
What would you do if you came home to find your dog cooking dinner?
Beat the crap out of it
Let it destroy everything in the kitchen
Sell it 
Enjoy the dinner with him
4
Because dogs are human friends and we need to care for them. 
1
Feel like hunting
If you want to go fishing, what would you take with you?
Basketball
Tennis Ball
Soccer ball
Fishing Rod
4
A fishing rod might be able to help you catch some fish
2
Feeling Smart?
What is the best way to prepare for a jeopardy?
Eat a lot
Sleep a lot
Study a lot
Drink a lot 
3 
Because studying will help you win the game, obviously
2
Road trip
If you drove with 43 people from chicago to mississippi and picked two from texas, what is name of driver?
Jack
Bill
John
You
4
You, because you were the one who drove those people 
5
Sickness relieve
If doctor gave you 3 pills to take every .5 hours, how long until all of them are taken?
.5 hours
1 hour
2 hours
1.5 hours
2
1 hour, because you could take one right away to start with
4
Need for Speed
If I have to travel 4 miles on I-35 in traffic, what would I take?
The bus
The car
The speed bike
By foot
3
The speed bike because it could cut through traffic, even thoguh you could get a ticket
2
Time for Party
What would not be a smart move in a crowded bar or party?
Pay for your own drink 
Don't get in a fight
Make sure you bring your friend along
Take drinks from everyone 
4
Taking drinks from everyone wouldn't be smart, because that could be dangerous
1

You are calling judgement(score) out of the scope of your main() function. 您正在调用main()函数范围之外的judgement(score) The score variable is local in that function. score变量在该函数中是局部的。 Just indent that line to match the function indentation. 只需缩进该行以匹配函数缩进即可。

In Python, indentation has syntactical meaning, so you are not "calling judgment function at the very bottom of main" but before the main function call. 在Python中,缩进具有句法含义,因此您不是“在main的最底部调用判断函数”,而是在main函数调用之前。

It looks like you're calling judgement(score) before main() (both at the bottom of the script). 看起来您在main()之前(都是在脚本底部main()都调用了judgement(score) )。 Why don't you move the judgement(score) into main ? 您为什么不将judgement(score)转移到main judgement(score) Then main 's local copy of score will be copied into the local environment of judgement , and no globals are necessary. 然后main的本地score副本将被复制到本地judgement环境中,并且不需要全局变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM