Learn Python, Microsoft 365 and Google Workspace
Connect with me: Youtube | LinkedIn | WhatsApp Channel | Web | Facebook | Twitter
“The only way to do great work is to love what you do.”
– Steve Jobs
A function is a block of reusable code that performs a specific task. It’s reusable, which means you can call it multiple times in your program. This helps to organize your code, make it more readable, and avoid repetition.
**Why Do We Use Functions? **
We use functions in Python for several reasons:
To define a function, you use the def
keyword followed by the function name, parentheses for parameters, and a colon. The code block that defines the function is indented.
Syntax:
def function_name(parameters):
# Function body
# Code to be executed
def greet(name):
print("Hello,", name + "!")
# Calling the function
greet("Ahmad") # Output: Hello, Ahmad!
Explanation:
def greet(name):
defines a function named greet
that takes one parameter, name
.print("Hello,", name + "!")
is the function body, which prints a greeting message using the provided name.greet("Ahmad")
calls the function with the argument “Ahmad”.Key Points:
return
statement.return
keyword.def add(x, y):
return x + y
result = add(3, 5)
print(result) # Output: 8
Function Requirements:
calculate_area
that takes two parameters: length
and width
.Input:
Output:
Expected Output
The area of the rectangle with length 5 and width 3 is: 15
Additional Test Cases
length = 7
, width = 2
The area of the rectangle with length 7 and width 2 is: 14
length = 10.5
, width = 4.2
The area of the rectangle with length 10.5 and width 4.2 is: 44.1
Function Requirements:
is_even
that takes one parameter: number
."Even"
if the number is even, and "Odd"
if the number is odd.Input:
Output:
"Even"
or "Odd"
Expected Output
The number 4 is: Even
Encourage beginners to test the function with various numbers:
num = 7
The number 7 is: Odd
num = -2
The number -2 is: Even
num = 0
The number 0 is: Even
You can assign default values to parameters, which makes them optional when calling the function.
Video: Learn How to Use Default Parameters in Function Definition
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("Alice") # Uses default message "Hello"
greet("Alice", "Hi") # Overrides default with "Hi"
def multiply(a, b):
return a * b
result = multiply(b=3, a=5) # You can specify arguments in any order
greet
that takes a name as an argument and a greeting message with a default value of “Hello”. If no greeting is provided, the function should use “Hello.”greet("Alice")
should output "Hello, Alice!"
and greet("Alice", "Good morning")
should output "Good morning, Alice!"
calc_price
that accepts price
, tax=0.05
, and discount=0
. Calculate the final price after applying tax and discount. Test with various keyword arguments to see how changes affect the result.calc_price(100)
, calc_price(100, discount=0.1)
, calc_price(100, tax=0.07, discount=0.1)
video: Guard Statements in Python: Explained Simply
def greet():
print("Hello World!")
greeting = greet
def myfunction(val):
return val % 4 == 0
print(myfunction (13) or myfunction (8))
E) 3.5
def greet(name="User"):
return "Hello, " + name
print(greet("Ahmad"))
A) `Hello, User`
B) `Hello, Ahmad`
C) `Hello`
D) `Error`
def my_function():
pass
print(my_function())
- A) `None`
- B) `0`
- C) `True`
- D) `Error`
def my_func(a, b=2, c=3):
return a + b + c
print(my_func(5, c=4))
11
12
10
Error
def my_func(a, b, c=3):
return a + b + c
my_func(1, 2)
my_func(1, 2, 4)
my_func(a=1, b=2, c=5)
my_func(1, c=4, b=2, 5)
def change_value(x):
x = 10
num = 5
change_value(num)
print(num)
5
10
Error
None
def greet(name: str) -> str:
return "Hello, " + name + "!"
result = greet(5)
print(result)
- A) Hello, 5!
- B) TypeError
- C) None
- D) Hello, !
def func(x, y=2):
return x * y
print(func(3))
sum3(num1,num3,num3)
that takes three numbers as input and returns the sum.Write a function SumNum(num1)
that takes a number as input and returns the sum of numbers from 1 to that number (num1).
Write a function sumSquares(x)
that takes a list of numbers as input and returns the sum of their squares.
Write a function order_food
that accepts a main_dish
, an optional side_dish
with a default value of "fries"
, and an optional drink
with a default of "water"
. Call this function using both positional and keyword arguments.
order_food("burger")
, order_food("pizza", drink="soda")
, and order_food("salad", side_dish="breadsticks", drink="juice")
Create a function introduce
that takes three parameters: name
, age
, and city
. Set default values for age
to 18 and city
to “Unknown”. Test calling the function with different combinations of arguments.
introduce("John")
, introduce("John", 25)
, introduce("John", 25, "New York")
Define a function student_profile
that accepts name
, grade
, and subject
with a default value of "Math"
. Use keyword arguments to call this function in different orders.
student_profile(grade="A", name="Emma")
and student_profile("Sophia", "B", subject="History")
Write a function add_numbers
that takes two numbers and returns their sum.
add_numbers(3, 5)
should return 8
Write a function circle_area
that calculates the area of a circle given its radius. Use the formula: area = π * radius² (you can use 3.14
for π).
circle_area(3)
should return approximately 28.26
celsius_to_fahrenheit
that takes a temperature in Celsius and converts it to Fahrenheit using the formula: Fahrenheit = Celsius * (9/5) + 32.celsius_to_fahrenheit(25)
should return 77.0
is_even
that takes a number and returns True
if the number is even, and False
otherwise.is_even(4)
should return True
and is_even(7)
should return False
max_of_three
that takes three numbers and returns the largest one.max_of_three(3, 7, 5)
should return 7
simple_interest
that calculates simple interest given principal
, rate
, and time
using the formula: interest = (principal * rate * time) / 100.simple_interest(1000, 5, 2)
should return 100.0
is_prime
that checks if a number is prime. A prime number has only two divisors: 1 and itself.is_prime(7)
should return True
and is_prime(8)
should return False
factorial
that takes a number and returns its factorial. (Factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120
)factorial(5)
should return 120
Write a program with three functions:
isEven(n)
: This function takes an integer n
as input and returns True
if n
is even and False
otherwise. You can use the modulo operator (%
) to check for evenness.printTable(n)
: This function takes an integer n
as input and prints its multiplication table. The table should show the product of n
with each number from 1 to 10, formatted like n * i = n * i
, where i
is the current number in the loop.main
: The main program should:
isEven(n)
function to check if the entered number is even.printTable(n)
function to print its multiplication table.Example output:
Enter an integer: 4
4 is even! Here's its multiplication table:
4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
...
4 * 10 = 40
fibonacci
that takes a number n
and returns the n
th number in the Fibonacci sequence.fibonacci(5)
should return 5
(sequence: 0, 1, 1, 2, 3, 5, …)Function Requirements:
guess_number
that takes no parameters.Input:
Output:
When the user plays the game, the interaction might look like this:
Welcome to the Number Guessing Game!
Guess a number between 1 and 100.
Enter your guess: 50
Too low! Try again.
Enter your guess: 75
Too high! Try again.
Enter your guess: 60
Congratulations! You've guessed the number 60 in 3 attempts.
random
module to select a random number.input()
to get the user’s guess and convert it to an integer.Which of the following will cause a syntax error due to incorrect indentation in Python?
A)
print("Hello World!")
B)
def my_function():
print("Hello World!")
C)
if x == 10:
print("x is 10")
D)
x = 10
Answer: B
Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it. Parameters define what kind of arguments a function can accept.
See also the FAQ
question of Python Documentation
on the difference between arguments and parameters.
def greet(name): # 'name' is a parameter
print("Hello,", name + "!")
greet("Alice") # "Alice" is an argument
In this example:
name
is a parameter in the function greet
."Alice"
is an argument passed to the function when it’s called.To summarize:
Think of it like this:
Sure! Here’s a simple task for beginners to practice writing functions in Python, along with input and output examples.