1 of 72

Advanced Python Programming

Hoang-Giang Cao (高黃江)

Sep 2023

2 of 72

MIDTERM - Windows Programming Design

  • Date: 31 March 2025
  • 90 mins - On-site programing
  • Topics: If-else, for loop, functions
  • 6-8 coding problems

3 of 72

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

4 of 72

Basic Python

What will we learn today?

  • Built-in function
  • User-defined function
  • Variable scope

5 of 72

Basic Python

What will we learn today?

  • What is functions
  • How to define a function
  • Parameters & Argument
  • Keyword parameters & optional parameters
  • Return type

6 of 72

Function

  • We already use some function in python
    • input() -> take input from keyboard
    • print() -> print out to screen
    • int() -> convert to integer number
    • len() -> return the number of objects in a list
    • range () -> return a list of number in a defined range
  • The above functions are built-in functions in Python (內建函式)
  • Originally defined within the Python (Python 內建了多種始終可用的函數)

7 of 72

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

  • For other built-in functions, you may need to check them yourself when needed in practice

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()

8 of 72

Function

  • There are 2 types: built-in function and user-defined function
  • Beside the built-in function defined by Python, user can define their own functions, which called user-defined functions.

  • Which mean, user (coder/programmer) - you, write your own function, to do some specific task

9 of 72

Function

In short, function is a block of code that do a specific task

10 of 72

Function

  • So, why do we need to write our own functions?

11 of 72

Function

  • So, why do we need to write our own functions?
  • You gonna write a hundred -> a thousand lines of code.
  • You should not write them all in sequence as you did so far.
  • You should break the code down to smaller part, for a specific task that the block of code do.

-> So, we need to write a block of code to do a specific task in a function.

12 of 72

Function

  • So, why do we need to write our own functions?
    • Do some specific task (the task that user defined)
    • Reusability: Reuse your code multiple times
    • Modularity: break down complex tasks into smaller, simpler tasks.
    • Readability, understandable
    • Testing, debugging, maintaining
      • Repeatedly using, but implementing once -> testing once, debugging once, maintaining once

13 of 72

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;

}

  • Define data type for return
  • Define data type for parameters
  • Not multiple return variable
  • Require correct indentation
  • NOT require data type (flexible)
  • Allow multiple return variable

1

1

2

3

1

4

2

3

14 of 72

Function

  • How to define a function in python

def print_welcome_messege():�

print("Hello, ")

print ("Welcome to Advance Python Programming class.")

keyword

function name

Parentheses () and colon :

小括號 & 冒號

15 of 72

Function

  • How to define a function in python

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

16 of 72

Function

  • How to use a function -> To use a function, we call it
  • Call by the function name, with parentheses () 小括號

def print_welcome_messege():�

print("Hello, ")

print ("Welcome to Advance Python Programming class.")

print_welcome_messege()

Call a function by function name

17 of 72

Function

  • How to name your function?

Must:

    • NOT starting by a number, or specific character like '@', '$', '!' (except underscores ‘_’)
    • Starting with a character or underscores _
    • Avoid using Python keywords (if ,else, for, while)
    • Avoid using built-in functions name (min,max,print)

Should:

    • Function named in lowercase letters
    • Meaningful/descriptive -> easy to get/understand the purpose of function
      • . I.e find_max_value(), remove_smallest_value(); calculate_total_price()
    • Connect multiple words by underscores “_” I.e find_max_value();

18 of 72

Function

  • Parentheses ? ->
    • We place the parameters (inputs of the function) inside the parentheses

def print_welcome_messege():�

print("Hello, ")

print ("Welcome to Advance Python Programming class.")

Parentheses () and colon :

小括號 & 冒號

19 of 72

Function

  • Parentheses ? ->
    • We place the parameters (variable inputs of the function) inside the parentheses

def print_welcome_messege(first_name,last_name):�

