# A Guide to Functional Programming in Python with Examples

Functional programming is an interesting programming concept which gains a lot of attention lately. This article presents some of the most important aspects of functional programming in general and provides several examples in Python.

Functional programming is a kind of the declarative programming paradigm where functions represent relations among objects, like in mathematics. Thus, functions are much more than ordinary routines.

This programming paradigm can be implemented in a variety of languages. There are several functional programming languages such as Closure, Erlang or Haskel. Many languages support functional programming in addition to other paradigms: C++, C#, F#, Java, Python, JavaScript and others.

In this article, you’ll find explanations on several important principles and concepts related to functional programming:

• pure functions,
• anonymous functions,
• recursive functions,
• first-class functions,
• immutable data types.
Pure Functions

A pure function is a function that:

• is idempotent — returns the same result if provided the same arguments,
• has no side effects.

If a function uses an object from a higher scope or random numbers, communicates with files and so on, it might be impure because its result doesn’t depend only on its arguments.

A function that modifies objects outside of its scope, write to files, prints to the console and so on, have side effects and might be impure as well.

Pure functions usually don’t use objects from outer scopes and thus avoid shared states. This might simplify a program and help escape some errors.

Anonymous Functions

Anonymous (lambda) functions can be very convenient for functional programming constructs. They don’t have names and usually are created ad-hoc, with a single purpose.

In Python, you create an anonymous function with the lambda keyword:

``````lambda x, y: x + y

``````

The above statement creates the function that accepts two arguments and returns their sum. In the next example, the functions f and g do the same thing:

``````>>> f = lambda x, y: x + y
>>> def g(x, y):
return x + y

``````
Recursive Functions

A recursive function is a function that calls itself during the execution. For example, we can use recursion to find the factorial in the functional style:

``````>>> def factorial_r(n):
if n == 0:
return 1
return n * factorial_r(n - 1)

``````

Alternatively, we can solve the same problem with the while or for loop:

``````>>> def factorial_l(n):
if n == 0:
return 1
product = 1
for i in range(1, n+1):
product *= i
return product

``````
First Class Functions

In functional programming, functions are the first-class objects, also called higher-order functions — the data types treated the same way as other types.

Functions (or, to be more precise, their pointers or references) can be passed as arguments to and returned from other functions. They can also be used as variables inside programs.

The code below illustrates passing the built-in function max as an argument of the function f and calling it from inside f.

``````>>> def f(function, *arguments):
return function(*arguments)

>>> f(max, 1, 2, 4, 8, 16)
16

``````

Very important functional programming concepts are:

• mapping,
• filtering,
• reducing.

They are all supported in Python.

Mapping is performed with the built-in class map. It takes a function (or method, or any callable) as the first argument and an iterable (like a list or tuple) as the second argument, and returns the iterator with the results of calling the function on the items of the iterable:

``````>>> list(map(abs, [-2, -1, 0, 1, 2]))
[2, 1, 0, 1, 2]

``````

In this example, the built-in function abs is called with the arguments -2, -1, 0, 1 and 2, respectively. We can obtain the same result with the list comprehension:

``````>>> [abs(item) for item in [-2, -1, 0, 1, 2]]
[2, 1, 0, 1, 2]

``````

We don’t have to use built-in functions. It is possible to provide a custom function (or method, or any callable). Lambda functions can be particularly convenient in such cases:

``````>>> list(map(lambda item: 2 * item, [-2, -1, 0, 1, 2]))
[-4, -2, 0, 2, 4]

``````

The statement above multiplied each item of the list [-2, -1, 0, 1, 2] with 2 using the custom (lambda) function lambda item: 2 * item. Of course, we can use the comprehension to achieve the same thing:

``````>>> [2 * item for item in [-2, -1, 0, 1, 2]]
[-4, -2, 0, 2, 4]

``````

Filtering is performed with the built-in class filter. It also takes a function (or method, or any callable) as the first argument and iterable as the second. It calls the function on the items of the iterable and returns a new iterable with the items for which the function returned True or anything that is evaluated as True. For example:

``````>>> list(filter(lambda item: item >= 0, [-2, -1, 0, 1, 2]))
[0, 1, 2]

``````

The statement above returns the list of non-negative items of [-2, -1, 0, 1, 2], as defined with the function lambda item: item >= 0. Again, the same result can be achieved using the comprehension:

``````>>> [item for item in [-2, -1, 0, 1, 2] if item >= 0]
[0, 1, 2]

``````

Reducing is performed with the function reduce from the module functools. Again, it takes two arguments: a function and iterable. It calls the function on the first two items of the iterable, then on the result of this operation and the third item and so on. It returns a single value. For example, we can find the sum of all items of a list like this:

``````>>> import functools
>>>
>>> functools.reduce(lambda x, y: x + y, [1, 2, 4, 8, 16])
31

``````

This example is just for illustration. The preferred way of calculating the sum is using the built-in reducing function sum:

``````>>> sum([1, 2, 4, 8, 16])
31

``````
Immutable Data Types

An immutable object is an object whose state can’t be modified once it’s created. Contrary, a mutable object allows changes in its state.

Immutable objects are generally desirable in functional programming.

For example, in Python, lists are mutable, while tuples are immutable:

``````>>> a = [1, 2, 4, 8, 16] >>> a[0] = 32 # OK. You can modify lists.
>>> a
[32, 2, 4, 8, 16]
>>> a = (1, 2, 4, 8, 16)
>>> a[0] = 32 # Wrong! You can't modify tuples.
Traceback (most recent call last):
File "", line 1, in
TypeError: 'tuple' object does not support item assignment

``````

We can modify lists by appending them new elements, but when we try to do this with tuples, they are not changed but new instances are created:

``````>>> # Lists (mutable)
>>> a = [1, 2, 4] # a is a list
>>> b = a # a and b refer to the same list object
>>> id(a) == id(b)
True
>>> a += [8, 16] # a is modified and so is b - they refer to the same object
>>> a
[1, 2, 4, 8, 16]
>>> b
[1, 2, 4, 8, 16]
>>> id(a) == id(b)
True
>>>
>>> # Tuples (immutable)
>>> a = (1, 2, 4) # a is a tuple
>>> b = a # a and b refer to the same tuple object
>>> id(a) == id(b)
True
>>> a += (8, 16) # new tuple is created and assigned to a; b is unchanged
>>> a # a refers to the new object
(1, 2, 4, 8, 16)
>>> b # b refers to the old object
(1, 2, 4)
>>> id(a) == id(b)
False

``````

The underlying concepts and principles — especially higher-order functions, immutable data and the lack of side effects — imply important advantages of functional programs:

• they might be easier to comprehend, implement, test and debug,
• they might be shorter and more concise (compare two programs for calculating the factorial above),
• they might be less error-prone,
• they are easier to work with when implementing parallel execution.

Functional programming is a valuable paradigm worth learning. In addition to the advantages listed above, it’ll probably give you a new perspective on solving programming problems.

## Python Tutorial | Python Functions and Functional Programming

In this post, we will introduce a functional programming model. We learn about lambda expressions in Python, important function functions and the concept of particles.

Most of us have been introduced to Python as an `object-oriented` language, but Python functions are also useful tools for data scientists and programmers alike. While classes, and objects, are easy to start working with, there are other ways to write your Python code. Languages like Java can make it hard to move away from object-oriented thinking, but Python makes it easy.

Given that Python facilitates different approaches to writing code, a logical follow-up question is: what is a different way to write code? While there are several answers to this question, the most common alternative style of writing code is called` functional programming`. Functional programming gets its name from writing functions which provides the main source of logic in a program.

In this post, we will:

• Explain the basics of functional programming by comparing it to object-oriented programming.

• Cover why you might want to incorporate functional programming in your own code.

• Show you how Python allows you to switch between the two.

Comparing object-oriented to functional

The easiest way to introduce functional programming is to compare it to something we’re already aware of: object-oriented programming. Suppose we wanted to create a line counter class that takes in a file, reads each line, then counts the total amount of lines in the file. Using a class, it could look something like the following:

``````class LineCounter:
def __init__(self, filename):
self.file = open(filename, 'r')
self.lines = []

self.lines = [line for line in self.file]

def count(self):
return len(self.lines)
``````

While not the best implementation, it does provide an insight into object-oriented design. Within the class, there are the familiar concepts of methods and properties. The properties set and retrieve the state of the object, and the methods manipulate that state.

For both these concepts to work, the object’s state must change over time. This change of state is evident in the `lines` property after calling the `read()` method. As an example, here’s how we would use this class:

``````# example_file.txt contains 100 lines.
lc = LineCounter('example_file.txt')
print(lc.lines)
>> []
print(lc.count())
>> 0

# The lc object must read the file to
# set the lines property.
# The `lc.lines` property has been changed.
# This is called changing the state of the lc
# object.
print(lc.lines)
>> [['Hello world!', ...]]
print(lc.count())
>> 100

``````

The ever-changing state of an object is both its blessing and curse. To understand why a changing state can be seen as a negative, we have to introduce an alternative. The alternative is to build the line counter as a series of independent functions.

``````def read(filename):
with open(filename, 'r') as f:
return [line for line in f]

def count(lines):
return len(lines)

lines_count = count(example_lines)

``````
Working with pure functions

In the previous example, we were able to count the lines only with the use of functions. When we only use functions, we are applying a functional approach to programming which is, non-excitingly, called functional programming. The concepts behind functional programming requires functions to be `stateless`, and rely only on their given inputs to produce an output.

The functions that meet the above criteria are called `pure functions`. Here’s an example to highlight the difference between pure functions, and non-pure:

``````# Create a global variable `A`.
A = 5

def impure_sum(b):
# Adds two numbers, but uses the
# global `A` variable.
return b + A

def pure_sum(a, b):
# ONLY the local function inputs.
return a + b

print(impure_sum(6))
>> 11

print(pure_sum(4, 6))
>> 10

``````

The benefit of using pure functions over impure (non-pure) functions is the reduction of side effects. **Side effects **occur when there are changes performed within a function’s operation that are outside its scope. For example, they occur when we change the state of an object, perform any I/O operation, or even call `print()`:

``````def read_and_print(filename):
with open(filename) as f:
# Side effect of opening a
# file outside of function.
data = [line for line in f]
for line in data:
# Call out to the operating system
# "println" method (side effect).
print(line)

``````

Programmers reduce side effects in their code to make it easier to follow, test, and debug. The more side effects a codebase has, the harder it is to step through a program and understand its sequence of execution.

While it’s convienent to try and eliminate all side effects, they’re often used to make programming easier. If we were to ban all side effects, then you wouldn’t be able to read in a file, call print, or even assign a variable within a function. Advocates for functional programming understand this tradeoff, and try to eliminate side effects where possible without sacrificing development implementation time.

The Lambda Expression

Instead of the `def` syntax for function declaration, we can use a lambda expression to write Python functions. The lambda syntax closely follows the `def` syntax, but it’s not a 1-to-1 mapping. Here’s an example of building a function that adds two integers:

``````# Using `def` (old way).
return a + b

# Using `lambda` (new way).
>> True

``````

The `lambda` expression takes in a comma seperated sequences of inputs (like `def`). Then, immediately following the colon, it returns the expression without using an explicit return statement. Finally, when assigning the`lambda` expression to a variable, it acts exactly like a Python function, and can be called using the the function call syntax: `new_add()`.

If we didn’t assign `lambda` to a variable name, it would be called an anonymous function. These** anonymous functions** are extremely helpful, especially when using them as an input for another function. For example, the `sorted()` function takes in an optional `key` argument (a function) that describes how the items in a list should be sorted.

``````unsorted = [('b', 6), ('a', 10), ('d', 0), ('c', 4)]

# Sort on the second tuple value (the integer).
print(sorted(unsorted, key=lambda x: x[1]))
>> [('d', 0), ('c', 4), ('b', 6), ('a', 10)]

``````
The Map Function

While the ability to pass in functions as arguments is not unique to Python, it is a recent development in programming languages. Functions that allow for this type of behavior are called** first-class functions**. Any language that contains first-class functions can be written in a functional style.

