Python Code Examples—Learn Python with 50+ Examples

Here is a list of Python code examples. This list covers the basics of Python. You can use this list as a cheat sheet whether you are preparing for an exam, interview, or are otherwise curious about Python.

Fundamentals of Python

Variables

A variable can store a value. The value can be a number, list, or anything else that is a valid Python object.

Here are some examples:

number = 10
name = "Jack"
data = {"name": "Alice", age: 30}
numbers = [1, 2, 3, 4, 5]

Strings

Strings represent text in Python.

For example, you can create a variable that stores the name of a person:

name = "Alice"

Numbers

Python supports numeric values, that is, integers and floats.

If a number has lots of digits, you can use underscores as visual separators to group digits.

Here are some examples of formatting numbers in Python:

number = 6

ten_thousand = 10_000
billion = 1_000_000_000

decimal_number = 4.23
pi_approx = 3.142

earth_mass = 5.972e24
proton_mass = 1.6726e-27

Booleans

The boolean values True or False represent whether something is true or not true.

is_raining = False
is_sunny = True

Constants

Constants are variables that are not meant to change. To declare constants, make sure the name of the constant is capitalized.

For instance:

NUM = 10
NAME = "Alice"
PARTICIPANTS = ["Alice", "Bob", "Charlie"]

Comments

Leaving code comments is sometimes necessary.

Unfortunately, you cannot just type what you want in a code editor.

Instead, you need to highlight the fact that the line or lines contain a comment. The Python interpreter then knows that the line is not meant to be executed.

For example:

# This is a comment. It is marked by a '#'
# You can add one anywhere in the code.

'''
This is a docstring.
It can also be used as a 
multi-line comment.
'''

Type Conversions

In Python, there are different types, such as integers, floats, and booleans.

You can convert from one type to another using the built-in conversion functions.

For example:

num_string = "10"

num_int    = int(num_string)
num_float  = float(num_string)
is_rainy = "True"

# Convert string to boolean
is_rainy = bool(is_rainy)

Python can also make automatic type conversion. For example, when you try to add an integer with a float, it converts the integer to float for you:

num1 = 10
num2 = 12.32

res = num1 + num2

print(type(res))

Output:

<class 'float'>

Math Operators in Python

OperatorsOperationExample
**Exponent (Power)2 ** 4 = 16
%Modulus (Remainder)5 % 3 = 2
//Integer division20 // 7 = 2
/Division11 / 5 = 2.2
*Multiplication2 * 3 = 6
Subtraction4 - 3 = 1
+Addition1 + 1 = 2

Control Flow in Python

Comparison Operators in Python

OperatorMeaning
==Equal to
!=Not equal to
<Less than
>Greater Than
<=Less than or Equal to
>=Greater than or Equal to

Examples:

5 == 5             # True
5 == 6             # False

1 < 2              # True
2 <= 1             # False

"Alice" == "Alice" # True
"Alice" == "Bob"   # False

True == True       # True
Flase == False     # False

If…Else Statements

If…else statements are used to check if a condition is true.

  • If the condition is met, a piece of code is executed.
  • If the condition is not met, another piece of code is executed instead.

For example:

age = 20

if age <= 18:
    print("You cannot drive")
else:
    print("You are old enough to drive")

Output:

You are old enough to drive

If…Elif…Else Statements

If you have multiple conditions that you want to test at the same, you can add elif statements between the if...else.

For example:

age = 17

if age < 17:
    print("You cannot drive")
elif age == 17:
    print("You can start at driving school")
else:
    print("You are old enough to drive")

Output:

You can start at driving school

Ternary Operator

In Python, there is a shorthand for if…else statements called the ternary operator.

For example:

age = 50

# Regular if-else statement
description = ""

if age > 100:
    description = "Old"
else:
    description = "Young"

# The same using ternary operator as a shorthand
description = "Old" if age > 100 else "Young"

For Loop

To repeat instructions, you can use a for loop in Python.

For example, if you want to print a list of numbers, you can use a for loop like this:

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

for number in numbers:
    print(number)

Output:

1
2
3
4
5

While Loop

To repeat instructions, you can also use a while loop in Python.

For example, if you want to print a list of numbers, you can use a while loop:

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

i = 0
while i < len(numbers):
    print(numbers[i])
    i += 1

Output:

1
2
3
4
5

