Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.
Scope means where a variable is visible. Return values let functions send results back so the rest of the program can use them.
Variables created inside a function are local: they only exist in that function.
def set_score():
score = 100
print(score) # 100
set_score()
print(score) # Error! score doesn't exist here
Variables defined outside functions (at the top of the file) are global and can be read inside functions. But if you assign to that name inside a function, you create a new local variable unless you use global (which we’ll avoid for now). So: prefer passing values in and returning values out instead of global variables.
Example:
def add(a, b):
total = a + b
return total
x = add(3, 5) # x is 8
print(add(10, 2)) # 12
You can return more than one value: return score, lives and then s, l = get_state().
You can use return in the middle of a function to exit early:
def is_positive(n):
if n <= 0:
return False
return True
When something goes wrong:
print(...) to see what values variables have.Write a small game or quiz that uses at least two functions that return values, e.g.:
roll_dice() returns a random number 1–6.ask_question(question, answer) returns True if the user’s input matches the answer, else False.Use the return values in your main loop to update score or state.
Next: 5.1 Pygame setup and the game loop — open a window and run a game loop.