HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

4) Functions and Scope Lesson

Python Function Page Layout

3 min to complete · By Martin Breuss

More code and more concepts can add up, and you might start to lose the overview inside of your own scripts. Some code might not even work the way you want it to. For example, try running the following code snippet in your editor:

print(random.randint(0, 100))
hello()

import random

def hello():
    print("hello")

Even though this code snippet consists entirely of valid Python code, you're still running into errors:

# OUTPUT
NameError: name 'random' is not defined

What Order Should You Write Your Code

Order matters because your Python script will execute from top to bottom. You'll run into two NameErrors, one about random and the other one about hello because you are attempting to use them before you define them.

The solution to this is to follow a certain order when writing a script or program:

  1. import statements at the very top
  2. followed by function definitions
  3. and finally, the code execution

You can re-organize the script shown above in this order to see it execute as intended:

# Import statements
import random

# Function definitions
def hello():
    print("hello")

# Code execution
print(random.randint(0, 100))
hello()

When you follow this basic order, it helps to avoid errors related to execution order, where you'd, for example, try to call a function before it's been defined. This structure also helps you and other coders to quickly orientate within your code and be able to read it faster.

Summary: Python Function Page Layout

  • Python code executes from top to bottom. When writing your scripts, you should stick to a basic order:
    1. import statements
    2. function definitions
    3. code execution
  • This helps to avoid errors and keep your code organized, accessible, and maintainable.
  • With this structure in mind, you're ready to dive into building some practical projects to apply your newly learned knowledge.