Break Statement

To exit a loop, you can use the break statement.

For example, let’s break the loop after finding a specific value:

numbers = [1,4,3,2,5,19,5,0]

target = 3

for number in numbers:
    print("Current number", number)
    if number == target:
        print("Target found. Exiting...")
        break

Output:

Current number 1
Current number 4
Current number 3
Target found. Exiting...

Continue Statement

To end the current iteration of a loop, use the continue statement. This jumps directly to the next iteration and disregards whatever it was doing in the current iteration.

For example:

n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    print(n)

Output:

1
3
5
7
9

Pass Statement

To pass or skip the implementation in Python, use the pass statement.

For example:

def my_function():
    pass
numbers = [1, 2, 3, 4, 5]

for number in numbers:
    pass

Functions in Python

A function is a labeled set of instructions that is easy to reuse. A function can take a number of parameters to work with.

The idea is then to call this function from other places in the code to perform the actions.

For example:

def greet(name):
    print(f"Hello, {name}. Nice to meet you!")

greet("Alice")
greet("Bob")

Output:

Hello, Alice. Nice to meet you!
Hello, Bob. Nice to meet you!

Python Function Default Parameters

A Python function can take default parameters. In other words, if the function is called without parameters, a default parameter is used instead.

For example:

def greet(name="there"):
    print(f"Hello, {name}. Nice to meet you!")

greet()
greet("Bob")

Output:

Hello, there. Nice to meet you!
Hello, Bob. Nice to meet you!

Python Function Keyword Arguments

In addition to passing function parameters as-is, you can label them. A labeled function argument is called a keyword argument.

Let’s see an example:

def email(firstname, lastname):
    print(f"{firstname.lower()}.{lastname.lower()}@codingem.com")

# Regular arguments
email("Alice", "Alisson")

# Keyword arguments
email(lastname="Alisson", firstname="Alice")

Both ways produce the same output:

alice.alisson@codingem.com
alice.alisson@codingem.com

The *args Parameters

Allow any number of arguments to a function.

def add(*args):
    result = 0
    for number in args:
        result += number
    return result


print(add(1, 2, 3))
print(add(1, 2, 3, 4, 5))
print(add(1))

Output:

6
15
1

The **kwargs Parameters

Allow any number of keyword arguments into a function:

def scan(**kwargs):
    for item, brand in kwargs.items():
        print(f"{item}: {brand}")


scan(shoes="Adidas", shirt="H&M", sweater="Zara")
scan(socks="Nike")

Output:

shoes: Adidas
shirt: H&M
sweater: Zara

socks: Nike

Recursion

Recursion means a function calls itself inside the function.

For example, to calculate a factorial, you can use a recursive function.

def factorial(n):
    if n == 1:
        return n
    else:
        # Function calls itself from within
        return n * factorial(n - 1)

f = factorial(4)

# factorial(4) = 4! = 4 * 3 * 2 * 1 = 24
print(f)

Output:

24

Lambda Functions

Lambda functions or lambda expressions are anonymous functions.

five_squared = (lambda x: x ** 2)(5)
print(five_squared)

Output:

25

The above example is not useful other than it demonstrates how you can create a lambda.

Let’s see lambdas in real action:

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

even_nums = filter(lambda n: n % 2 == 0, numbers)

print(list(even_nums))

Output:

[2, 4, 6, 8, 10]

Function Docstrings

To document a function, you can write a docstring to describe what it does.

For example:

def sum(a, b):
    """ Returns the sum of two numbers."""
    return a + b

# Ask to see the docstring of a function:
help(sum)

Output:

Help on function sum in module __main__:

sum(a, b)
    Returns the sum of two numbers.

Lists in Python

Lists are data structures that can hold multiple items at the same time. Lists in Python are easy to access, update, and modify.

Here are some examples:

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

# Access elements of a list
first = numbers[0]

# Add new element to the end of a list
numbers.append(6)

# Remove the last element from a list
numbers.pop()

Sorting a List

Sort a list of numbers in increasing order:

numbers = [8, 3, 1, 3, 4, 9, 10, 7, 2]

numbers.sort()

print(numbers)

Output:

[1, 2, 3, 3, 4, 7, 8, 9, 10]

And to sort it in decreasing order:

numbers = [8, 3, 1, 3, 4, 9, 10, 7, 2]

