Functions

George's Python
5 min readFeb 25, 2023

Functions are a key concept in programming, allowing us to group code into reusable blocks that can be called at any point in our program. In this lecture, we will explore how to create and use functions in Python.

Photo by Marita Kavelashvili on Unsplash

Creating a Function

To create a function in Python, we use the def keyword, followed by the name of the function and any arguments it takes, enclosed in parentheses. For example, let's create a simple function that prints "Hello, world!" when called:

def hello_world():
print("Hello, world!")

In this example, we have defined a function called hello_world that takes no arguments and simply prints "Hello, world!" when called. To call this function, we simply use its name followed by parentheses:

hello_world()  # Output: "Hello, world!"

Function Arguments

Functions can also take one or more arguments, allowing us to pass in values that the function can use in its calculations or operations. To define a function with arguments, we simply include the argument names within the parentheses when defining the function. For example, let’s create a function that takes two arguments and adds them together:

def add_numbers(num1, num2):
result = num1 + num2
print(f"The result of {num1} + {num2} is {result}")

In this example, we have defined a function called add_numbers that takes two arguments, num1 and num2, adds them together, and prints the result. To call this function, we pass in the values for num1 and num2 as arguments:

add_numbers(5, 7)  # Output: "The result of 5 + 7 is 12"

We can also define functions with default argument values. This allows us to call the function without providing a value for that argument, and the default value will be used instead. To define a default value for an argument, we simply provide the default value after the argument name in the function definition. For example:

def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")

greet("Alice") # Output: "Hello, Alice!"
greet("Bob", "Hi") # Output: "Hi, Bob!"

In this example, we have defined a function called greet that takes two arguments, name and greeting, with a default value of "Hello" for the greeting argument. We can call this function with just the name argument, in which case the default greeting of "Hello" will be used, or we can provide a different greeting value as the second argument.

Functions can return values using the return keyword. This allows us to use the result of a function in other parts of our program. For example, let's create a function that takes two arguments and returns their sum:

def add_numbers(num1, num2):
result = num1 + num2
return result

In this example, we have defined a function called add_numbers that takes two arguments, num1 and num2, adds them together, and returns the result using the return keyword. To use the result of this function, we can assign the function call to a variable:

sum = add_numbers(5, 7)
print(sum) # Output: 12

In this example, we have assigned the result of calling the add_numbers function with arguments 5 and 7 to a variable called sum, and then printed the value of sum. The function call itself consists of the function name followed by parentheses and the arguments separated by commas.

Function arguments can also have default values. This means that if an argument is not provided when the function is called, it will use the default value instead. Here’s an example:

def say_hello(name="John"):
print(f"Hello, {name}!")

say_hello() # Output: Hello, John!
say_hello("Alice") # Output: Hello, Alice!

In this example, the say_hello function has a default value of "John" for the name argument. If no argument is provided, it will use the default value and print "Hello, John!". If an argument is provided, it will use that instead and print "Hello, {name}!" with the provided name.

Function arguments can also be passed as keyword arguments, where the argument is preceded by the parameter name and an equal sign. This can be useful when you have many arguments with default values and only want to provide values for some of them. Here’s an example:

def describe_pet(name, animal_type="dog"):
print(f"My {animal_type} is named {name}.")

describe_pet(name="Fido") # Output: My dog is named Fido.
describe_pet(name="Whiskers", animal_type="cat") # Output: My cat is named Whiskers.

In this example, the describe_pet function has a default value of "dog" for the animal_type argument. We can provide a value for name and let the function use the default value for animal_type, or we can provide a value for both name and animal_type.

Function arguments can also have variable length, meaning that you can pass a varying number of arguments to a function. This is done using the *args syntax. Here's an example:

def print_numbers(*args):
for num in args:
print(num)

print_numbers(1, 2, 3) # Output: 1 2 3
print_numbers(4, 5, 6, 7) # Output: 4 5 6 7

In this example, the print_numbers function takes any number of arguments and prints them out one by one. We can call the function with any number of arguments and it will print them out.

Overall, functions are an essential tool in programming as they allow us to reuse code and make our code more modular and readable. With a good understanding of function arguments, we can write more flexible and powerful functions that can handle different situations and use cases.

examples of functions in Python:

  1. A function that calculates the area of a rectangle:
def calculate_rectangle_area(width, height):
area = width * height
return area

In this example, we define a function called calculate_rectangle_area that takes two arguments, width and height. The function then calculates the area of the rectangle using the formula width * height, assigns it to a variable called area, and returns the value of area. We can call this function and pass in the required arguments like this:

area = calculate_rectangle_area(5, 7)
print(area) # Output: 35

2. A function that checks if a number is prime:

def is_prime(number):
if number < 2:
return False
for i in range(2, int(number/2)+1):
if number % i == 0:
return False
return True

This function takes one argument, number, and checks if it is a prime number. We first check if the number is less than 2, since 1 and negative numbers are not prime. Then, we iterate over a range of numbers from 2 to half of the given number, checking if the number is divisible by any of them. If it is, then it is not a prime number and we return False. If we make it through the loop without finding a divisor, then the number is prime and we return True. We can call this function like this:

print(is_prime(7)) # Output: True
print(is_prime(10)) # Output: False

3. A function that prints a multiplication table:

def print_multiplication_table(n):
for i in range(1, 11):
print(f"{n} x {i} = {n*i}")

This function takes one argument, n, and prints out the multiplication table for that number from 1 to 10. We can call this function like this:

print_multiplication_table(5)

This will output:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

George's Python
George's Python

Written by George's Python

I write to help how to learn Python

No responses yet

Write a response