2011-04-19 5 views
0

안녕하세요, 이것은 매우 기본적인 개념이며, 나는 그것을 찾았고 전역 변수가 저를 위해 작동하지 않습니다. 변수 score을 사용하고 main 다른 함수를 judgment라고 부르며, 퀴즈의 점수에 따라 사용자에게 어떻게하는지 알려줄 수 있습니다. (바로 그 이유 때문에 내가 가장 아래쪽에 judgment 함수를 호출했습니다. main). 이라는 이름이 judgment 함수에 정의되지 않은 오류가 발생합니다.다른 함수의 변수 사용하기 python

코드 : trivia_points.txt 파일의

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

내용 :

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 
+2

참조 코드에 pastebin과 같은 외부 서비스를 사용하지 마십시오. 이것은 정보가 휘발성이며 곧 사라질 것입니다. SO에는 적합하지 않습니다. –

답변

3

당신은 당신의 main() 함수의 범위 밖으로 judgement(score)을 요구하고있다. score 변수는 해당 함수에서 로컬 변수입니다. 해당 줄을 들여 쓰기하여 함수 들여 쓰기와 일치시킵니다.

파이썬에서는 들여 쓰기가 구문 적 의미를 가지므로 주 기능 호출 전에 "주 기능 맨 아래에서 판단 기능을 호출하지"않습니다.

2

judgement(score)main() (모두 스크립트 하단에 있음)보다 먼저 호출하는 것 같습니다. judgement(score)main으로 옮기시겠습니까? 그런 다음 main의 로컬 복사본 score이 로컬 환경 judgement에 복사되고 전역이 필요하지 않습니다.

+0

입력에 감사드립니다. 그것은 효과가있었습니다. 판단 (점수)을 메인으로 옮김으로써 내용을 복사하거나 메인 기능에서 전체 기능을 다시 생성한다는 뜻입니까? 당신이 그 일을 할 수 있다는 것을 알지 못했습니다. – Burton

+0

필자는 @Fenikso가 말했듯이, 내가 정의한대로 함수 정의를 유지하면서 호출을 옮기기 만했습니다. 다행이야! –