numbers.sort(reverse=True)

print(numbers)

Output:

[10, 9, 8, 7, 4, 3, 3, 2, 1]

Sorting a List by Creating a Sorted Copy

To create a copy instead of sorting the list directly, use the sorted() function.

numbers = [8, 3, 1, 3, 4, 9, 10, 7, 2]

sorted_numbers = sorted(numbers)

print(sorted_numbers)

Output:

[1, 2, 3, 3, 4, 7, 8, 9, 10]

Slicing a List

To get a slice of a list, use the : operator with square brackets and define the range.

For example:

numbers = [8, 3, 1, 3, 4, 9, 10, 7, 2]

subset = numbers[0:3]
print(subset)

Output:

[8, 3, 1]

Check a quick guide to slicing in Python.

Unpacking a List

You can unpack or de-structure a Python list by assigning each item into a separate variable by:

point = [0, 1, 2]

x, y, z = point

print(x)
print(y)
print(z)

Output:

0
1
2

Iterating Over a List Using a For Loop

You can use a for loop to iterate over a list in Python.

For example:

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

for number in numbers:
    print(number)

Output:

1
2
3
4
5

Finding Index of a Specific Element

To figure out the index at which a specific element first occurs in a list, use the index() method:

names = ["Alice", "Bob", "Charlie", "Bob", "David"]

bob_position = names.index("Bob")

print(f"Bob is first met at position {bob_position}")

Output:

Bob is first met at position 1

Iterables and Iterators

A for loop can be used to iterate over a list in Python like this:

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

for number in numbers_list:
    print(number)

Output:

1
2
3
4
5

Under the hood, the for loop grabs the iterator of the numbers list and calls next on it to get the next number.

This process looks like this:

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

numbers_iterator = iter(numbers)

print(next(numbers_iterator))
print(next(numbers_iterator))
print(next(numbers_iterator))
print(next(numbers_iterator))
print(next(numbers_iterator))

Output:

1
2
3
4
5

This describes how the for loop behaves under the hood.

Any iterable object in Python returns an iterator that can be used to iterate over that iterable.

Transform List Elements Using Map Function

To run an operation for each element of an iterable (such as a list), you can use the built-in map() function.

For example:

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

squared_numbers = map(lambda x: x ** 2, numbers)

print(list(squared_numbers))

Output:

[1, 4, 9, 16, 25]

Filtering List Elements Using Filter Function

To filter list elements based on a condition, use the built-in filter() function:

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

even_nums = filter(lambda n: n % 2 == 0, numbers)

print(list(even_nums))

Output:

[2, 4, 6, 8, 10]

Reducing List Elements Using Reduce Function

To accumulate a list by performing an operation on two consecutive elements use the functools reduce() function.

For example, let’s count the sum of list elements:

from functools import reduce
numbers = [1, 2, 3, 4, 5]

sum = reduce(lambda x, y: x + y, numbers)

print(f"The sum of numbers is {sum}")

Output:

The sum of numbers is 15

List Comprehensions

You can use a list comprehension to shorten your for loops:

numbers = [1, 2, 3, 4, 5]
squared_nums = [number ** 2 for number in numbers]

print(squared_nums)

Output:

[1, 4, 9, 16, 25]

Another example with a condition:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_even_nums = [number ** 2 for number in numbers if number % 2 == 0]

print(squared_even_nums)

The result is all the even numbers squared. Odd numbers are left out:

[4, 16, 36, 64, 100]

Tuples in Python

A tuple is like a list that cannot be changed after creation. You can only create one and read values from it.

For example:

names = ("Alice", "Bob", "Charlie")

first = names[0] # Returns "Alice"

Unpacking Tuples

To read the values of a tuple into separate variables, you can use tuple unpacking:

location = (0, 1, 3)

x, y, z = location

print(x)
print(y)
print(z)

Output:

0
1
3

Dictionaries in Python

Python dictionaries hold key-value pairs of data.

For example:

student = {
    "name": "Alice",
    "age": 30,
    "major": "Physics",
    "married": False,
    "hobbies": ["Jogging", "Cycling", "Gym"]
}

Now you can access the values of the dictionary. For example:

print(student["name"])

for hobby in student["hobbies"]:
    print(f"I love {hobby}")

Output:

Alice
I love Jogging
I love Cycling
I love Gym