There are a set of important first-class functions that are commonly used within the functional paradigm. These functions take in a Python iterable, and, like `sorted()`, apply a function for each element in the list. Over the next few sections, we will examine each of these functions, but they all follow the general form of `function_name(function_to_apply, iterable_of_elements)`.

The first function we’ll work with is the `map()` function. The `map()` function takes in an iterable (ie. `list`), and creates a new iterable object, a special `map` object. The new object has the first-class function applied to every element.

``````# Pseudocode for map.
def map(func, seq):
# Return `Map` object with
# the function applied to every
# element.
return Map(
func(x)
for x in seq
)

``````

Here’s how we could use map to add `10` or `20` to every element in a list:

``````values = [1, 2, 3, 4, 5]

# Note: We convert the returned map object to
# a list data structure.
add_10 = list(map(lambda x: x + 10, values))
add_20 = list(map(lambda x: x + 20, values))

>> [11, 12, 13, 14, 15]

>> [21, 22, 23, 24, 25]

``````

Note that it’s important to cast the return value from `map()` as a `list` object. Using the returned `map` object is difficult to work with if you’re expecting it to function like a `list`. First, printing it does not show each of its items, and secondly, you can only iterate over it once.

The Filter Function

The second function we’ll work with is the `filter()` function. The `filter()` function takes in an iterable, creates a new iterable object (again, a special `map` object), and a first-class function that must return a `bool` value. The new map object is a filtered iterable of all elements that returned `True`.

``````# Pseudocode for filter.
def filter(evaluate, seq):
# Return `Map` object with
# the evaluate function applied to every
# element.
return Map(
x for x in seq
if evaluate(x) is True
)

``````

Here’s how we could filter odd or even values from a list:

``````values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Note: We convert the returned filter object to
# a list data structure.
even = list(filter(lambda x: x % 2 == 0, values))
odd = list(filter(lambda x: x % 2 == 1, values))

print(even)
>> [2, 4, 6, 8, 10]

print(odd)
>> [1, 3, 5, 7, 9]

``````
The Reduce Function

The last function we’ll look at is the reduce() function from the functools package. The `reduce()` function takes in an iterable, and then reduces the iterable to a single value. Reduce is different from `filter()` and `map()`, because reduce() takes in a function that has two input values.

Here’s an example of how we can use `reduce()` to sum all elements in a list.

``````from functools import reduce

values = [1, 2, 3, 4]

summed = reduce(lambda a, b: a + b, values)
print(summed)
>> 10

``````

An interesting note to make is that you do not have to operate on the second value in the `lambda` expression. For example, you can write a function that always returns the first value of an iterable:

``````from functools import reduce

values = [1, 2, 3, 4, 5]

# By convention, we add `_` as a placeholder for an input
# we do not use.
first_value = reduce(lambda a, _: a, values)
print(first_value)
>> 1

``````
Rewriting with list comprehensions

Because we eventually convert to lists, we should rewrite the `map()` and `filter()` functions using list comprehension instead. This is the more pythonic way of writing them, as we are taking advantage of the Python syntax for making lists. Here’s how you could translate the previous examples of `map()` and `filter()` to list comprehensions:

``````values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Map.
add_10 = [x + 10 for x in values]
>> [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

# Filter.
even = [x for x in values if x % 2 == 0]
print(even)
>> [2, 4, 6, 8, 10]

``````

From the examples, you can see that we don’t need to add the lambda expressions. If you are looking to add `map()`, or `filter(`) functions to your own code, this is usually the recommended way. However, in the next section, we’ll provide a case to still use the `map()` and `filter()` functions.

Writing Function Partials

Sometimes we want to use the behavior of a function, but decrease the number of arguments it takes. The purpose is to “save” one of the inputs, and create a new function that defaults the behavior using the saved input. Suppose we wanted to write a function that would always add 2 to any number:

``````def add_two(b):
return 2 + b

>> 6

``````

The`add_two` function is similar to the general function, \$f(a,b) = a + b\$, only it defaults one of the arguments (\$a = 2\$). In Python, we can use the partial module from the `functools` package to set these argument defaults. The `partial` module takes in a function, and “freezes” any number of args (or kwargs), starting from the first argument, then returns a new function with the default inputs.

``````from functools import partialdef add(a, b):
return a + b

>> 6
>> 14

``````

Partials can take in any function, including ones from the standard library.

``````# A partial that grabs IP addresses using
# the `map` function from the standard library.
extract_ips = partial(
map,
lambda x: x.split(' ')[0]
)

``````
Summary

In this post, we introduced the paradigm of functional programming. We learned about the lambda expression in Python, important functional functions, and the concept of partials. Overall, we showed that Python provides a programmer with the tools to easily switch between functional programming and object-oriented programming.

## The Python range() Function

Python’s built-in range function is handy when you need to perform an action a specific number of times. As an experienced Pythonista, you’ve most likely used it before. But what does it do?

`range()` is a built-in function of Python. It is used when a user needs to perform an action for a specific number of times. `range()` in Python(3.x) is just a renamed version of a function called `xrange` in Python(2.x). The range() function is used to generate a sequence of numbers.

`range()` is commonly used in for looping hence, knowledge of same is key aspect when dealing with any kind of Python code. Most common use of `range()` function in Python is to iterate sequence type (List, string etc.. ) with for and while loop.

Python `range()` Basics :
In simple terms, `range()` allows user to generate a series of numbers within a given range. Depending on how many arguments user is passing to the function, user can decide where that series of numbers will begin and end as well as how big the difference will be between one number and the next.`range()` takes mainly three arguments.

• start: integer starting from which the sequence of integers is to be returned
• stop: integer before which the sequence of integers is to be returned.
The range of integers end at stop – 1.
• step: integer value which determines the increment between each integer in the sequence
``````# Python Program to
# show range() basics

# printing a number
for i in range(10):
print(i, end =" ")
print()

# using range for iteration
l = [10, 20, 30, 40]
for i in range(len(l)):
print(l[i], end =" ")
print()

# performing sum of natural
# number
sum = 0
for i in range(1, 10):
sum = sum + i
print("Sum of first 10 natural number :", sum)

``````

Output :

``````0 1 2 3 4 5 6 7 8 9
10 20 30 40
Sum of first 10 natural number : 45
``````

There are three ways you can call `range() :`

• `range(stop)` takes one argument.
• `range(start, stop)` takes two arguments.
• `range(start, stop, step)` takes three arguments.

#### range(stop)

When user call `range()` with one argument, user will get a series of numbers that starts at 0 and includes every whole number up to, but not including, the number that user have provided as the stop. For Example

``````# Python program to
# print whole number
# using range()

# printing first 10
# whole number
for i in range(10):
print(i, end =" ")
print()

# printing first 20
# whole number
for i in range(20):
print(i, end = " ")

``````

Output:

``````0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
``````
range(start, stop)

When user call range() with two arguments, user get to decide not only where the series of numbers stops but also where it starts, so user don’t have to start at 0 all the time. User can use `range()` to generate a series of numbers from X to Y using a range(X, Y). For Example:

``````# Python program to
# print natural number
# using range

# printing a natural
# number upto 20
for i in range(1, 20):
print(i, end =" ")
print()

# printing a natural
# number from 5 t0 20
for i in range(5, 20):
print(i, end =" ")

``````

Output:

``````1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
``````
range(start, stop, step)

When user call `range()` with three arguments, user can choose not only where the series of numbers will start and stop but also how big the difference will be between one number and the next. If user don’t provide a step, then range() will automatically behave as if the step is 1.

``````# Python program to
# print all number
# divisible by 3 and 5

# using range to print number
# divisible by 3
for i in range(0, 30, 3):
print(i, end = " ")
print()

# using range to print number
# divisible by 5
for i in range(0, 50, 5):
print(i, end = " ")

``````

Output :

``````0 3 6 9 12 15 18 21 24 27
0 5 10 15 20 25 30 35 40 45
``````

In this example, we are printing an even number between 0 to 10 so we choose our starting point from 0(start = 0) and stop the series at 10(stop = 10). For printing even number the difference between one number and the next must be 2 (step = 2) after providing a step we get a following output ( 0, 2, 4, 8).

Incrementing with range using positive step :
If user want to increment, then user need `step` to be a positive number. For example:

``````# Python program to
# increment with
# range()

# incremented by 2
for i in range(2, 25, 2):
print(i, end =" ")
print()

# incremented by 4
for i in range(0, 30, 4):
print(i, end =" ")
print()

# incremented by 3
for i in range(15, 25, 3):
print(i, end =" ")

``````

Output :

``````2 4 6 8 10 12 14 16 18 20 22 24
0 4 8 12 16 20 24 28
15 18 21 24
``````

Decrementing with range using negative step :
If user want to decrement, then user need `step` to be a negative number. For example:

``````# Python program to
# decrement with
# range()

# incremented by -2
for i in range(25, 2, -2):
print(i, end =" ")
print()

# incremented by -4
for i in range(30, 1, -4):
print(i, end =" ")
print()

# incremented by -3
for i in range(25, -6, -3):
print(i, end =" ")

``````

Output :

``````25 23 21 19 17 15 13 11 9 7 5 3
30 26 22 18 14 10 6 2
25 22 19 16 13 10 7 4 1 -2 -5
``````

Using float Numbers in Python range() :
Python `range()` function doesn’t support the float numbers. i.e. user cannot use floating-point or non-integer number in any of its argument. User can use only integer numbers.For example

``````# Python program to
# show using float
# number in range()

# using a float number
for i in range(3.3):
print(i)

# using a float number
for i in range(5.5):
print(i)

``````

Output :

``````for i in range(3.3):
TypeError: 'float' object cannot be interpreted as an integer
``````

Points to remember about Python `range()` function :

• `range()` function only works with the integers i.e. whole numbers.
• All argument must be integers. User can not pass a string or float number or any other type in a start, stop and step argument of a range().
• All three arguments can be positive or negative.
• The step value must not be zero. If a step is zero python raises a ValueError exception.
• `range()` is a type in Python
``````# Python program to
# show range() type

# checking a type of
# range
type(range(3))

``````
• User can access items in a `range()` by index, just as user do with a list:
``````# Python program to
# access items in a range

# accessing a items
range(3)[1]

# accessing a items
range(3)[2]

``````

## Defining Main Functions in Python

• A Basic Python main()
• Execution Modes in Python
Executing From the Command LineImporting Into a Module or the Interactive Interpreter* Best Practices for Python Main Functions
Put Most Code Into a Function or ClassUse name to Control the Execution of Your CodeCreate a Function Called main() to Contain the Code You Want to RunCall Other Functions From main()Summary of Python Main Function Best Practices* Conclusion

Many programming languages have a special function that is automatically executed when an operating system starts to run a program. This function is usually called `main()` and must have a specific return type and arguments according to the language standard. On the other hand, the Python interpreter executes scripts starting at the top of the file, and there is no specific function that Python automatically executes.

Nevertheless, having a defined starting point for the execution of a program is useful for understanding how a program works. Python programmers have come up with several conventions to define this starting point.

• What the special `__name__` variable is and how Python defines it
• Why you would want to use a `main()` in Python
• What conventions there are for defining `main()` in Python
• What the best-practices are for what code to put into your `main()`
A Basic Python main()

In some Python scripts, you may see a function definition and a conditional statement that looks like the example below:

``````def main():
print("Hello World!")

if __name__ == "__main__":
main()

``````

In this code, there is a function called `main()` that prints the phrase `Hello World!` when the Python interpreter executes it. There is also a conditional (or `if`) statement that checks the value of `__name__` and compares it to the string `"__main__"`. When the `if` statement evaluates to `True`, the Python interpreter executes `main()`. You can read more about conditional statements in Conditional Statements in Python.

This code pattern is quite common in Python files that you want to be executed as a script and imported in another module. To help understand how this code will execute, you should first understand how the Python interpreter sets `__name__` depending on how the code is being executed.

