Advanced Python Programming
Hoang-Giang Cao (高黃江)
Sep 2023
MIDTERM - Windows Programming Design
Schedule
| Content | Date |
✔ | Lecture: For loop / while loop | 10 March |
✔ | Homework HW1: If-else, for loop | 10-16 March |
✔ | Lecture: functions | 17 March |
| Homework HW2: functions | 17-23 March |
| Quiz QZ2: Pre-MIDTERM | 24 March |
| MIDTERM | 31 March |
Basic Python
What will we learn today?
Basic Python
What will we learn today?
Function
from math import sqrt,floor, ceil, pow
N = 9
print(f"sqrt(9) \t {sqrt(N)}")
print(f"9^2 \t\t {pow(9, 2)}")
print(f"9^3 \t\t {pow(9, 3)}")
print(f"abs(-9) \t {abs(-9)}")
print(f"floor(9.2) \t {floor(9.2)}")
print(f"ceil(9.2) \t {ceil(9.2)}")\
Built-in Function - Example
sqrt() | Calculates the square root of a number. | math |
pow() | Raises a number to a specified power. | math |
abs() | Returns the absolute value of an integer. | default |
ceil() | Rounds a number up to the nearest integer. | math |
floor() | Rounds a number down to the nearest integer. | math |
import math
N = 9
print(f"sqrt(9) \t {math.sqrt(N)}")
print(f"9^2 \t\t {math.pow(9, 2)}")
print(f"9^3 \t\t {math.pow(9, 3)}")
print(f"abs(-9) \t {abs(-9)}")
print(f"floor(9.2) \t {math.floor(9.2)}")
print(f"ceil(9.2) \t {math.ceil(9.2)}")
Not specify the function -> math.function( …)
Specify the function -> function( …)
Function
Function
In short, function is a block of code that do a specific task
Function
Function
-> So, we need to write a block of code to do a specific task in a function.
Function
Compare Python vs C++
def calculate_area_rectangle(width,length):
area = width * length
return area
float sum_number(int width, int length) {
float area = width * length;
return area;
}
1
1
2
3
1
4
2
3
Function
def print_welcome_messege():�
print("Hello, ")
print ("Welcome to Advance Python Programming class.")
keyword
function name
Parentheses () and colon :
小括號 & 冒號
Function
def print_welcome_messege():�
print("Hello, ")
print ("Welcome to Advance Python Programming class.")
keyword
function name
Parentheses () and colon :
小括號 & 冒號
body
Indentation
The block of code bellow (same indentation) is belong to the function
A block of code
Function
def print_welcome_messege():�
print("Hello, ")
print ("Welcome to Advance Python Programming class.")
print_welcome_messege()
Call a function by function name
Function
Must:
Should:
Function
def print_welcome_messege():�
print("Hello, ")
print ("Welcome to Advance Python Programming class.")
Parentheses () and colon :
小括號 & 冒號
Function
def print_welcome_messege(first_name,last_name):�
print("Hello,”,first_name,last_name)
print ("Welcome to Advance Python Programming class.")
Function
def print_welcome_messege(first_name,last_name):�
print("Hello,”,first_name,last_name)
print ("Welcome to Advance Python Programming class.")
print_welcome_messege("Allen”, “Huang”)
parameters
arguments
Function
def print_welcome_messege(first_name,last_name):�
print("Hello,”,first_name,last_name)
print ("Welcome to Advance Python Programming class.")
print_welcome_messege("Allen”, “Huang”)
parameters
arguments
Function
def print_welcome_messege(first_name,last_name):�
print("Hello,”,first_name,last_name)
print ("Welcome to Advance Python Programming class.")
print_welcome_messege("Allen”, “Huang”)
parameters
first_name = “Allen” ; last_name = “Huang”
Function
def print_welcome_messege(first_name,last_name):�
print("Hello,”,first_name,last_name)
print ("Welcome to Advance Python Programming class.")
print_welcome_messege("Lionel”, “Messi”)
parameters
first_name = “Lionel” ; last_name = “Messi”
Function
def print_welcome_messege(first_name,last_name):�
print("Hello,”,first_name,last_name)
print ("Welcome to Advance Python Programming class.")
print_welcome_messege("Lionel”, “Messi”)
print_welcome_messege("Cristiano”, “Ronaldo”)
parameters
Reuse the function with different arguments
Function
def print_welcome_messege(first_name,last_name,student_id):�
print("Hello,”,first_name,last_name)
print ("Your student ID:”,student_id)
print ("Welcome to Advance Python Programming class.")
print_welcome_messege("Lionel”, “Messi”, 10)
parameters
first_name = “Lionel” ; last_name = “Messi”; student_id = 10
We can have multiple parameters
Here is 3
Argument position & Optional parameters
Function
def print_welcome_messege(first_name,last_name,student_id):�
print("Hello,”,first_name,last_name)
print ("Your student ID:”,student_id)
print ("Welcome to Advance Python Programming class.")
print_welcome_messege("Lionel”, 10, “Messi”)
parameters
The argument place correspondence with the parameters
Student_id = “Messi”
Function
def print_welcome_messege(first_name,last_name,student_id):�
print("Hello,”,first_name,last_name)
print ("Your student ID:”,student_id)
print ("Welcome to Advance Python Programming class.")
print_welcome_messege(first_name="Lionel”, last_name=“Messi”, student_id= 10)
Function
def print_welcome_messege(first_name,last_name,student_id):�
print("Hello,”,first_name,last_name)
print ("Your student ID:”,student_id)
print ("Welcome to Advance Python Programming class.")
print_welcome_messege(student_id= 10, last_name=“Messi”, first_name="Lionel”)
Function
def print_welcome_messege(first_name,last_name,student_id):�
print("Hello,”,first_name,last_name)
print ("Your student ID:”,student_id)
print ("Welcome to Advance Python Programming class.")
print_welcome_messege("Lionel”, “Messi”, 10)
Optional parameters
def print_welcome_messege(first_name,last_name,student_id):�
print("Hello,”,first_name,last_name)
print ("Your student ID:”,student_id)
print ("Welcome to Advance Python Programming class.")
print_welcome_messege("Lionel”, “Messi”)
Required parameters
first_name = “Lionel” ; last_name = “Messi”; student_id = ?!? missing argument
Missing argument
Getting error
Optional parameters
def print_welcome_messege(first_name,last_name,student_id=1):�
print("Hello,”,first_name,last_name)
print ("Your student ID:”,student_id)
print ("Welcome to Advance Python Programming class.")
print_welcome_messege("Lionel”,“Messi”)
Optional parameters
def print_welcome_messege(first_name,last_name,student_id=1):�
print("Hello,”,first_name,last_name)
print ("Your student ID:”,student_id)
print ("Welcome to Advance Python Programming class.")
print_welcome_messege("Lionel”,“Messi”)
Optional parameters
Required parameters
Optional parameters
def print_welcome_messege(first_name,last_name,student_id=1):�
print("Hello,”,first_name,last_name)
print ("Your student ID:”,student_id)
print ("Welcome to Advance Python Programming class.")
print_welcome_messege("Lionel”,“Messi”)
Optional parameters
Required parameters
Optional parameters
def print_welcome_messege(first_name, student_id=1,last_name):�
print("Hello,”,first_name,last_name)
print ("Your student ID:”,student_id)
print ("Welcome to Advance Python Programming class.")
print_welcome_messege("Lionel”,“Messi”)
Optional parameters
ERROR
Return Values
Return Types of Function
Return Types of Function
def sum_number(a,b):� result = a+b
return result
res = sum_number (5,7)
print (res)
Do a task, calculation, and return the value
def sum_number(a,b):� result = a+b
print (result)
sum_number (5,7)
Do a task, NOT return anything
Return Types of Function
def calculate(a,b):� summation = a+b
subtraction = a-b
multiply = a * b
division = a/b
return summation, subtraction, multiply, division
sum,sub,mul,div = calculate(5,7)
print (“sum:”,sum)
print (“sub:”,sub)
print (“mul:”,mul)
print (“div:”,div)
Do a task, calculation, and return multiple values. to use later (assign to a variable)
Return Types of Function
def calculate(a,b):� summation = a+b
subtraction = a-b
multiply = a * b
division = a/b
return summation, subtraction, multiply, division
sum,sub,mul,div = calculate(5,7)
print (“sum:”,sum)
print (“sub:”,sub)
print (“mul:”,mul)
print (“div:”,div)
Do a task, calculation, and return multiple values. to use later (assign to a variable)
In order!
Function
Function
def sum_number(a,b):� result = a+b
return result
print (“Up to here”)
res = sum_number (5,7)
print (res)
Never reach here
Function
def print_welcome_messege(first_name,last_name,student_id):�
print("Hello,”,first_name,last_name)
print ("Your student ID:”,student_id)
return
print ("Welcome to Advance Python Programming class.")
print_welcome_messege("Lionel”, “Messi”, 10)
Never reach here
Function
def find_the_first_odd_number(arr):
for i in range (len(arr)):
if (arr[i] %2 == 0):
return number �
print("Here, No odd number”)
return -1
x = [1,3,5,7,2,4,6,8,10]
return_value = find_the_first_odd_number(x)
print(return_value)
If reach an odd number, will return the number immediately
Function
def find_the_first_odd_number(arr):
for i in range (len(arr)):
if (arr[i] %2 == 0):
return number �
print("Here, No odd number”)
return -1
x = [1,3,5,7]
return_value = find_the_first_odd_number(x)
print(return_value)
If can not any odd number, will run until the end
Compare Python vs C++
def calculate_area_rectangle(width,length):
area = width * length
return area
float sum_number(int width, int length) {
float area = width * length;
return area;
}
def calculate(a,b):
summation = a+b
subtraction = a-b
multiply = a * b
division = a/b
return summation, subtraction, multiply, division
Compare Python vs C++
def calculate_area_rectangle(width,length):
area = width * length
return area
float sum_number(int width, int length) {
float area = width * length;
return area;
}
1
1
2
3
1
4
2
3
Scope
Local variable, global variable, scope of variable
HARD TO UNDERSTAND
Scope of variable
Global variable:
Local variable of function:
Scope of variable
a,b,summation is local variables, can not access (not available outside the function)
def calculate(a,b):
summation = a+b
print (“inside: ”,a,b,summation)
return summation
sum = calculate(10, 20)
print (“Outside (global): ”,a,b,summation)
ERROR
Scope of variable
first, second is global variables, can use/access anywhere
def calculate(a,b):
summation = a+b
print (“inside f,s: ”,first, second)
return summation
first, second = 5, 7
sum = calculate(10, 20)
print (“Outside (global) f,s: ”,first, second)
GLOBAL
Scope of variable
If local variable has the same name with the global variable
inside the function, local variable has the priority (scope = local)
def calculate(a,b):
first, second = 1, 2
print (“inside f,s: ”,first, second)
summation = a+b
return summation
first, second = 5, 7
print (“Outside (global) f,s: ”,first, second)
sum = calculate(10, 20)
LOCAL
GLOBAL
Scope of variable
def calculate(a,b):
print ("Inside function: f, s",first, second)
print ("Inside function: a, b",a, b)
summation = a+b
return summation
first, second = 5,7
sum = calculate(first, second)
print ("Global: f, s",first, second)
Let’s make it more complicated.
Local:
first = ?
second = ?
a = ?
b = ?
Global
first = ?
second = ?
a = ?
b = ?
Scope of variable
def calculate(a,b):
print ("Inside function: f, s",first, second)
print ("Inside function: a, b",a, b)
summation = a+b
return summation
first, second = 5,7
sum = calculate(first, second)
print ("Global: f, s",first, second)
print ("Global: a, b",a, b)
Let’s make it more complicated.
Local:
first = 5
second = 7
a = 5
b = 7
summation = 12
Global
first = 5
second = 7
a = not available
b = not available
sum = 12
Scope of variable
def calculate(a,b):
first, second = 1,2
print ("Inside function: f, s",first, second)
print ("Inside function: a, b",a, b)
summation = a+b
return summation
first, second = 5,7
sum = calculate(first, second)
print ("Global: f, s",first, second)
print ("Global: a, b",a, b)
Let’s make it more complicated.
Local:
first = 1
second = 2
a = 5
b = 7
summation = 12
Global
first = 5
second = 7
a = not available
b = not available
sum = 12
Scope of variable
Global variable:
Local variable of function:
Simple Examples
Exercises 1
Write function to calculate and return the area of a rectangle.
Function takes 2 floats numbers as width and lengths
area = length * width
Input | Return value |
2.5, 3.5 | 8.75 |
10, 2.5 | 25 |
Test case (of function):
Exercises 1
Write function to calculate and return the area of a rectangle.
Function takes 2 floats numbers as width and lengths
Input | Return value |
2.5, 3.5 | 8.75 |
10, 2.5 | 25 |
Test case (of function):
def calculate_area_rectangle(width,length):
area = width * length
return area
print(calculate_area_rectangle(2,3))
print(calculate_area_rectangle(2.5,3.5))
print(calculate_area_rectangle(10,2.5))
area = length * width
Exercises 2
Write a function to calculate and return the area of circle
Function takes 1 float number as radius of the circle
��
Input | Return value |
1 | 3.14 |
2 | 12.56 |
3 | 28.26 |
1.5 | 7.065 |
2.5 | 19.625 |
Test case (of function):
Exercises 3
Write a function to return the Last Digit of number a
Hint: 119 = 11x10 + 9. 91 = 9*10 + 1 -> a%10
��
Input | Return value |
88 | 8 |
91 | 1 |
13333 | 3 |
a % b = remainder
a = b * quotient + remainder
Test case (of function):
Exercises 3b
Write a function to return the Second Digit of number a
Hint: 119 = 11x10 + 9. 119%10 = 9
int(119/10) = 11 or floor(119/10) = 11 then, 11%10 = 1
��
Input | Return value |
119 | 1 |
78 | 7 |
91 | 9 |
13343 | 4 |
a % b = remainder
a = b * quotient + remainder
Test case (of function):
Example 4
def divide(a, b):
if b == 0:
print("Error: Division by zero is not allowed.")
return 0 # You can return a specific error code or value
return a / b
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = divide(num1, num2)
print("The result of division is:", result)
Write function to divide 2 variable. Check invalid divisible by 0
Example 5
Write function int fibonacci(int n) to print the first n numbers of fibonacci sequence
In the main function, require use enter an integer n. Then call function fibonacci
Example 5
Write function int fibonacci(int n) to print the first n numbers of fibonacci sequence
In the main function, require use enter an integer n. Then call function fibonacci
def fibonacci(n):
a, b = 0, 1
print("Fibonacci sequence:", end=" ")
for i in range(1, n+1):
print(a, end=" ")
next = a + b
a = b
b = next
print()
n = int(input("Enter a positive integer n: "))
fibonacci(n)
Example 6
Write function int pow_2(int a) to calculate the square of an integer number a. i.e a2
In the main function, require use enter an integer a. Then call function pow_2 to get the result of a2
Example 6
Write function int pow_2(int a) to calculate the square of an integer number a. i.e a2
In the main function, require use enter an integer a. Then call function pow_2 to get the result of a2
def pow_2(a):
return a * a # Return the square of a
number = int(input("Enter an integer: "))
result = pow_2(number)
print(f"The square of {number} is: {result}")
Example 7
Write function int factorial(int a) , calculate and return the result of factorial of a . ie a!
In the main function, require use enter an integer a. Then call function factorial to get the result of a!
Example 7
Write function int factorial(int a) , calculate and return the result of factorial of a . ie a!
In the main function, require use enter an integer a. Then call function factorial to get the result of a!
def factorial(a):
result = 1
for i in range(1, a + 1):
result *= i
return result
a = int(input("Enter an integer: "))
result = factorial(a)
print(f"The factorial of {a} is: {result}")
Example 8
Write function int pow_a_of_b(int a, int b) , calculate and return the result of ab
In the main function, require use enter 2 integers a and b. Then call function pow_a_of_bto get the result of ab
Example 8
Write function int pow_a_of_b(int a, int b) , calculate and return the result of ab
In the main function, require use enter 2 integers a and b. Then call function pow_a_of_bto get the result of ab
def pow_a_of_b(a, b):
result = 1
for i in range(b):
result *= a
return result
a = int(input("Enter the base: "))
b = int(input("Enter the exponent: "))
result = pow_a_of_b(a, b)
print(f"{a}^{b} is: {result}")
Example 9
Write function int sum_N(int n) , calculate and return the result of sum all number from 1 to N
In the main function, require use enter an integer n . Then call function sum_N to get the result