print("Hello,”,first_name,last_name)

print ("Welcome to Advance Python Programming class.")

20 of 72

Function

  • Parentheses ?
    • We place the parameters (inputs of the function) inside the parentheses
    • We called the function with arguments

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

21 of 72

Function

  • Parentheses ? ->
    • We place the parameters (inputs of the function) inside the parentheses
    • We called the function with arguments, in the same order as parameters

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

22 of 72

Function

  • Parentheses ? ->
    • We place the parameters (inputs of the function) inside the parentheses
    • We called the function with arguments, in the same order as parameters

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”

23 of 72

Function

  • Parentheses ? ->
    • We place the parameters (inputs of the function) inside the parentheses
    • We called the function with different arguments

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”

24 of 72

Function

  • Parentheses ? ->
    • We place the parameters (inputs of the function) inside the parentheses
    • We called the function with different arguments

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

25 of 72

Function

  • Parentheses ? ->
    • We place the parameters (inputs of the function) inside the parentheses
    • We called the function with different arguments

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

26 of 72

Argument position & Optional parameters

27 of 72

Function

  • Parentheses ? ->
    • We place the parameters (inputs of the function) inside the parentheses
    • We called the function with different arguments

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”

28 of 72

Function

  • Keyword: make your function readable

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)

29 of 72

Function

  • Keyword arguments: make your function readable
  • With keyword argument, you can place the arguments in any order

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”)

30 of 72

Function

  • Parameters: variable input of the function
    • Use as local variable inside the function
  • Arguments: actual value for a given parameters
    • Can call function with different arguments
    • Or saying assigned different value for the 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”, 10)

31 of 72

Optional parameters

  • Parentheses ? ->
    • We place the parameters (inputs of the function) inside the parentheses
    • We called the function with different arguments

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

32 of 72

Optional parameters

  • Optional parameters
  • Also in C/C++, Java and other programming languge

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”)

33 of 72

Optional parameters

  • Optional parameters: parameters goes with default value
  • Required parameter can not be missed

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

34 of 72

Optional parameters

  • Optional parameters must go after required 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

35 of 72

Optional parameters

  • Optional parameters must go after required parameters
  • I.e: all optional parameters must be placed at the end in the parameter list

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

36 of 72

Return Values

37 of 72

Return Types of Function

  • There are 2 ways to return a function:
  • Return a value or a set of values
    • Do a task
    • Do some calculations, and return the result

  • Return nothing or Return None (by default)
    • Do a task, NOT return anything
    • If no return, means return None

38 of 72

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

39 of 72

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)

40 of 72

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!

41 of 72

Function

  • A function is a set of statements that (might) take inputs, do some specific computation, and (might) return output.
  • Some function might not require any input
  • Some function might not return output

42 of 72

Function

  • Keyword return: when the return is executed, it will out of the function immediately

def sum_number(a,b):� result = a+b

return result

print (“Up to here”)

res = sum_number (5,7)

print (res)

Never reach here

43 of 72

Function

  • Keyword return: when the return is executed, it will out of the function immediately

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

44 of 72

Function

  • Why return not always placed at the end of the function?
  • Because sometime you want to terminal the function earlier
    • To save the time when a specific condition is reached already.

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

45 of 72

Function

  • Why return not always placed at the end of the function?
  • Because sometime you want to terminal the function earlier
    • To save the time when a specific condition is reached already.

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

46 of 72

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;

}

  • Define data type for return
  • Define data type for parameters
  • Not multiple return variable
  • Require correct indentation
  • NOT require data type (flexible)
  • Allow multiple return variable

def calculate(a,b):

summation = a+b

subtraction = a-b

multiply = a * b

division = a/b

return summation, subtraction, multiply, division

47 of 72

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;

}

  • Define data type for return
  • Define data type for parameters
  • Not multiple return variable
  • Require correct indentation
  • NOT require data type (flexible)
  • Allow multiple return variable

1

1

2

3

1

4

2

3

48 of 72

Scope

Local variable, global variable, scope of variable

HARD TO UNDERSTAND

49 of 72

Scope of variable

Global variable:

  • Use anywhere in the program.

Local variable of function:

  • Use inside the function only.
  • NOT available outside the function.
  • If the name of local variable is the same as global variable
    • Inside the function, the program will use local variable

50 of 72

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

51 of 72

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

52 of 72

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

53 of 72

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 = ?

54 of 72

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

55 of 72

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

56 of 72

Scope of variable

Global variable:

  • Use anywhere in the program

Local variable of function:

  • ONLY use inside the function.
  • NOT available outside the function.
  • If the name of local variable is the same as global variable
    • Inside the function, local variable has the priority (scope = local)

57 of 72

Simple Examples

58 of 72

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):

59 of 72

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

60 of 72

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):

61 of 72

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):

62 of 72

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):

63 of 72

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

64 of 72

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

65 of 72

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)

66 of 72

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

67 of 72

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}")

68 of 72

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!

69 of 72

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}")

70 of 72

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

71 of 72

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}")

72 of 72

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