Execution Modes in Python

There are two primary ways that you can instruct the Python interpreter to execute or use code:

1. You can execute the Python file as a script using the command line.
2. You can import the code from one Python file into another file or into the interactive interpreter.

You can read a lot more about these approaches in How to Run Your Python Scripts. No matter which way of running your code you’re using, Python defines a special variable called `__name__` that contains a string whose value depends on how the code is being used.

We’ll use this example file, saved as `execution_methods.py`, to explore how the behavior of the code changes depending on the context:

``````print("This is my file to test Python's execution methods.")
print("The variable __name__ tells me which context this file is running in.")
print("The value of __name__ is:", repr(__name__))

``````

In this file, there are three calls to `print()` defined. The first two print some introductory phrases. The third `print()` will first print the phrase `The value of __name__ is`, and then it will print the representation of the `__name__` variable using Python’s built-in `repr()`.

In Python, `repr()` displays the printable representation of an object. This example uses `repr()` to emphasize that the value of `__name__` is a string. You can read more about `repr()` in the Python documentation.

You’ll see the words file, module, and script used throughout this article. Practically, there isn’t much difference between them. However, there are slight differences in meaning that emphasize the purpose of a piece of code:

1. File: Typically, a Python file is any file that contains code. Most Python files have the extension `.py`.
2. Script: A Python script is a file that you intend to execute from the command line to accomplish a task.
3. Module: A Python module is a file that you intend to import from within another module or a script, or from the interactive interpreter. You can read more about modules in the Python documentation.

This distinction is also discussed in How to Run Your Python Scripts.

### Executing From the Command Line

In this approach, you want to execute your Python script from the command line.

When you execute a script, you will not be able to interactively define the code that the Python interpreter is executing. The details of how you can execute Python from your command line are not that important for the purpose of this article, but you can expand the box below to read more about the differences between the command line on Windows, Linux, and macOS.

The way that you tell the computer to execute code from the command line is slightly different depending on your operating system.

On Linux and macOS, the command line typically looks like the example below:

``````[email protected]:~/Documents\$

``````

• A Basic Python main()
• Execution Modes in Python
Executing From the Command LineImporting Into a Module or the Interactive Interpreter* Best Practices for Python Main Functions
Put Most Code Into a Function or ClassUse name to Control the Execution of Your CodeCreate a Function Called main() to Contain the Code You Want to RunCall Other Functions From main()Summary of Python Main Function Best Practices* Conclusion

Many programming languages have a special function that is automatically executed when an operating system starts to run a program. This function is usually called `main()` and must have a specific return type and arguments according to the language standard. On the other hand, the Python interpreter executes scripts starting at the top of the file, and there is no specific function that Python automatically executes.

Nevertheless, having a defined starting point for the execution of a program is useful for understanding how a program works. Python programmers have come up with several conventions to define this starting point.

• What the special `__name__` variable is and how Python defines it
• Why you would want to use a `main()` in Python
• What conventions there are for defining `main()` in Python
• What the best-practices are for what code to put into your `main()`
A Basic Python main()

In some Python scripts, you may see a function definition and a conditional statement that looks like the example below:

``````def main():
print("Hello World!")

if __name__ == "__main__":
main()

``````

In this code, there is a function called `main()` that prints the phrase `Hello World!` when the Python interpreter executes it. There is also a conditional (or `if`) statement that checks the value of `__name__` and compares it to the string `"__main__"`. When the `if` statement evaluates to `True`, the Python interpreter executes `main()`. You can read more about conditional statements in Conditional Statements in Python.

This code pattern is quite common in Python files that you want to be executed as a script and imported in another module. To help understand how this code will execute, you should first understand how the Python interpreter sets `__name__` depending on how the code is being executed.

Execution Modes in Python

There are two primary ways that you can instruct the Python interpreter to execute or use code:

1. You can execute the Python file as a script using the command line.
2. You can import the code from one Python file into another file or into the interactive interpreter.

You can read a lot more about these approaches in How to Run Your Python Scripts. No matter which way of running your code you’re using, Python defines a special variable called `__name__` that contains a string whose value depends on how the code is being used.

We’ll use this example file, saved as `execution_methods.py`, to explore how the behavior of the code changes depending on the context:

``````print("This is my file to test Python's execution methods.")
print("The variable __name__ tells me which context this file is running in.")
print("The value of __name__ is:", repr(__name__))

``````

In this file, there are three calls to `print()` defined. The first two print some introductory phrases. The third `print()` will first print the phrase `The value of __name__ is`, and then it will print the representation of the `__name__` variable using Python’s built-in `repr()`.

In Python, `repr()` displays the printable representation of an object. This example uses `repr()` to emphasize that the value of `__name__` is a string. You can read more about `repr()` in the Python documentation.

You’ll see the words file, module, and script used throughout this article. Practically, there isn’t much difference between them. However, there are slight differences in meaning that emphasize the purpose of a piece of code:

1. File: Typically, a Python file is any file that contains code. Most Python files have the extension `.py`.
2. Script: A Python script is a file that you intend to execute from the command line to accomplish a task.
3. Module: A Python module is a file that you intend to import from within another module or a script, or from the interactive interpreter. You can read more about modules in the Python documentation.

This distinction is also discussed in How to Run Your Python Scripts.

### Executing From the Command Line

In this approach, you want to execute your Python script from the command line.

When you execute a script, you will not be able to interactively define the code that the Python interpreter is executing. The details of how you can execute Python from your command line are not that important for the purpose of this article, but you can expand the box below to read more about the differences between the command line on Windows, Linux, and macOS.

The way that you tell the computer to execute code from the command line is slightly different depending on your operating system.

On Linux and macOS, the command line typically looks like the example below:

``````[email protected]:~/Documents\$

``````

• A Basic Python main()
• Execution Modes in Python
Executing From the Command LineImporting Into a Module or the Interactive Interpreter* Best Practices for Python Main Functions
Put Most Code Into a Function or ClassUse name to Control the Execution of Your CodeCreate a Function Called main() to Contain the Code You Want to RunCall Other Functions From main()Summary of Python Main Function Best Practices* Conclusion

Many programming languages have a special function that is automatically executed when an operating system starts to run a program. This function is usually called `main()` and must have a specific return type and arguments according to the language standard. On the other hand, the Python interpreter executes scripts starting at the top of the file, and there is no specific function that Python automatically executes.

Nevertheless, having a defined starting point for the execution of a program is useful for understanding how a program works. Python programmers have come up with several conventions to define this starting point.

• What the special `__name__` variable is and how Python defines it
• Why you would want to use a `main()` in Python
• What conventions there are for defining `main()` in Python
• What the best-practices are for what code to put into your `main()`
A Basic Python main()

In some Python scripts, you may see a function definition and a conditional statement that looks like the example below:

``````def main():
print("Hello World!")

if __name__ == "__main__":
main()

``````

In this code, there is a function called `main()` that prints the phrase `Hello World!` when the Python interpreter executes it. There is also a conditional (or `if`) statement that checks the value of `__name__` and compares it to the string `"__main__"`. When the `if` statement evaluates to `True`, the Python interpreter executes `main()`. You can read more about conditional statements in Conditional Statements in Python.

This code pattern is quite common in Python files that you want to be executed as a script and imported in another module. To help understand how this code will execute, you should first understand how the Python interpreter sets `__name__` depending on how the code is being executed.

Execution Modes in Python

There are two primary ways that you can instruct the Python interpreter to execute or use code:

1. You can execute the Python file as a script using the command line.
2. You can import the code from one Python file into another file or into the interactive interpreter.

You can read a lot more about these approaches in How to Run Your Python Scripts. No matter which way of running your code you’re using, Python defines a special variable called `__name__` that contains a string whose value depends on how the code is being used.

We’ll use this example file, saved as `execution_methods.py`, to explore how the behavior of the code changes depending on the context:

``````print("This is my file to test Python's execution methods.")
print("The variable __name__ tells me which context this file is running in.")
print("The value of __name__ is:", repr(__name__))

``````

In this file, there are three calls to `print()` defined. The first two print some introductory phrases. The third `print()` will first print the phrase `The value of __name__ is`, and then it will print the representation of the `__name__` variable using Python’s built-in `repr()`.

In Python, `repr()` displays the printable representation of an object. This example uses `repr()` to emphasize that the value of `__name__` is a string. You can read more about `repr()` in the Python documentation.

You’ll see the words file, module, and script used throughout this article. Practically, there isn’t much difference between them. However, there are slight differences in meaning that emphasize the purpose of a piece of code:

1. File: Typically, a Python file is any file that contains code. Most Python files have the extension `.py`.
2. Script: A Python script is a file that you intend to execute from the command line to accomplish a task.
3. Module: A Python module is a file that you intend to import from within another module or a script, or from the interactive interpreter. You can read more about modules in the Python documentation.

This distinction is also discussed in How to Run Your Python Scripts.

### Executing From the Command Line

In this approach, you want to execute your Python script from the command line.

When you execute a script, you will not be able to interactively define the code that the Python interpreter is executing. The details of how you can execute Python from your command line are not that important for the purpose of this article, but you can expand the box below to read more about the differences between the command line on Windows, Linux, and macOS.

The way that you tell the computer to execute code from the command line is slightly different depending on your operating system.

On Linux and macOS, the command line typically looks like the example below:

``````[email protected]:~/Documents\$

``````

• A Basic Python main()
• Execution Modes in Python
Executing From the Command LineImporting Into a Module or the Interactive Interpreter* Best Practices for Python Main Functions
Put Most Code Into a Function or ClassUse name to Control the Execution of Your CodeCreate a Function Called main() to Contain the Code You Want to RunCall Other Functions From main()Summary of Python Main Function Best Practices* Conclusion

Many programming languages have a special function that is automatically executed when an operating system starts to run a program. This function is usually called `main()` and must have a specific return type and arguments according to the language standard. On the other hand, the Python interpreter executes scripts starting at the top of the file, and there is no specific function that Python automatically executes.

Nevertheless, having a defined starting point for the execution of a program is useful for understanding how a program works. Python programmers have come up with several conventions to define this starting point.

• What the special `__name__` variable is and how Python defines it
• Why you would want to use a `main()` in Python
• What conventions there are for defining `main()` in Python
• What the best-practices are for what code to put into your `main()`
A Basic Python main()

In some Python scripts, you may see a function definition and a conditional statement that looks like the example below:

``````def main():
print("Hello World!")

if __name__ == "__main__":
main()

``````

In this code, there is a function called `main()` that prints the phrase `Hello World!` when the Python interpreter executes it. There is also a conditional (or `if`) statement that checks the value of `__name__` and compares it to the string `"__main__"`. When the `if` statement evaluates to `True`, the Python interpreter executes `main()`. You can read more about conditional statements in Conditional Statements in Python.

This code pattern is quite common in Python files that you want to be executed as a script and imported in another module. To help understand how this code will execute, you should first understand how the Python interpreter sets `__name__` depending on how the code is being executed.

Execution Modes in Python

There are two primary ways that you can instruct the Python interpreter to execute or use code:

1. You can execute the Python file as a script using the command line.
2. You can import the code from one Python file into another file or into the interactive interpreter.

You can read a lot more about these approaches in How to Run Your Python Scripts. No matter which way of running your code you’re using, Python defines a special variable called `__name__` that contains a string whose value depends on how the code is being used.

We’ll use this example file, saved as `execution_methods.py`, to explore how the behavior of the code changes depending on the context:

``````print("This is my file to test Python's execution methods.")
print("The variable __name__ tells me which context this file is running in.")
print("The value of __name__ is:", repr(__name__))

``````

In this file, there are three calls to `print()` defined. The first two print some introductory phrases. The third `print()` will first print the phrase `The value of __name__ is`, and then it will print the representation of the `__name__` variable using Python’s built-in `repr()`.

In Python, `repr()` displays the printable representation of an object. This example uses `repr()` to emphasize that the value of `__name__` is a string. You can read more about `repr()` in the Python documentation.

