⬅ Previous Topic
Python SetsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.
⬅ Previous Topic
Python SetsAs you write more code, you’ll notice that some parts of your code repeat. Instead of writing the same thing again and again, we can group that code into something called a function.
Functions let you give a name to a block of code. Later, you can use that name to run the code whenever you want — as many times as you want!
This is how you define a simple function in Python:
def function_name():
# block of code
print("Hello!")
Explanation:
def
is a keyword used to define a function.function_name
is the name you choose for your function (no spaces, only letters, numbers, and underscores).()
is where we can pass information (called parameters) — more on that below.Once the function is defined, you can use it like this:
def say_hello():
print("Hello!")
say_hello()
Hello!
Explanation: The line say_hello()
tells Python to run the code inside the function.
You can also send information to a function by using parameters:
def greet(name):
print("Hello, " + name + "!")
greet("Alice")
greet("Bob")
Hello, Alice!
Hello, Bob!
Explanation: The word you pass inside greet()
goes into the name
variable inside the function.
Sometimes you want a function to calculate and give back a value. For that, we use the return
keyword:
def add(a, b):
return a + b
result = add(3, 4)
print(result)
7
Explanation: The function add()
calculates 3 + 4
and returns 7
, which we print.
# No input, no return
def show_message():
print("Welcome!")
# Input, no return
def greet_user(name):
print("Hi, " + name)
# Input and return
def multiply(x, y):
return x * y
# Using the functions
show_message()
greet_user("Zara")
print(multiply(3, 5))
Welcome!
Hi, Zara
15
Functions are like mini-programs inside your main program. You can call them whenever you need them. This makes your code easier to read, write, and fix. You’ll be using functions a lot in Python!
⬅ Previous Topic
Python SetsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.