Or you can change them:

# Update an existing item
student["age"] = 31

# Add a new item
student["graduated"] = False

print(student)

Output:

{'name': 'Alice', 'age': 31, 'major': 'Physics', 'married': False, 'hobbies': ['Jogging', 'Cycling', 'Gym'], 'graduated': False}

Dictionary Comprehension

To loop through a dictionary in Python, you can use a regular for loop. Or you can utilize dictionary comprehension.

To access the dictionary items for the loop, call the items() method of the dictionary.

For example:

data = {"first": 1, "second": 2, "third": 3}

data_squared_values = {value ** 2 for key, value in data.items()}

print(data_squared_values)

Output:

{1, 4, 9}

Sets in Python

Sets are collections of unique values. In other words, a set cannot hold two identical values.

Here is an example of a set:

numbers = {1, 2, 3, 3, 3, 3, 3, 2, 1, 1, 0}

# Each value can occur only once in a set
print(numbers)

Output:

{0, 1, 2, 3}

Set Comprehension

To loop through a set, you can use a regular loop.

But you can also use a shorthand called set comprehension.

For example:

numbers = {1, 2, 3, 4, 5}

squared_numbers = {number ** 2 for number in numbers}

print(squared_numbers)

Output:

{1, 4, 9, 16, 25}

Next, let’s take a look at the useful built-in methods of a set.

Union of Sets

numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}

union = numbers1.union(numbers2)

print(union)

Output:

{1, 2, 3, 4, 5}

Intersection of Sets

numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}

intersection = numbers1.intersection(numbers2)

print(intersection)

Output:

{3}

Difference between Sets

numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}

difference = numbers1.difference(numbers2)

print(difference)

Output:

{1, 2}

Symmetric Difference of Sets

numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}

sym_difference = numbers1.symmetric_difference(numbers2)

print(sym_difference)

Output:

{1, 2, 4, 5}

Subset

numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}

print({1, 2}.issubset(numbers1))
print({1, 2}.issubset(numbers2))

Output:

True
False

Superset

numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}

print({1, 2, 3, 4}.issuperset(numbers1))
print({1, 2, 3, 4}.issuperset(numbers2))

Output:

True
False

Disjoint Sets

print({1, 2, 3}.isdisjoint({4, 5, 6}))
print({1, 2, 3}.isdisjoint({1, 100, 1000}))

Output:

True
False

Error Handling in Python

Try…Except Structure

The basic error handling in Python is possible by trying to run an expression and catching the possible error.

This can be done using the try…except structure.

For example:

try:
    result = x / y
except ZeroDivisionError:
    print("Cannot divide by 0")
except NameError:
    print("Define both numbers first")

Output:

Define both numbers first

Try…Except…Finally Structure

To always run a block of code after handling errors, use a finally block:

try:
    y = 10
    print(y)
except:
    print("There was an error")
finally:
    print("Process completed.")

Output:

The number is 10
Process completed.

Try…Except…Else Structure

You can run code if there are no errors in the expression you run in the try block using the else statement.

For instance:

try:
    y = 10
    print(y)
except:
    print("There was an error")
else:
    print("There were no errors.")
finally:
    print("Process completed.")

Output:

The number is 10
There were no errors.
Process completed.

Python Loops with Else

For…Else

numbers = [1, 2, 3]

for n in numbers:
    print(n)
else:
    print("Loop completed")

Output:

1
2
3
Loop completed

While…Else

numbers = [1, 2, 3]

i = 0
while i < len(numbers):
    print(numbers[i])
    i += 1
else:
    print("Loop completed")

Output:

1
2
3
Loop completed

Files in Python

Read a Text File

To read a text file, use the following:

with open('example.txt') as file:
    lines = file.readlines()

If the file is not in the same folder as your code, remember to replace the example.txt with the path to the file.

Write to a Text File

with open('example.txt', 'w') as f:
    f.write('Hello world!')

If you want to create a file, use the same syntax. If the file it tries to open does not exist, a new one is created.

If you want to create a file to another folder, replace the example.txt with the desired path to the file.

Check If a File Exists

from os.path import exists

if exists(path_to_file):
    # Do something

Conclusion

That is a lot of Python code examples. I hope you find it useful.

Happy coding!

Further Reading

Python Interview Questions and Answers

Useful Advanced Features of Python