You’ll see the words file, module, and script used throughout this article. Practically, there isn’t much difference between them. However, there are slight differences in meaning that emphasize the purpose of a piece of code:

1. File: Typically, a Python file is any file that contains code. Most Python files have the extension `.py`.
2. Script: A Python script is a file that you intend to execute from the command line to accomplish a task.
3. Module: A Python module is a file that you intend to import from within another module or a script, or from the interactive interpreter. You can read more about modules in the Python documentation.

This distinction is also discussed in How to Run Your Python Scripts.

### Executing From the Command Line

In this approach, you want to execute your Python script from the command line.

When you execute a script, you will not be able to interactively define the code that the Python interpreter is executing. The details of how you can execute Python from your command line are not that important for the purpose of this article, but you can expand the box below to read more about the differences between the command line on Windows, Linux, and macOS.

The way that you tell the computer to execute code from the command line is slightly different depending on your operating system.

On Linux and macOS, the command line typically looks like the example below:

``````[email protected]:~/Documents\$

``````

The part before the dollar sign (`) may look different, depending on your username and your computer’s name. The commands that you type will go after the `. On Linux or macOS, the name of the Python 3 executable is `python3`, so you should run Python scripts by typing `python3 script_name.py` after the ```Table of Contents

• A Basic Python main()
• Execution Modes in Python
Executing From the Command LineImporting Into a Module or the Interactive Interpreter* Best Practices for Python Main Functions
Put Most Code Into a Function or ClassUse name to Control the Execution of Your CodeCreate a Function Called main() to Contain the Code You Want to RunCall Other Functions From main()Summary of Python Main Function Best Practices* Conclusion

Many programming languages have a special function that is automatically executed when an operating system starts to run a program. This function is usually called `main()` and must have a specific return type and arguments according to the language standard. On the other hand, the Python interpreter executes scripts starting at the top of the file, and there is no specific function that Python automatically executes.

Nevertheless, having a defined starting point for the execution of a program is useful for understanding how a program works. Python programmers have come up with several conventions to define this starting point.

• What the special `__name__` variable is and how Python defines it
• Why you would want to use a `main()` in Python
• What conventions there are for defining `main()` in Python
• What the best-practices are for what code to put into your `main()`
A Basic Python main()

In some Python scripts, you may see a function definition and a conditional statement that looks like the example below:

``````def main():
print("Hello World!")

if __name__ == "__main__":
main()

``````

In this code, there is a function called `main()` that prints the phrase `Hello World!` when the Python interpreter executes it. There is also a conditional (or `if`) statement that checks the value of `__name__` and compares it to the string `"__main__"`. When the `if` statement evaluates to `True`, the Python interpreter executes `main()`. You can read more about conditional statements in Conditional Statements in Python.

This code pattern is quite common in Python files that you want to be executed as a script and imported in another module. To help understand how this code will execute, you should first understand how the Python interpreter sets `__name__` depending on how the code is being executed.

Execution Modes in Python

There are two primary ways that you can instruct the Python interpreter to execute or use code:

1. You can execute the Python file as a script using the command line.
2. You can import the code from one Python file into another file or into the interactive interpreter.

You can read a lot more about these approaches in How to Run Your Python Scripts. No matter which way of running your code you’re using, Python defines a special variable called `__name__` that contains a string whose value depends on how the code is being used.

We’ll use this example file, saved as `execution_methods.py`, to explore how the behavior of the code changes depending on the context:

``````print("This is my file to test Python's execution methods.")
print("The variable __name__ tells me which context this file is running in.")
print("The value of __name__ is:", repr(__name__))

``````

In this file, there are three calls to `print()` defined. The first two print some introductory phrases. The third `print()` will first print the phrase `The value of __name__ is`, and then it will print the representation of the `__name__` variable using Python’s built-in `repr()`.

In Python, `repr()` displays the printable representation of an object. This example uses `repr()` to emphasize that the value of `__name__` is a string. You can read more about `repr()` in the Python documentation.

You’ll see the words file, module, and script used throughout this article. Practically, there isn’t much difference between them. However, there are slight differences in meaning that emphasize the purpose of a piece of code:

1. File: Typically, a Python file is any file that contains code. Most Python files have the extension `.py`.
2. Script: A Python script is a file that you intend to execute from the command line to accomplish a task.
3. Module: A Python module is a file that you intend to import from within another module or a script, or from the interactive interpreter. You can read more about modules in the Python documentation.

This distinction is also discussed in How to Run Your Python Scripts.

### Executing From the Command Line

In this approach, you want to execute your Python script from the command line.

When you execute a script, you will not be able to interactively define the code that the Python interpreter is executing. The details of how you can execute Python from your command line are not that important for the purpose of this article, but you can expand the box below to read more about the differences between the command line on Windows, Linux, and macOS.

The way that you tell the computer to execute code from the command line is slightly different depending on your operating system.

On Linux and macOS, the command line typically looks like the example below:

``````[email protected]:~/Documents\$

``````

• A Basic Python main()
• Execution Modes in Python
Executing From the Command LineImporting Into a Module or the Interactive Interpreter* Best Practices for Python Main Functions
Put Most Code Into a Function or ClassUse name to Control the Execution of Your CodeCreate a Function Called main() to Contain the Code You Want to RunCall Other Functions From main()Summary of Python Main Function Best Practices* Conclusion

Many programming languages have a special function that is automatically executed when an operating system starts to run a program. This function is usually called `main()` and must have a specific return type and arguments according to the language standard. On the other hand, the Python interpreter executes scripts starting at the top of the file, and there is no specific function that Python automatically executes.

Nevertheless, having a defined starting point for the execution of a program is useful for understanding how a program works. Python programmers have come up with several conventions to define this starting point.

• What the special `__name__` variable is and how Python defines it
• Why you would want to use a `main()` in Python
• What conventions there are for defining `main()` in Python
• What the best-practices are for what code to put into your `main()`
A Basic Python main()

In some Python scripts, you may see a function definition and a conditional statement that looks like the example below:

``````def main():
print("Hello World!")

if __name__ == "__main__":
main()

``````

In this code, there is a function called `main()` that prints the phrase `Hello World!` when the Python interpreter executes it. There is also a conditional (or `if`) statement that checks the value of `__name__` and compares it to the string `"__main__"`. When the `if` statement evaluates to `True`, the Python interpreter executes `main()`. You can read more about conditional statements in Conditional Statements in Python.

This code pattern is quite common in Python files that you want to be executed as a script and imported in another module. To help understand how this code will execute, you should first understand how the Python interpreter sets `__name__` depending on how the code is being executed.

Execution Modes in Python

There are two primary ways that you can instruct the Python interpreter to execute or use code:

1. You can execute the Python file as a script using the command line.
2. You can import the code from one Python file into another file or into the interactive interpreter.

You can read a lot more about these approaches in How to Run Your Python Scripts. No matter which way of running your code you’re using, Python defines a special variable called `__name__` that contains a string whose value depends on how the code is being used.

We’ll use this example file, saved as `execution_methods.py`, to explore how the behavior of the code changes depending on the context:

``````print("This is my file to test Python's execution methods.")
print("The variable __name__ tells me which context this file is running in.")
print("The value of __name__ is:", repr(__name__))

``````

In this file, there are three calls to `print()` defined. The first two print some introductory phrases. The third `print()` will first print the phrase `The value of __name__ is`, and then it will print the representation of the `__name__` variable using Python’s built-in `repr()`.

In Python, `repr()` displays the printable representation of an object. This example uses `repr()` to emphasize that the value of `__name__` is a string. You can read more about `repr()` in the Python documentation.

You’ll see the words file, module, and script used throughout this article. Practically, there isn’t much difference between them. However, there are slight differences in meaning that emphasize the purpose of a piece of code:

1. File: Typically, a Python file is any file that contains code. Most Python files have the extension `.py`.
2. Script: A Python script is a file that you intend to execute from the command line to accomplish a task.
3. Module: A Python module is a file that you intend to import from within another module or a script, or from the interactive interpreter. You can read more about modules in the Python documentation.

This distinction is also discussed in How to Run Your Python Scripts.

### Executing From the Command Line

In this approach, you want to execute your Python script from the command line.

When you execute a script, you will not be able to interactively define the code that the Python interpreter is executing. The details of how you can execute Python from your command line are not that important for the purpose of this article, but you can expand the box below to read more about the differences between the command line on Windows, Linux, and macOS.

The way that you tell the computer to execute code from the command line is slightly different depending on your operating system.

On Linux and macOS, the command line typically looks like the example below:

``````[email protected]:~/Documents\$

``````

• A Basic Python main()
• Execution Modes in Python
Executing From the Command LineImporting Into a Module or the Interactive Interpreter* Best Practices for Python Main Functions
Put Most Code Into a Function or ClassUse name to Control the Execution of Your CodeCreate a Function Called main() to Contain the Code You Want to RunCall Other Functions From main()Summary of Python Main Function Best Practices* Conclusion

Many programming languages have a special function that is automatically executed when an operating system starts to run a program. This function is usually called `main()` and must have a specific return type and arguments according to the language standard. On the other hand, the Python interpreter executes scripts starting at the top of the file, and there is no specific function that Python automatically executes.

Nevertheless, having a defined starting point for the execution of a program is useful for understanding how a program works. Python programmers have come up with several conventions to define this starting point.

• What the special `__name__` variable is and how Python defines it
• Why you would want to use a `main()` in Python
• What conventions there are for defining `main()` in Python
• What the best-practices are for what code to put into your `main()`
A Basic Python main()

In some Python scripts, you may see a function definition and a conditional statement that looks like the example below:

``````def main():
print("Hello World!")

if __name__ == "__main__":
main()

``````

In this code, there is a function called `main()` that prints the phrase `Hello World!` when the Python interpreter executes it. There is also a conditional (or `if`) statement that checks the value of `__name__` and compares it to the string `"__main__"`. When the `if` statement evaluates to `True`, the Python interpreter executes `main()`. You can read more about conditional statements in Conditional Statements in Python.

This code pattern is quite common in Python files that you want to be executed as a script and imported in another module. To help understand how this code will execute, you should first understand how the Python interpreter sets `__name__` depending on how the code is being executed.

Execution Modes in Python

There are two primary ways that you can instruct the Python interpreter to execute or use code:

1. You can execute the Python file as a script using the command line.
2. You can import the code from one Python file into another file or into the interactive interpreter.

You can read a lot more about these approaches in How to Run Your Python Scripts. No matter which way of running your code you’re using, Python defines a special variable called `__name__` that contains a string whose value depends on how the code is being used.

We’ll use this example file, saved as `execution_methods.py`, to explore how the behavior of the code changes depending on the context:

``````print("This is my file to test Python's execution methods.")
print("The variable __name__ tells me which context this file is running in.")
print("The value of __name__ is:", repr(__name__))

``````

In this file, there are three calls to `print()` defined. The first two print some introductory phrases. The third `print()` will first print the phrase `The value of __name__ is`, and then it will print the representation of the `__name__` variable using Python’s built-in `repr()`.

In Python, `repr()` displays the printable representation of an object. This example uses `repr()` to emphasize that the value of `__name__` is a string. You can read more about `repr()` in the Python documentation.

You’ll see the words file, module, and script used throughout this article. Practically, there isn’t much difference between them. However, there are slight differences in meaning that emphasize the purpose of a piece of code:

1. File: Typically, a Python file is any file that contains code. Most Python files have the extension `.py`.
2. Script: A Python script is a file that you intend to execute from the command line to accomplish a task.
3. Module: A Python module is a file that you intend to import from within another module or a script, or from the interactive interpreter. You can read more about modules in the Python documentation.

This distinction is also discussed in How to Run Your Python Scripts.

### Executing From the Command Line

In this approach, you want to execute your Python script from the command line.

When you execute a script, you will not be able to interactively define the code that the Python interpreter is executing. The details of how you can execute Python from your command line are not that important for the purpose of this article, but you can expand the box below to read more about the differences between the command line on Windows, Linux, and macOS.

The way that you tell the computer to execute code from the command line is slightly different depending on your operating system.

On Linux and macOS, the command line typically looks like the example below:

``````[email protected]:~/Documents\$

``````

• A Basic Python main()
• Execution Modes in Python
Executing From the Command LineImporting Into a Module or the Interactive Interpreter* Best Practices for Python Main Functions
Put Most Code Into a Function or ClassUse name to Control the Execution of Your CodeCreate a Function Called main() to Contain the Code You Want to RunCall Other Functions From main()Summary of Python Main Function Best Practices* Conclusion

Many programming languages have a special function that is automatically executed when an operating system starts to run a program. This function is usually called `main()` and must have a specific return type and arguments according to the language standard. On the other hand, the Python interpreter executes scripts starting at the top of the file, and there is no specific function that Python automatically executes.

Nevertheless, having a defined starting point for the execution of a program is useful for understanding how a program works. Python programmers have come up with several conventions to define this starting point.

• What the special `__name__` variable is and how Python defines it
• Why you would want to use a `main()` in Python
• What conventions there are for defining `main()` in Python
• What the best-practices are for what code to put into your `main()`
A Basic Python main()

In some Python scripts, you may see a function definition and a conditional statement that looks like the example below:

``````def main():
print("Hello World!")

if __name__ == "__main__":
main()

``````

In this code, there is a function called `main()` that prints the phrase `Hello World!` when the Python interpreter executes it. There is also a conditional (or `if`) statement that checks the value of `__name__` and compares it to the string `"__main__"`. When the `if` statement evaluates to `True`, the Python interpreter executes `main()`. You can read more about conditional statements in Conditional Statements in Python.

This code pattern is quite common in Python files that you want to be executed as a script and imported in another module. To help understand how this code will execute, you should first understand how the Python interpreter sets `__name__` depending on how the code is being executed.

Execution Modes in Python

There are two primary ways that you can instruct the Python interpreter to execute or use code:

1. You can execute the Python file as a script using the command line.
2. You can import the code from one Python file into another file or into the interactive interpreter.

You can read a lot more about these approaches in How to Run Your Python Scripts. No matter which way of running your code you’re using, Python defines a special variable called `__name__` that contains a string whose value depends on how the code is being used.

We’ll use this example file, saved as `execution_methods.py`, to explore how the behavior of the code changes depending on the context:

``````print("This is my file to test Python's execution methods.")
print("The variable __name__ tells me which context this file is running in.")
print("The value of __name__ is:", repr(__name__))

``````

In this file, there are three calls to `print()` defined. The first two print some introductory phrases. The third `print()` will first print the phrase `The value of __name__ is`, and then it will print the representation of the `__name__` variable using Python’s built-in `repr()`.

In Python, `repr()` displays the printable representation of an object. This example uses `repr()` to emphasize that the value of `__name__` is a string. You can read more about `repr()` in the Python documentation.

You’ll see the words file, module, and script used throughout this article. Practically, there isn’t much difference between them. However, there are slight differences in meaning that emphasize the purpose of a piece of code:

1. File: Typically, a Python file is any file that contains code. Most Python files have the extension `.py`.
2. Script: A Python script is a file that you intend to execute from the command line to accomplish a task.
3. Module: A Python module is a file that you intend to import from within another module or a script, or from the interactive interpreter. You can read more about modules in the Python documentation.

This distinction is also discussed in How to Run Your Python Scripts.

### Executing From the Command Line

In this approach, you want to execute your Python script from the command line.

When you execute a script, you will not be able to interactively define the code that the Python interpreter is executing. The details of how you can execute Python from your command line are not that important for the purpose of this article, but you can expand the box below to read more about the differences between the command line on Windows, Linux, and macOS.

The way that you tell the computer to execute code from the command line is slightly different depending on your operating system.

On Linux and macOS, the command line typically looks like the example below:

``````[email protected]:~/Documents\$

``````

The part before the dollar sign (`) may look different, depending on your username and your computer’s name. The commands that you type will go after the `. On Linux or macOS, the name of the Python 3 executable is `python3`, so you should run Python scripts by typing `python3 script_name.py` after the ``.

On Windows, the command prompt typically looks like the example below:

``````C:\Users\Eleanor\Documents>

``````

The part before the `>` may look different, depending on your username. The commands that you type will go after the `>`. On Windows, the name of the Python 3 executable is typically `python`, so you should run Python scripts by typing `python script_name.py` after the `>`.

Regardless of your operating system, the output from the Python scripts that you use in this article will be the same, so only the Linux and macOS style of input is shown in this article, and the input line will start at the ```Table of Contents

