Today, we're continuing our 10-day journey to learn Python, kicking off Day 4's lesson. If you haven't checked out Day 1 yet, you can find it here: 🎁Learn Python in 10 Days: Day 1
Hey there! Let's dive into loops in Python, using some everyday examples and some hands-on coding. Here's a breakdown of the main points, all formatted nicely for you.
Day 4: Functions 🎉
Functions are organized, reusable pieces of code designed to perform a specific task.
name = "Alex"
length = len(name)
print(length)
You can call len()
(to get the length) whenever you need because it's a built-in Python function (pre-written for you). But what if we didn't use the len()
function to get the string length?
str = "python"
count = 0
for i in str:
count += 1
print(count)
We can use a function to make this process simpler
def my_len(data):
count = 0
for i in data:
count += 1
print(f"The length of the string '{data}' is {count}")
my_len(str)
Functions help create specific, reusable chunks of code, improving reusability, reducing redundant code, and boosting development efficiency.
2. Defining a Function
Function definition:
def function_name(params):
function_body
return return_value
Calling a function:
function_name(params)
Let's define a simple function
def my_hi():
print("hello")
my_hi()
Things to keep in mind:
- If parameters aren't needed, you can omit them.
- If a return value isn't needed, you can omit it.
- Define the function before using it.
3. Function Parameters
Function parameters allow a function to accept external data when it's called.
def add1():
result = 1 + 2
print(f"{result}")
add1()
The add1() function is very limited, only adding 1 and 2. Let's give it parameters so users can specify any numbers to add.
def add2(a, b):
result = a + b
print(f"{a} + {b} = {a + b}")
add2(3, 4)
- In the function definition,
a
andb
are called formal parameters, indicating the function will use these (separated by comma). - During the function call, the provided
3
and4
are actual parameters, the real values used by the function.
You can pass any number of parameters (including none) to a function.
4. Function Return Values
Return values are the results a function sends back after it's done processing.
# Define a function to add two numbers and return the result.
def add(a, b):
result = a + b
return result
r = add(3, 4)
print(r)
A "return value" is the final result given to the function's caller after completing its task. The syntax is:
def function_name(params):
function_body
return return_value
variable = function(params)
Note: A function stops execution when it hits a return
, so any code after that won't run.
If there's no return
statement, the function returns None
, a special literal indicating the function did not return any meaningful value.
def say_hello():
print("hello")
# None
result = say_hello()
print(result)
print(f"The return type is {type(result)}")
5. Function Documentation
Functions are pure code, so understanding their meaning involves reading the code line by line, which can be inefficient.
We can add documentation to functions to help explain their purpose:
def func(x, y):
"""
Function description
:param x: Explanation for parameter x
:param y: Explanation for parameter y
:return: Explanation for the return value
"""
function_body
return return_value
For example:
def add(x, y):
"""
The add function takes two parameters and adds them together.
:param x: One of the numbers to add.
:param y: The other number to add.
:return: The sum of x and y.
"""
result = x + y
print(f"{x} + {y} = {x + y}")
return result
You can hover over the function name to see its docstring, helping understand the function better.
6. Nested Function Calls
Nested functions are when one function calls another.
def func_b():
print(2)
def func_a():
print(1)
func_b()
func_a()
When func_a
calls func_b
, func_b
finishes all its tasks before returning to where func_a
left off.
7. Variable Scope
Variable scope determines where a variable is accessible (where it can be used and where it can't).
There are two main types: local variables and global variables.
Local variables are defined inside a function and can only be used there.
def test():
num = 100
print(num) # Error: name 'num' is not defined
The variable num
is local to the function test
and can't be accessed outside of it.
Global variables can be accessed both inside and outside functions.
num = 100
def testA():
print(num)
def testB():
print(num)
testA() # 100
testB() # 100
Using the global
keyword:
num = 100
def testA():
print(num)
def testB():
global num
num = 200
print(num)
testA() # 100
testB() # 200
print(num) # 200
# Example: Agricultural Bank ATM: Deposit, Withdrawal, and Balance Check Functions
# Define global variables
money = 50000
name = None
# Ask the user for their name
name = input("Please enter your name: ")
# Define the balance query function
def query(show_header):
if show_header:
print("--------- Balance Inquiry ---------")
print(f"Hello {name}, your remaining balance is {money}")
# Define the deposit function
def save(amount):
global money
print("--------- Deposit ---------")
money += amount
print(f"{name}, you have successfully deposited {amount} units")
query(False)
# Define the withdrawal function
def get(amount):
global money
print("--------- Withdrawal ---------")
if money != 0:
money -= amount
print(f"{name}, you have successfully withdrawn {amount} units")
query(False)
else:
print("Your account balance is zero, please deposit some money")
# Define the main menu function
def main():
print("---------- Main Menu -----------")
print(f"Hello! Welcome to the Agricultural Bank ATM. Please choose an option:")
print("For balance inquiry, enter\t[1]")
print("For deposit, enter\t\t[2]")
print("For withdrawal, enter\t\t[3]")
print("For exit, enter\t\t[4]")
return input("Please enter your choice: ")
# Infinite loop to ensure it doesn't exit
while True:
choice = main()
if choice == "1":
query(True)
continue # Continue to the next iteration
elif choice == "2":
amount = int(input("Enter the amount you want to deposit: "))
save(amount)
continue
elif choice == "3":
amount = int(input("Enter the amount you want to withdraw: "))
get(amount)
continue
else:
print("Exiting the system!")
break
Top comments (2)
Thank you, William, for your work. I'm just starting to learn Python, and I was curious to see how you program.
I was a bit disappointed when I couldn't find the 5th lesson. But then I saw that the 4th lesson was only posted today, which means the next one is coming :)
You're welcome, I'll post an update every day.😊