• A Basic Python main()
• Execution Modes in Python
Executing From the Command LineImporting Into a Module or the Interactive Interpreter* Best Practices for Python Main Functions
Put Most Code Into a Function or ClassUse name to Control the Execution of Your CodeCreate a Function Called main() to Contain the Code You Want to RunCall Other Functions From main()Summary of Python Main Function Best Practices* Conclusion

Many programming languages have a special function that is automatically executed when an operating system starts to run a program. This function is usually called `main()` and must have a specific return type and arguments according to the language standard. On the other hand, the Python interpreter executes scripts starting at the top of the file, and there is no specific function that Python automatically executes.

Nevertheless, having a defined starting point for the execution of a program is useful for understanding how a program works. Python programmers have come up with several conventions to define this starting point.

• What the special `__name__` variable is and how Python defines it
• Why you would want to use a `main()` in Python
• What conventions there are for defining `main()` in Python
• What the best-practices are for what code to put into your `main()`
A Basic Python main()

In some Python scripts, you may see a function definition and a conditional statement that looks like the example below:

``````def main():
print("Hello World!")

if __name__ == "__main__":
main()

``````

In this code, there is a function called `main()` that prints the phrase `Hello World!` when the Python interpreter executes it. There is also a conditional (or `if`) statement that checks the value of `__name__` and compares it to the string `"__main__"`. When the `if` statement evaluates to `True`, the Python interpreter executes `main()`. You can read more about conditional statements in Conditional Statements in Python.

This code pattern is quite common in Python files that you want to be executed as a script and imported in another module. To help understand how this code will execute, you should first understand how the Python interpreter sets `__name__` depending on how the code is being executed.

Execution Modes in Python

There are two primary ways that you can instruct the Python interpreter to execute or use code:

1. You can execute the Python file as a script using the command line.
2. You can import the code from one Python file into another file or into the interactive interpreter.

You can read a lot more about these approaches in How to Run Your Python Scripts. No matter which way of running your code you’re using, Python defines a special variable called `__name__` that contains a string whose value depends on how the code is being used.

We’ll use this example file, saved as `execution_methods.py`, to explore how the behavior of the code changes depending on the context:

``````print("This is my file to test Python's execution methods.")
print("The variable __name__ tells me which context this file is running in.")
print("The value of __name__ is:", repr(__name__))

``````

In this file, there are three calls to `print()` defined. The first two print some introductory phrases. The third `print()` will first print the phrase `The value of __name__ is`, and then it will print the representation of the `__name__` variable using Python’s built-in `repr()`.

In Python, `repr()` displays the printable representation of an object. This example uses `repr()` to emphasize that the value of `__name__` is a string. You can read more about `repr()` in the Python documentation.

You’ll see the words file, module, and script used throughout this article. Practically, there isn’t much difference between them. However, there are slight differences in meaning that emphasize the purpose of a piece of code:

1. File: Typically, a Python file is any file that contains code. Most Python files have the extension `.py`.
2. Script: A Python script is a file that you intend to execute from the command line to accomplish a task.
3. Module: A Python module is a file that you intend to import from within another module or a script, or from the interactive interpreter. You can read more about modules in the Python documentation.

This distinction is also discussed in How to Run Your Python Scripts.

### Executing From the Command Line

In this approach, you want to execute your Python script from the command line.

When you execute a script, you will not be able to interactively define the code that the Python interpreter is executing. The details of how you can execute Python from your command line are not that important for the purpose of this article, but you can expand the box below to read more about the differences between the command line on Windows, Linux, and macOS.

The way that you tell the computer to execute code from the command line is slightly different depending on your operating system.

On Linux and macOS, the command line typically looks like the example below:

``````[email protected]:~/Documents\$

``````

• A Basic Python main()
• Execution Modes in Python
Executing From the Command LineImporting Into a Module or the Interactive Interpreter* Best Practices for Python Main Functions
Put Most Code Into a Function or ClassUse name to Control the Execution of Your CodeCreate a Function Called main() to Contain the Code You Want to RunCall Other Functions From main()Summary of Python Main Function Best Practices* Conclusion

Many programming languages have a special function that is automatically executed when an operating system starts to run a program. This function is usually called `main()` and must have a specific return type and arguments according to the language standard. On the other hand, the Python interpreter executes scripts starting at the top of the file, and there is no specific function that Python automatically executes.

Nevertheless, having a defined starting point for the execution of a program is useful for understanding how a program works. Python programmers have come up with several conventions to define this starting point.

• What the special `__name__` variable is and how Python defines it
• Why you would want to use a `main()` in Python
• What conventions there are for defining `main()` in Python
• What the best-practices are for what code to put into your `main()`
A Basic Python main()

In some Python scripts, you may see a function definition and a conditional statement that looks like the example below:

``````def main():
print("Hello World!")

if __name__ == "__main__":
main()

``````

In this code, there is a function called `main()` that prints the phrase `Hello World!` when the Python interpreter executes it. There is also a conditional (or `if`) statement that checks the value of `__name__` and compares it to the string `"__main__"`. When the `if` statement evaluates to `True`, the Python interpreter executes `main()`. You can read more about conditional statements in Conditional Statements in Python.

This code pattern is quite common in Python files that you want to be executed as a script and imported in another module. To help understand how this code will execute, you should first understand how the Python interpreter sets `__name__` depending on how the code is being executed.

Execution Modes in Python

There are two primary ways that you can instruct the Python interpreter to execute or use code:

1. You can execute the Python file as a script using the command line.
2. You can import the code from one Python file into another file or into the interactive interpreter.

You can read a lot more about these approaches in How to Run Your Python Scripts. No matter which way of running your code you’re using, Python defines a special variable called `__name__` that contains a string whose value depends on how the code is being used.

We’ll use this example file, saved as `execution_methods.py`, to explore how the behavior of the code changes depending on the context:

``````print("This is my file to test Python's execution methods.")
print("The variable __name__ tells me which context this file is running in.")
print("The value of __name__ is:", repr(__name__))

``````

In this file, there are three calls to `print()` defined. The first two print some introductory phrases. The third `print()` will first print the phrase `The value of __name__ is`, and then it will print the representation of the `__name__` variable using Python’s built-in `repr()`.

In Python, `repr()` displays the printable representation of an object. This example uses `repr()` to emphasize that the value of `__name__` is a string. You can read more about `repr()` in the Python documentation.

You’ll see the words file, module, and script used throughout this article. Practically, there isn’t much difference between them. However, there are slight differences in meaning that emphasize the purpose of a piece of code:

1. File: Typically, a Python file is any file that contains code. Most Python files have the extension `.py`.
2. Script: A Python script is a file that you intend to execute from the command line to accomplish a task.
3. Module: A Python module is a file that you intend to import from within another module or a script, or from the interactive interpreter. You can read more about modules in the Python documentation.

This distinction is also discussed in How to Run Your Python Scripts.

### Executing From the Command Line

In this approach, you want to execute your Python script from the command line.

When you execute a script, you will not be able to interactively define the code that the Python interpreter is executing. The details of how you can execute Python from your command line are not that important for the purpose of this article, but you can expand the box below to read more about the differences between the command line on Windows, Linux, and macOS.

The way that you tell the computer to execute code from the command line is slightly different depending on your operating system.

On Linux and macOS, the command line typically looks like the example below:

``````[email protected]:~/Documents\$

``````

• A Basic Python main()
• Execution Modes in Python
Executing From the Command LineImporting Into a Module or the Interactive Interpreter* Best Practices for Python Main Functions
Put Most Code Into a Function or ClassUse name to Control the Execution of Your CodeCreate a Function Called main() to Contain the Code You Want to RunCall Other Functions From main()Summary of Python Main Function Best Practices* Conclusion

Many programming languages have a special function that is automatically executed when an operating system starts to run a program. This function is usually called `main()` and must have a specific return type and arguments according to the language standard. On the other hand, the Python interpreter executes scripts starting at the top of the file, and there is no specific function that Python automatically executes.

Nevertheless, having a defined starting point for the execution of a program is useful for understanding how a program works. Python programmers have come up with several conventions to define this starting point.

• What the special `__name__` variable is and how Python defines it
• Why you would want to use a `main()` in Python
• What conventions there are for defining `main()` in Python
• What the best-practices are for what code to put into your `main()`
A Basic Python main()

In some Python scripts, you may see a function definition and a conditional statement that looks like the example below:

``````def main():
print("Hello World!")

if __name__ == "__main__":
main()

``````

In this code, there is a function called `main()` that prints the phrase `Hello World!` when the Python interpreter executes it. There is also a conditional (or `if`) statement that checks the value of `__name__` and compares it to the string `"__main__"`. When the `if` statement evaluates to `True`, the Python interpreter executes `main()`. You can read more about conditional statements in Conditional Statements in Python.

This code pattern is quite common in Python files that you want to be executed as a script and imported in another module. To help understand how this code will execute, you should first understand how the Python interpreter sets `__name__` depending on how the code is being executed.

Execution Modes in Python

There are two primary ways that you can instruct the Python interpreter to execute or use code:

1. You can execute the Python file as a script using the command line.
2. You can import the code from one Python file into another file or into the interactive interpreter.

You can read a lot more about these approaches in How to Run Your Python Scripts. No matter which way of running your code you’re using, Python defines a special variable called `__name__` that contains a string whose value depends on how the code is being used.

We’ll use this example file, saved as `execution_methods.py`, to explore how the behavior of the code changes depending on the context:

``````print("This is my file to test Python's execution methods.")
print("The variable __name__ tells me which context this file is running in.")
print("The value of __name__ is:", repr(__name__))

``````

In this file, there are three calls to `print()` defined. The first two print some introductory phrases. The third `print()` will first print the phrase `The value of __name__ is`, and then it will print the representation of the `__name__` variable using Python’s built-in `repr()`.

In Python, `repr()` displays the printable representation of an object. This example uses `repr()` to emphasize that the value of `__name__` is a string. You can read more about `repr()` in the Python documentation.

You’ll see the words file, module, and script used throughout this article. Practically, there isn’t much difference between them. However, there are slight differences in meaning that emphasize the purpose of a piece of code:

1. File: Typically, a Python file is any file that contains code. Most Python files have the extension `.py`.
2. Script: A Python script is a file that you intend to execute from the command line to accomplish a task.
3. Module: A Python module is a file that you intend to import from within another module or a script, or from the interactive interpreter. You can read more about modules in the Python documentation.

This distinction is also discussed in How to Run Your Python Scripts.

### Executing From the Command Line

In this approach, you want to execute your Python script from the command line.

When you execute a script, you will not be able to interactively define the code that the Python interpreter is executing. The details of how you can execute Python from your command line are not that important for the purpose of this article, but you can expand the box below to read more about the differences between the command line on Windows, Linux, and macOS.

The way that you tell the computer to execute code from the command line is slightly different depending on your operating system.

On Linux and macOS, the command line typically looks like the example below:

``````[email protected]:~/Documents\$

``````

• A Basic Python main()
• Execution Modes in Python
Executing From the Command LineImporting Into a Module or the Interactive Interpreter* Best Practices for Python Main Functions
Put Most Code Into a Function or ClassUse name to Control the Execution of Your CodeCreate a Function Called main() to Contain the Code You Want to RunCall Other Functions From main()Summary of Python Main Function Best Practices* Conclusion

Many programming languages have a special function that is automatically executed when an operating system starts to run a program. This function is usually called `main()` and must have a specific return type and arguments according to the language standard. On the other hand, the Python interpreter executes scripts starting at the top of the file, and there is no specific function that Python automatically executes.

Nevertheless, having a defined starting point for the execution of a program is useful for understanding how a program works. Python programmers have come up with several conventions to define this starting point.

• What the special `__name__` variable is and how Python defines it
• Why you would want to use a `main()` in Python
• What conventions there are for defining `main()` in Python
• What the best-practices are for what code to put into your `main()`
A Basic Python main()

In some Python scripts, you may see a function definition and a conditional statement that looks like the example below:

``````def main():
print("Hello World!")

if __name__ == "__main__":
main()

``````

In this code, there is a function called `main()` that prints the phrase `Hello World!` when the Python interpreter executes it. There is also a conditional (or `if`) statement that checks the value of `__name__` and compares it to the string `"__main__"`. When the `if` statement evaluates to `True`, the Python interpreter executes `main()`. You can read more about conditional statements in Conditional Statements in Python.

This code pattern is quite common in Python files that you want to be executed as a script and imported in another module. To help understand how this code will execute, you should first understand how the Python interpreter sets `__name__` depending on how the code is being executed.

Execution Modes in Python

There are two primary ways that you can instruct the Python interpreter to execute or use code:

1. You can execute the Python file as a script using the command line.
2. You can import the code from one Python file into another file or into the interactive interpreter.

You can read a lot more about these approaches in How to Run Your Python Scripts. No matter which way of running your code you’re using, Python defines a special variable called `__name__` that contains a string whose value depends on how the code is being used.

We’ll use this example file, saved as `execution_methods.py`, to explore how the behavior of the code changes depending on the context:

``````print("This is my file to test Python's execution methods.")
print("The variable __name__ tells me which context this file is running in.")
print("The value of __name__ is:", repr(__name__))

``````

In this file, there are three calls to `print()` defined. The first two print some introductory phrases. The third `print()` will first print the phrase `The value of __name__ is`, and then it will print the representation of the `__name__` variable using Python’s built-in `repr()`.

In Python, `repr()` displays the printable representation of an object. This example uses `repr()` to emphasize that the value of `__name__` is a string. You can read more about `repr()` in the Python documentation.

You’ll see the words file, module, and script used throughout this article. Practically, there isn’t much difference between them. However, there are slight differences in meaning that emphasize the purpose of a piece of code:

1. File: Typically, a Python file is any file that contains code. Most Python files have the extension `.py`.
2. Script: A Python script is a file that you intend to execute from the command line to accomplish a task.
3. Module: A Python module is a file that you intend to import from within another module or a script, or from the interactive interpreter. You can read more about modules in the Python documentation.

This distinction is also discussed in How to Run Your Python Scripts.

### Executing From the Command Line

In this approach, you want to execute your Python script from the command line.

When you execute a script, you will not be able to interactively define the code that the Python interpreter is executing. The details of how you can execute Python from your command line are not that important for the purpose of this article, but you can expand the box below to read more about the differences between the command line on Windows, Linux, and macOS.

The way that you tell the computer to execute code from the command line is slightly different depending on your operating system.

On Linux and macOS, the command line typically looks like the example below:

``````[email protected]:~/Documents\$

``````

The part before the dollar sign (`) may look different, depending on your username and your computer’s name. The commands that you type will go after the `. On Linux or macOS, the name of the Python 3 executable is `python3`, so you should run Python scripts by typing `python3 script_name.py` after the ```Table of Contents

• A Basic Python main()
• Execution Modes in Python
Executing From the Command LineImporting Into a Module or the Interactive Interpreter* Best Practices for Python Main Functions
Put Most Code Into a Function or ClassUse name to Control the Execution of Your CodeCreate a Function Called main() to Contain the Code You Want to RunCall Other Functions From main()Summary of Python Main Function Best Practices* Conclusion

Many programming languages have a special function that is automatically executed when an operating system starts to run a program. This function is usually called `main()` and must have a specific return type and arguments according to the language standard. On the other hand, the Python interpreter executes scripts starting at the top of the file, and there is no specific function that Python automatically executes.

Nevertheless, having a defined starting point for the execution of a program is useful for understanding how a program works. Python programmers have come up with several conventions to define this starting point.

• What the special `__name__` variable is and how Python defines it
• Why you would want to use a `main()` in Python
• What conventions there are for defining `main()` in Python
• What the best-practices are for what code to put into your `main()`
A Basic Python main()

In some Python scripts, you may see a function definition and a conditional statement that looks like the example below:

``````def main():
print("Hello World!")

if __name__ == "__main__":
main()

``````

In this code, there is a function called `main()` that prints the phrase `Hello World!` when the Python interpreter executes it. There is also a conditional (or `if`) statement that checks the value of `__name__` and compares it to the string `"__main__"`. When the `if` statement evaluates to `True`, the Python interpreter executes `main()`. You can read more about conditional statements in Conditional Statements in Python.

This code pattern is quite common in Python files that you want to be executed as a script and imported in another module. To help understand how this code will execute, you should first understand how the Python interpreter sets `__name__` depending on how the code is being executed.

Execution Modes in Python

There are two primary ways that you can instruct the Python interpreter to execute or use code:

1. You can execute the Python file as a script using the command line.
2. You can import the code from one Python file into another file or into the interactive interpreter.

You can read a lot more about these approaches in How to Run Your Python Scripts. No matter which way of running your code you’re using, Python defines a special variable called `__name__` that contains a string whose value depends on how the code is being used.

We’ll use this example file, saved as `execution_methods.py`, to explore how the behavior of the code changes depending on the context:

``````print("This is my file to test Python's execution methods.")
print("The variable __name__ tells me which context this file is running in.")
print("The value of __name__ is:", repr(__name__))

``````

In this file, there are three calls to `print()` defined. The first two print some introductory phrases. The third `print()` will first print the phrase `The value of __name__ is`, and then it will print the representation of the `__name__` variable using Python’s built-in `repr()`.

In Python, `repr()` displays the printable representation of an object. This example uses `repr()` to emphasize that the value of `__name__` is a string. You can read more about `repr()` in the Python documentation.

You’ll see the words file, module, and script used throughout this article. Practically, there isn’t much difference between them. However, there are slight differences in meaning that emphasize the purpose of a piece of code:

1. File: Typically, a Python file is any file that contains code. Most Python files have the extension `.py`.
2. Script: A Python script is a file that you intend to execute from the command line to accomplish a task.
3. Module: A Python module is a file that you intend to import from within another module or a script, or from the interactive interpreter. You can read more about modules in the Python documentation.

This distinction is also discussed in How to Run Your Python Scripts.

### Executing From the Command Line

In this approach, you want to execute your Python script from the command line.

When you execute a script, you will not be able to interactively define the code that the Python interpreter is executing. The details of how you can execute Python from your command line are not that important for the purpose of this article, but you can expand the box below to read more about the differences between the command line on Windows, Linux, and macOS.

The way that you tell the computer to execute code from the command line is slightly different depending on your operating system.

On Linux and macOS, the command line typically looks like the example below:

``````[email protected]:~/Documents\$

``````

• A Basic Python main()
• Execution Modes in Python
Executing From the Command LineImporting Into a Module or the Interactive Interpreter* Best Practices for Python Main Functions
Put Most Code Into a Function or ClassUse name to Control the Execution of Your CodeCreate a Function Called main() to Contain the Code You Want to RunCall Other Functions From main()Summary of Python Main Function Best Practices* Conclusion

Many programming languages have a special function that is automatically executed when an operating system starts to run a program. This function is usually called `main()` and must have a specific return type and arguments according to the language standard. On the other hand, the Python interpreter executes scripts starting at the top of the file, and there is no specific function that Python automatically executes.

Nevertheless, having a defined starting point for the execution of a program is useful for understanding how a program works. Python programmers have come up with several conventions to define this starting point.

• What the special `__name__` variable is and how Python defines it
• Why you would want to use a `main()` in Python
• What conventions there are for defining `main()` in Python
• What the best-practices are for what code to put into your `main()`
A Basic Python main()

In some Python scripts, you may see a function definition and a conditional statement that looks like the example below:

``````def main():
print("Hello World!")

if __name__ == "__main__":
main()

``````

In this code, there is a function called `main()` that prints the phrase `Hello World!` when the Python interpreter executes it. There is also a conditional (or `if`) statement that checks the value of `__name__` and compares it to the string `"__main__"`. When the `if` statement evaluates to `True`, the Python interpreter executes `main()`. You can read more about conditional statements in Conditional Statements in Python.

This code pattern is quite common in Python files that you want to be executed as a script and imported in another module. To help understand how this code will execute, you should first understand how the Python interpreter sets `__name__` depending on how the code is being executed.

Execution Modes in Python

There are two primary ways that you can instruct the Python interpreter to execute or use code:

1. You can execute the Python file as a script using the command line.
2. You can import the code from one Python file into another file or into the interactive interpreter.

You can read a lot more about these approaches in How to Run Your Python Scripts. No matter which way of running your code you’re using, Python defines a special variable called `__name__` that contains a string whose value depends on how the code is being used.

We’ll use this example file, saved as `execution_methods.py`, to explore how the behavior of the code changes depending on the context:

``````print("This is my file to test Python's execution methods.")
print("The variable __name__ tells me which context this file is running in.")
print("The value of __name__ is:", repr(__name__))

``````

In this file, there are three calls to `print()` defined. The first two print some introductory phrases. The third `print()` will first print the phrase `The value of __name__ is`, and then it will print the representation of the `__name__` variable using Python’s built-in `repr()`.

In Python, `repr()` displays the printable representation of an object. This example uses `repr()` to emphasize that the value of `__name__` is a string. You can read more about `repr()` in the Python documentation.

You’ll see the words file, module, and script used throughout this article. Practically, there isn’t much difference between them. However, there are slight differences in meaning that emphasize the purpose of a piece of code:

1. File: Typically, a Python file is any file that contains code. Most Python files have the extension `.py`.
2. Script: A Python script is a file that you intend to execute from the command line to accomplish a task.
3. Module: A Python module is a file that you intend to import from within another module or a script, or from the interactive interpreter. You can read more about modules in the Python documentation.

This distinction is also discussed in How to Run Your Python Scripts.

### Executing From the Command Line

In this approach, you want to execute your Python script from the command line.

When you execute a script, you will not be able to interactively define the code that the Python interpreter is executing. The details of how you can execute Python from your command line are not that important for the purpose of this article, but you can expand the box below to read more about the differences between the command line on Windows, Linux, and macOS.

The way that you tell the computer to execute code from the command line is slightly different depending on your operating system.

On Linux and macOS, the command line typically looks like the example below:

``````[email protected]:~/Documents\$

``````

• A Basic Python main()
• Execution Modes in Python
Executing From the Command LineImporting Into a Module or the Interactive Interpreter* Best Practices for Python Main Functions
Put Most Code Into a Function or ClassUse name to Control the Execution of Your CodeCreate a Function Called main() to Contain the Code You Want to RunCall Other Functions From main()Summary of Python Main Function Best Practices* Conclusion

Many programming languages have a special function that is automatically executed when an operating system starts to run a program. This function is usually called `main()` and must have a specific return type and arguments according to the language standard. On the other hand, the Python interpreter executes scripts starting at the top of the file, and there is no specific function that Python automatically executes.

Nevertheless, having a defined starting point for the execution of a program is useful for understanding how a program works. Python programmers have come up with several conventions to define this starting point.

• What the special `__name__` variable is and how Python defines it
• Why you would want to use a `main()` in Python
• What conventions there are for defining `main()` in Python
• What the best-practices are for what code to put into your `main()`
A Basic Python main()

In some Python scripts, you may see a function definition and a conditional statement that looks like the example below:

``````def main():
print("Hello World!")

if __name__ == "__main__":
main()

``````

In this code, there is a function called `main()` that prints the phrase `Hello World!` when the Python interpreter executes it. There is also a conditional (or `if`) statement that checks the value of `__name__` and compares it to the string `"__main__"`. When the `if` statement evaluates to `True`, the Python interpreter executes `main()`. You can read more about conditional statements in Conditional Statements in Python.

This code pattern is quite common in Python files that you want to be executed as a script and imported in another module. To help understand how this code will execute, you should first understand how the Python interpreter sets `__name__` depending on how the code is being executed.

Execution Modes in Python

There are two primary ways that you can instruct the Python interpreter to execute or use code:

1. You can execute the Python file as a script using the command line.
2. You can import the code from one Python file into another file or into the interactive interpreter.

You can read a lot more about these approaches in How to Run Your Python Scripts. No matter which way of running your code you’re using, Python defines a special variable called `__name__` that contains a string whose value depends on how the code is being used.

We’ll use this example file, saved as `execution_methods.py`, to explore how the behavior of the code changes depending on the context:

``````print("This is my file to test Python's execution methods.")
print("The variable __name__ tells me which context this file is running in.")
print("The value of __name__ is:", repr(__name__))

``````

In this file, there are three calls to `print()` defined. The first two print some introductory phrases. The third `print()` will first print the phrase `The value of __name__ is`, and then it will print the representation of the `__name__` variable using Python’s built-in `repr()`.

In Python, `repr()` displays the printable representation of an object. This example uses `repr()` to emphasize that the value of `__name__` is a string. You can read more about `repr()` in the Python documentation.

You’ll see the words file, module, and script used throughout this article. Practically, there isn’t much difference between them. However, there are slight differences in meaning that emphasize the purpose of a piece of code:

1. File: Typically, a Python file is any file that contains code. Most Python files have the extension `.py`.
2. Script: A Python script is a file that you intend to execute from the command line to accomplish a task.
3. Module: A Python module is a file that you intend to import from within another module or a script, or from the interactive interpreter. You can read more about modules in the Python documentation.

This distinction is also discussed in How to Run Your Python Scripts.

### Executing From the Command Line

In this approach, you want to execute your Python script from the command line.

When you execute a script, you will not be able to interactively define the code that the Python interpreter is executing. The details of how you can execute Python from your command line are not that important for the purpose of this article, but you can expand the box below to read more about the differences between the command line on Windows, Linux, and macOS.

The way that you tell the computer to execute code from the command line is slightly different depending on your operating system.

On Linux and macOS, the command line typically looks like the example below:

``````[email protected]:~/Documents\$

``````

• A Basic Python main()
• Execution Modes in Python
Executing From the Command LineImporting Into a Module or the Interactive Interpreter* Best Practices for Python Main Functions
Put Most Code Into a Function or ClassUse name to Control the Execution of Your CodeCreate a Function Called main() to Contain the Code You Want to RunCall Other Functions From main()Summary of Python Main Function Best Practices* Conclusion

Many programming languages have a special function that is automatically executed when an operating system starts to run a program. This function is usually called `main()` and must have a specific return type and arguments according to the language standard. On the other hand, the Python interpreter executes scripts starting at the top of the file, and there is no specific function that Python automatically executes.

Nevertheless, having a defined starting point for the execution of a program is useful for understanding how a program works. Python programmers have come up with several conventions to define this starting point.

• What the special `__name__` variable is and how Python defines it
• Why you would want to use a `main()` in Python
• What conventions there are for defining `main()` in Python
• What the best-practices are for what code to put into your `main()`
A Basic Python main()

In some Python scripts, you may see a function definition and a conditional statement that looks like the example below:

``````def main():
print("Hello World!")

if __name__ == "__main__":
main()

``````

In this code, there is a function called `main()` that prints the phrase `Hello World!` when the Python interpreter executes it. There is also a conditional (or `if`) statement that checks the value of `__name__` and compares it to the string `"__main__"`. When the `if` statement evaluates to `True`, the Python interpreter executes `main()`. You can read more about conditional statements in Conditional Statements in Python.

This code pattern is quite common in Python files that you want to be executed as a script and imported in another module. To help understand how this code will execute, you should first understand how the Python interpreter sets `__name__` depending on how the code is being executed.

Execution Modes in Python

There are two primary ways that you can instruct the Python interpreter to execute or use code:

1. You can execute the Python file as a script using the command line.
2. You can import the code from one Python file into another file or into the interactive interpreter.

You can read a lot more about these approaches in How to Run Your Python Scripts. No matter which way of running your code you’re using, Python defines a special variable called `__name__` that contains a string whose value depends on how the code is being used.

We’ll use this example file, saved as `execution_methods.py`, to explore how the behavior of the code changes depending on the context:

``````print("This is my file to test Python's execution methods.")
print("The variable __name__ tells me which context this file is running in.")
print("The value of __name__ is:", repr(__name__))

``````

In this file, there are three calls to `print()` defined. The first two print some introductory phrases. The third `print()` will first print the phrase `The value of __name__ is`, and then it will print the representation of the `__name__` variable using Python’s built-in `repr()`.

In Python, `repr()` displays the printable representation of an object. This example uses `repr()` to emphasize that the value of `__name__` is a string. You can read more about `repr()` in the Python documentation.

You’ll see the words file, module, and script used throughout this article. Practically, there isn’t much difference between them. However, there are slight differences in meaning that emphasize the purpose of a piece of code:

1. File: Typically, a Python file is any file that contains code. Most Python files have the extension `.py`.
2. Script: A Python script is a file that you intend to execute from the command line to accomplish a task.
3. Module: A Python module is a file that you intend to import from within another module or a script, or from the interactive interpreter. You can read more about modules in the Python documentation.

This distinction is also discussed in How to Run Your Python Scripts.

### Executing From the Command Line

In this approach, you want to execute your Python script from the command line.

When you execute a script, you will not be able to interactively define the code that the Python interpreter is executing. The details of how you can execute Python from your command line are not that important for the purpose of this article, but you can expand the box below to read more about the differences between the command line on Windows, Linux, and macOS.

The way that you tell the computer to execute code from the command line is slightly different depending on your operating system.

On Linux and macOS, the command line typically looks like the example below:

``````[email protected]:~/Documents\$

``````

The part before the dollar sign (`) may look different, depending on your username and your computer’s name. The commands that you type will go after the `. On Linux or macOS, the name of the Python 3 executable is `python3`, so you should run Python scripts by typing `python3 script_name.py` after the ``.

On Windows, the command prompt typically looks like the example below:

``````C:\Users\Eleanor\Documents>

``````

The part before the `>` may look different, depending on your username. The commands that you type will go after the `>`. On Windows, the name of the Python 3 executable is typically `python`, so you should run Python scripts by typing `python script_name.py` after the `>`.

Regardless of your operating system, the output from the Python scripts that you use in this article will be the same, so only the Linux and macOS style of input is shown in this article, and the input line will start at the ``.

Now you should execute the `execution_methods.py` script from the command line, as shown below:

``````\$ python3 execution_methods.py
This is my file to test Python's execution methods.
The variable __name__ tells me which context this file is running in.
The value of __name__ is: '__main__'

``````

In this example, you can see that name has the value `'__main__'`, where the quote symbols (`'`) tell you that the value has the string type.

Remember that, in Python, there is no difference between strings defined with single quotes (`'`) and double quotes (`"`). You can read more about defining strings in Basic Data Types in Python.

You will find identical output if you include a shebang line in your script and execute it directly (`./execution_methods.py`), or use the `%run` magic in IPython or Jupyter Notebooks.

You may also see Python scripts executed from within packages by adding the `-m` argument to the command. Most often, you will see this recommended when you’re using `pip`: `python3 -m pip install package_name`.

Adding the `-m` argument runs the code in the `__main__.py` module of a package. You can find more information about the `__main__.py` file in How to Publish an Open-Source Python Package to PyPI.

In all three of these cases, `__name__` has the same value: the string `'__main__'`.

Technical detail: The Python documentation defines specifically when `__name__` will have the value `'__main__'`:

A module’s `__name__` is set equal to `'__main__'` when read from standard input, a script, or from an interactive prompt. (Source)
`__name__` is stored in the global namespace of the module along with the `__doc__`, `__package__`, and other attributes. You can read more about these attributes in the Python Data Model documentation and, specifically for modules and packages, in the Python Import documentation.

### Importing Into a Module or the Interactive Interpreter

Now let’s take a look at the second way that the Python interpreter will execute your code: imports. When you are developing a module or script, you will most likely want to take advantage of modules that someone else has already built, which you can do with the `import` keyword.

During the import process, Python executes the statements defined in the specified module (but only the first time you import a module). To demonstrate the results of importing your `execution_methods.py` file, start the interactive Python interpreter and then import your `execution_methods.py` file:

``````>>> import execution_methods
This is my file to test Python's execution methods.
The variable __name__ tells me which context this file is running in.
The value of __name__ is: 'execution_methods'

``````

In this code output, you can see that the Python interpreter executes the three calls to `print()`. The first two lines of output are exactly the same as when you executed the file as a script on the command line because there are no variables in either of the first two lines. However, there is a difference in the output from the third `print()`.

When the Python interpreter imports code, the value of `__name__` is set to be the same as the name of the module that is being imported. You can see this in the third line of output above. `__name__` has the value `'execution_methods'`, which is the name of the `.py` file that Python is importing from.

Note that if you `import` the module again without quitting Python, there will be no output.

Best Practices for Python Main Functions

Now that you can see the differences in how Python handles its different execution modes, it’s useful for you to know some best practices to use. These will apply whenever you want to write code that you can run as a script and import in another module or an interactive session.

You will learn about four best practices to make sure that your code can serve a dual purpose:

1. Put most code into a function or class.
2. Use `__name__` to control execution of your code.
3. Create a function called `main()` to contain the code you want to run.
4. Call other functions from `main()`.

### Put Most Code Into a Function or Class

Remember that the Python interpreter executes all the code in a module when it imports the module. Sometimes the code you write will have side effects that you want the user to control, such as:

• Running a computation that takes a long time
• Writing to a file on the disk
• Printing information that would clutter the user’s terminal

In these cases, you want the user to control triggering the execution of this code, rather than letting the Python interpreter execute the code when it imports your module.

Therefore, the best practice is to include most code inside a function or a class. This is because when the Python interpreter encounters the `def` or `class` keywords, it only stores those definitions for later use and doesn’t actually execute them until you tell it to.

Save the code below to a file called `best_practices.py` to demonstrate this idea:

``````from time import sleep
print("This is my file to demonstrate best practices.")
def process_data(data):
print("Beginning data processing...")
modified_data = data + " that has been modified"
sleep(3)
print("Data processing finished.")
return modified_data

``````

In this code, you first import `sleep()` from the `<a href="https://realpython.com/python-time-module/" target="_blank">time</a>` module.

`sleep()` pauses the interpreter for however many seconds you give as an argument and will produce a function that takes a long time to run for this example. Next, you use `print()` to print a sentence describing the purpose of this code.

Then, you define a function called `process_data()` that does five things:

1. Prints some output to tell the user that the data processing is starting
2. Modifies the input data
3. Pauses the execution for three seconds using `sleep()`
4. Prints some output to tell the user that the processing is finished
5. Returns the modified data

Execute the Best Practices File on the Command Line

Now, what will happen when you execute this file as a script on the command line?

The Python interpreter will execute the `from time import sleep` and `print()` lines that are outside the function definition, then it will create the definition of the function called `process_data()`. Then, the script will exit without doing anything further, because the script does not have any code that executes `process_data()`.

The code block below shows the result of running this file as a script:

``````\$ python3 best_practices.py
This is my file to demonstrate best practices.

``````

The output that we can see here is the result of the first `print()`. Notice that importing from `time` and defining `process_data()` produce no output. Specifically, the outputs of the calls to `print()` that are inside the definition of `process_data()` are not printed!

Import the Best Practices File in Another Module or the Interactive Interpreter

When you import this file in an interactive session (or another module), the Python interpreter will perform exactly the same steps as when it executes file as a script.

Once the Python interpreter imports the file, you can use any variables, classes, or functions defined in the module you’ve imported. To demonstrate this, we will use the interactive Python interpreter. Start the interactive interpreter and then type `import best_practices`:

``````>>> import best_practices
This is my file to demonstrate best practices.

``````

The only output from importing the `best_practices.py` file is from the first `print()` call defined outside `process_data()`. Importing from `time` and defining `process_data()` produce no output, just like when you executed the code from the command line.

### Use `__name__` to Control the Execution of Your Code

What if you want `process_data()` to execute when you run the script from the command line but not when the Python interpreter imports the file?

You can use `<strong>__name__</strong>` to determine the execution context and conditionally run `process_data()` only when `__name__` is equal to `"__main__"`. Add the code below to the bottom of your `best_practices.py` file:

``````if __name__ == "__main__":
data = "My data read from the Web"
print(data)
modified_data = process_data(data)
print(modified_data)

``````

In this code, you’ve added a conditional statement that checks the value of `__name__`. This conditional will evaluate to `True` when `__name__` is equal to the string `"__main__"`. Remember that the special value of `"__main__"` for the `__name__` variable means the Python interpreter is executing your script and not importing it.

Inside the conditional block, you have added four lines of code (lines 12, 13, 14, and 15):

• Lines 12 and 13: You are creating a variable `data` that stores the data you’ve acquired from the Web and printing it.
• Line 14: You are processing the data.
• Line 15: You are printing the modified data.

Now, run your `best_practices.py` script from the command line to see how the output will change:

``````\$ python3 best_practices.py
This is my file to demonstrate best practices.
My data read from the Web
Beginning data processing...
Data processing finished.
My data read from the Web that has been modified

``````

First, the output shows the result of the `print()` call outside of `process_data()`.

After that, the value of `data` is printed. This happened because the variable `__name__` has the value `"__main__"` when the Python interpreter executes the file as a script, so the conditional statement evaluated to `True`.

Next, your script called `process_data()` and passed `data` in for modification. When `process_data()` executes, it prints some status messages to the output. Finally, the value of `modified_data` is printed.

Now you should check what happens when you import the `best_practices.py` file from the interactive interpreter (or another module). The example below demonstrates this situation:

``````>>> import best_practices
This is my file to demonstrate best practices.

``````

Notice that you get the same behavior as before you added the conditional statement to the end of the file! This is because the `__name__` variable had the value `"best_practices"`, so Python did not execute the code inside the block, including `process_data()`, because the conditional statement evaluated to `False`.

### Create a Function Called main() to Contain the Code You Want to Run

Now you are able to write Python code that can be run from the command line as a script and imported without unwanted side effects. Next, you are going to learn about how to write your code to make it easy for other Python programmers to follow what you mean.

Many languages, such as C, C++, Java, and several others, define a special function that must be called `main()` that the operating system automatically calls when it executes the compiled program. This function is often called the entry point because it is where execution enters the program.

By contrast, Python does not have a special function that serves as the entry point to a script. You can actually give the entry point function in a Python script any name you want!

Although Python does not assign any significance to a function named `main()`, the best practice is to **name the entry point function **`<strong>main()</strong>` anyways. That way, any other programmers who read your script immediately know that this function is the starting point of the code that accomplishes the primary task of the script.

In addition, `main()` should contain any code that you want to run when the Python interpreter executes the file. This is better than putting the code directly into the conditional block because a user can reuse `main()`if they import your module.

Change the `best_practices.py` file so that it looks like the code below:

``````from time import sleep
print("This is my file to demonstrate best practices.")
def process_data(data):
print("Beginning data processing...")
modified_data = data + " that has been modified"
sleep(3)
print("Data processing finished.")
return modified_data
def main():
data = "My data read from the Web"
print(data)
modified_data = process_data(data)
print(modified_data)
if __name__ == "__main__":
main()

``````

In this example, you added the definition of `main()` that includes the code that was previously inside the conditional block. Then, you changed the conditional block so that it executes `main()`. If you run this code as a script or import it, you will get the same output as in the previous section.

### Call Other Functions From main()

Another common practice in Python is to have `<strong>main()</strong>` execute other functions, rather than including the task-accomplishing code in `main()`. This is especially useful when you can compose your overall task from several smaller sub-tasks that can execute independently.

For example, you may have a script that does the following:

1. Reads a data file from a source that could be a database, a file on the disk, or a web API
2. Processes the data
3. Writes the processed data to another location

If you implement each of these sub-tasks in separate functions, then it is easy for a you (or another user) to re-use a few of the steps and ignore the ones you don’t want. Then you can create a default workflow in `main()`, and you can have the best of both worlds.

Whether to apply this practice to your code is a judgment call on your part. Splitting the work into several functions makes reuse easier but increases the difficulty for someone else trying to interpret your code because they have to follow several jumps in the flow of the program.

Modify your `best_practices.py` file so that it looks like the code below:

``````from time import sleep
print("This is my file to demonstrate best practices.")
def process_data(data):
print("Beginning data processing...")
modified_data = data + " that has been modified"
sleep(3)
print("Data processing finished.")
return modified_data
data = "Data from the web"
return data
def write_data_to_database(data):
print("Writing data to a database")
print(data)
def main():
modified_data = process_data(data)
write_data_to_database(modified_data)
if __name__ == "__main__":
main()

``````

In this example code, the first 10 lines of the file have the same content that they had before. The second function definition on line 12 creates and returns some sample data, and the third function definition on line 17 simulates writing the modified data to a database.

On line 21, `main()` is defined. In this example, you have modified `main()` so that it calls the data reading, data processing, and data writing functions in turn.

First, the `data` is created from `read_data_from_web()`. This `data` is passed to `process_data()`, which returns the `modified_data`. Finally, `modified_data` is passed into `write_data_to_database()`.

The last two lines of the script are the conditional block that checks `__name__` and runs `main()` if the `if` statement is `True`.

Now, you can run the whole processing pipeline from the command line, as shown below:

``````\$ python3 best_practices.py
This is my file to demonstrate best practices.
Beginning data processing...
Data processing finished.
Writing processed data to a database
Data from the web that has been modified

``````

In the output from this execution, you can see that the Python interpreter executed `main()`, which executed `read_data_from_web()`, `process_data()`, and `write_data_to_database()`. However, you can also import the `best_practices.py` file and re-use `process_data()` for a different input data source, as shown below:

``````>>> import best_practices as bp
This is my file to demonstrate best practices.
>>> data = "Data from a file"
>>> modified_data = bp.process_data(data)
Beginning data processing...
Data processing finished.
>>> bp.write_data_to_database(modified_data)
Writing processed data to a database
Data from a file that has been modified

``````

In this example, you imported `best_practices` and shortened the name to `bp` for this code.

The import process caused the Python interpreter to execute all of the lines of code in the `best_practices.py` file, so the output shows the line explaining the purpose of the file.

Then, you stored data from a file in `data` instead of reading the data from the Web. Then, you reused `process_data()`and `write_data_to_database()` from the `best_practices.py` file. In this case, you took advantage of reusing your code instead of defining all of the logic in `main()`.

### Summary of Python Main Function Best Practices

Here are four key best practices about `main()` in Python that you just saw:

1. Put code that takes a long time to run or has other effects on the computer in a function or class, so you can control exactly when that code is executed.
2. Use the different values of `__name__` to determine the context and change the behavior of your code with a conditional statement.
3. You should name your entry point function `main()` in order to communicate the intention of the function, even though Python does not assign any special significance to a function named `main()`.
4. If you want to reuse functionality from your code, define the logic in functions outside `main()` and call those functions within `main()`.
Conclusion

Congratulations! You now know how to create Python `main()` functions.

You learned the following:

• Knowing the value of the `__name__` variable is important to write code that serves the dual purpose of executable script and importable module.
• `__name__` takes on different values depending on how you executed your Python file. `__name__` will be equal to:
`"__main__"` when the file is executed from the command line or with `python -m` (to execute a package’s `__main__.py` file)The name of the module, if the module is being imported* Python programmers have developed a set of good practices to use when you want to develop reusable code.

Now you’re ready to go write some awesome Python `main()` function code!