03 - Basic Python Programming II
03 - Basic Python Programming II
u Part 1:Function
u Understanding Functions
u Defining and Calling Functions
u Keyword Argument
u Default Argument Value
u Arbitrary Argument
u Parameter Passing Methods
u Function Return Values
u Global and Local Variables
u Recursive Functions
Understanding
Functions
Understanding Functions
u A function is an independent program unit assigned a name for later calls that
captures a set of statements with a designated functionality or for frequent use.
u A function is like a machine, where you can design its functionality, as well as the
required input (raw materials) and output (products). E.g.,
• Vending machine → Function
• Coins and product selection buttons → Input
• Dispensed products → Output
u In some programming languages, functions are referred to as methods,
procedures, or subroutines.
Advantages of Using Functions
u Reusability
u Simplifies Code and Improves Readability
u Easier Debugging
u Modularity and Consistency
Function
Call
functions
u The rules for naming functions are the same as for variables.
u Statements form the body of the function and execute specific tasks.
u Statements must be indented to the right relative to def, indicating that they
belong to the function block.
u Return value represents the function's output, also called the return value. It can
be one or multiple values.
u The return value can be a string, number, boolean, container (list, dict, etc.), or
other objects. If a function has no return value, the return statement can be
omitted.
Call a Function
u The values passed when calling a function are referred to as arguments (引數),
and they correspond to the function's parameters (參數).
u Even if a function has no required parameters, parentheses () must still be
included when calling it. E.g., myInput = input()
When to Use Functions
u A function can be used to capture two or more very similar code segments that
vary only in a few values or variables.
u Global variable
• A variable created outside a function.
• It is accessible by all statements Global variable
u Local variable
• A variable created inside a function.
• It can only be accessed by statements
within that function.
C o m m o n M i s t a k e W h e n M o d i f y i n g Va r i a b l e s
u If there is a global variable x and we want to modify its value through the
function changeX(), the code is as follows:
?
u What will ? be?
R e a d i n g G l o b a l & L o c a l Va r i a b l e s i n a F u n c t i o n
u In the readFunc1() function, the global variable x is read without modifying its content.
u In the readFunc2() function, a new variable with the same name as the global variable x
is assigned.
Memory
u In a function, the program will first look for an assigned local variable name.
x = 10
If it cannot find one, it will then search for the global variable in the main
…
program.
Global var x = 20
Local var
R e l a t i o n s h i p B e t w e e n N a m e s p a c e & Va r i a b l e s
Var A
(Local
variable)
u globals(): Returns a dictionary containing the names and values of all global
variables in the program.
u locals(): Returns a dictionary containing the names and values of all local
variables within the current function.
Re c u r s i v e F u n c t i o n s
Recursive Functions
u A function that continuously calls itself during execution is called a recursive function.
u Recursion is similar to a loop but can handle parameters and return values that loops
may struggle with.
u Recursive functions offer better logic, readability, and flexibility compared to loops.
u Characteristics of a Recursive Function:
1. The function must be able to call itself.
2. It must have a stopping condition.
Recursive Function Example –
Calculating Factorial
u When n = 0: F(n) = F(0) = 0! = 1
u When n > 0: F(n) = n! = n * (n-1)! = n * F(n-1)
u When n < 0: F(n) = -1 (indicating that the factorial cannot be calculated)
F(4) =24
=4* F(3) =6
=3* F(2) =2
=2* F(1) =1
= 1 * F(0) =1
Par t 2: Data Containers
u Set
u List • Creating a Set
• Creating a List • Built-in Functions of a Set
• Built-in Functions of a List • Operators, Subsets, and Supersets
• Operators • Intersection, Union, Difference, and
• Modifying Elements Symmetric Difference
• List Processing Methods • Set Processing Methods
• List Comprehension (解析) u Dictionary
• Two-Dimensional Lists • Creating a Dictionary
u Tuple • Built-in Functions and Operators of
• Creating a Tuple a Dictionary
• Tuple Operations • Reading a Dictionary
• Dictionary Processing Methods
• Shallow Copy vs. Deep Copy in
Lists and Dictionaries
• Dictionary Comprehension
List
Creating a List
u list (List): A sequence of ordered elements that can be modified
u A list is enclosed in square brackets [ ], with elements separated by
commas. The data types of the elements can be different.
u You can create a list using Python's built-in list() function or [ ], e.g.,
>>> list1 = list()
>>> list1
[]
>>> list2 = list([1, 2, 3])
>>> list2
[1, 2, 3]
u Alternatively, you can define a list using [ ] as shown below.
>>> list1 = []
>>> list2 = [1, 2, 3]
B u i l t- i n F u n c t i o n s of a L i s t
Common built-in functions for lists:
u len(L) >>> len([1, 2, 3, 4, 5])
5
u max(L) >>> max([1, 2, 3, 4, 5])
5
u min(L)
>>> min([1, 2, 3, 4, 5])
u sum(L) 1
>>> sum([1, 2, 3, 4, 5])
15
Concatenation and Repetition Operators
u Concatenation Operator (+)
• The + operator can be used to concatenate lists, e.g.,
>>> 3 * [1, 2, 3]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Comparison & Membership Operators
u Comparison Operators
• The comparison operators (>, <, >=, <=, ==, !=) can be used to
compare the size or equality of two lists, e.g.,
>>> [1, 'two', '三'] == ['三', 'two', 1]
False
>>> [1, 2, 3] != [1, 2, 3, 4]
True
u in and not in Membership Operators
• The in operator checks if an element exists in a list, e.g.,
>>> "Three" in [1, 2, "Three", "Four"]
True
• The not in operator checks if an element does not exist in a list, e.g.,
>>> 2 not in [1, 2, "Three", "Four"]
False
Indexing and Slicing Operators
u Use the indexing operator [i] to access elements in a list.
Given a list variable: L = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
• L[0], L[1], ..., L[9] represent 5, 10, ..., 50.
• L[-1], L[-2], ..., L[-10] represent 50, 45, ..., 5.
Index
Content
Index
u The contents of a list can be modified using indexing and slicing operators.
u Use the indexing operator [i] to modify a specific element in the list, e.g.,
>>> fruits = ['apple', 'banana', 'orange']
>>> fruits[0] = 'grape'
>>> print(fruits)
['grape', 'banana', 'orange']
u Use the slicing operator [start : end] to modify all elements within the
specified index range, e.g.,
>>> a = ['a', 'b', 'c', 'd', 'e']
>>> a[1:4] = [100, 200, 300]
>>> print(a)
['a', 100, 200, 300, 'e']
List Processing Methods
>>> list1.clear()
>>> print(list1)
[]
List Processing Methods
u Copy a list: >>> print(list2)
[100, 200, 300]
• list.copy()
>>> list3 = list2.copy()
• list2 = list1[:] >>> print(list3)
[100, 200, 300]
>>> list4 = list2[:] >>> list1 = [50, 20, 40, 20, 30, 20, 10]
u Additional functions: >>> print(list4) >>> list1.index(20)
[100, 200, 300] 1
• list.index(x) >>> list1.count(20)
3
• list.count(x) >>> list1.sort()
>>> print(list1)
• list.sort() [10, 20, 20, 20, 30, 40, 50]
>>> list1.reverse()
• list.reverse() >>> print(list1)
[50, 40, 30, 20, 20, 20, 10]
List Assignment vs. List Copying
u Assignment u Copy
• list2 = list1 • list.copy()
• list2 = list1[:]
>>> list1 = [10, 20, 30] >>> list1 = [10, 20, 30]
>>> list2 = list1 >>> list3 = list1.copy() #i.e., list3 = list1[:]
>>> del list1[1] >>> del list1[1]
>>> print(list1) >>> print(list1)
[10, 30] [10, 30]
>>> print(list2) >>> print(list3)
[10, 30] [10, 20, 30]
u Summary:
• Using assignment (=) appears to copy a list, but in reality, list1
and list2 both reference the same list.
• When the elements of list1 are modified, list2 is also affected.
Conversion Between Lists and Strings
u str.split(s)
• Convert a string to a list: Use str.split(s) to split a string str into a list
based on the specified delimiter s.
u str.join(L)
• Convert a list to a string: Use str.join(L) to join the elements of list L
into a single string, using str as the
separator.
List Comprehension
u List comprehension provides a more concise way to create a list.
u The square brackets [ ] contain a for statement, which can be
followed by multiple for or if statements.
u The elements of the list are generated based on the specified
expressions, e.g.,
List Comprehension with
Conditional Statements
uWith a single if condition:
• [expression for item in iterable if condition]
uWith an if…else condition:
• [expression1 if condition else expression2 for item in iterable]
uWith nested if conditions:
• [expression for item in iterable if condition1 if condition2]
Tw o - D i m e n s i o n a l L i s t s
uA two-dimensional list is an extension of a regular list that can store tabular data
or matrices.
uFor example, a 5-row × 3-column grade sheet can be stored in a 5×3 two-
dimensional list named grades:
grades = [[95, 100, 100], [86, 90, 75], [98, 98, 96], [78, 90, 80], [70, 68, 72]]
uTo access elements in this two-dimensional list, two indices are required:
• The first index represents the row index.
• The second index represents the column index.
Chinese English Math Chinese English Math
Student 1 Student 1
Student 2 Student 2
Student 3 Student 3
Student 4 Student 4
Student 5 Student 5
E x a m p l e o f a Tw o - D i m e n s i o n a l L i s t
uThe following example prints the total score for each student based on the grade sheet.
Tu p l e
C r e a t i n g a Tu p l e
utuple (Tuple): A sequence of ordered elements that cannot be modified.
uA tuple is enclosed in parentheses ( ), with elements separated by
commas. The data types of the elements can be different
uYou can create a tuple using Python's built-in tuple() function or ( ), e.g.,
>>> tuple1 = tuple()
>>> tuple1
()
>>> tuple2 = tuple((1, 2, 3))
>>> tuple2
(1, 2, 3)
>>> S = {1, 2, 3, 4, 5}
>>> print(len(S))
5
>>> print(max(S))
5
>>> print(min(S))
1
>>> print(sum(S))
15
Operators, Subsets, and Supersets
u A set does not support:
• Concatenation (+)
• Repetition (*)
>>> S = {'a', 'b', 'c', 'd', 1, 2, 3}
• Indexing ([ ])
>>> print('b' in S)
• Slicing ([start:end]) True
• Any other order-related operations
>>> print(10 not in S)
u Supported Operators: True
• Membership operators (in, not in): Check whether a specific element exists in a set.
• Comparison operators (<, <=, >, >=): Determine subset or superset relationships
between two sets.
Operators, Subsets, and Supersets
u If A and B are both sets, the following syntax can be used for checks:
Condition Syntax Operator Description
A and B contain exactly the same elements A == B == A and B are identical sets
A and B have different elements A != B != A and B are not identical
B is a subset of A B <= A <= B is entirely contained within A, or A and B are identical
B is a proper subset of A B<A < B is fully contained within A, and A has additional elements
A is a superset of B A >= B >= A fully contains B, or A and B are identical
A is a proper superset of B A>B > A fully contains B and has extra elements not in B
Operators, Subsets, and Supersets
u Example: >>> A = {4, 1, 3, 2}; B = {1, 2, 3}; C = {3, 1, 2} >>> B <= A
>>> B == C True
>>> B < A
True True
>>> A != B >>> A >= B
True True
>>> A > B
True
u Additionally, to check for subset or superset relationships, the following
methods can be used:
• set.issubset(S) → Returns True if the set is a subset of S. >>> B.issubset(A)
True
• set.issuperset(S) → Returns True if the set is a superset of S. >>> A.issuperset(B)
True
Intersection, Union, Difference, and
Symmetric Difference
Condition Operator Set method
Intersection & set.intersection(S)
Union | set.union(S)
Difference - set.difference(S)
Symmetric difference ^ set.symmetric_difference(S)
Intersection, Union, Difference, and
Symmetric Difference
>>> S1 = {10, 20, 30}
>>> S2 = {20, 30, 40}
>>> S3 = S1.copy()
>>> print(S3)
{50, 20, 70, 40, 10, 60, 30}
Set Processing Methods
u Removing elements from a set: >>> S1.discard(70)
>>> print(S1)
• set.remove(x) {40, 10, 20, 60, 30}
>>> S1.discard(70)
• set.discard(x) >>> print(S1)
{40, 10, 20, 60, 30}
• set.pop()
>>> pop_element = S1.pop()
• set.clear() >>> print(pop_element)
40
>>> S1.remove(50)
>>> print(S1)
>>> print(S1)
{70, 40, 10, 20, 60, 30} {10, 20, 60, 30}
>>> S1.remove(50)
Traceback (most recent call last): >>> S1.clear()
File "<stdin>", line 1, in <module> >>> print(S1)
KeyError: 50 set()
Dictionar y
Creating a Dictionar y
u dict (Dictionary): A collection of key-value pairs, where keys are
unique, unordered (not exactly true), and the content can be modified.
u It belongs to the mapping type, meaning values in the dictionary are
accessed using keys as indexes.
u A dictionary is enclosed in curly braces {}, with key-value pairs
separated by commas.
u A dictionary can be created using Python's built-in dict() function or
{ }.The following four examples create the same dictionary, and any
one of them can be used: >>> A = {"one": 1, "two": 2, "three": 3}
>>> B = dict({"three": 3, "one": 1, "two": 2})
>>> C = dict(one=1, two=2, three=3)
>>> D = dict([("two", 2), ("one", 1), ("three", 3)])
>>> print(A)
{'three': 3, 'two': 2, 'one': 1}
Does a Python Dictionar y Have Order?
u Yes!!!
u In Python 3.7 and later, dictionaries maintain insertion order as an
implementation detail, and in Python 3.8+, it's officially guaranteed
by the language specification.
u This means that when you iterate over a dictionary, the keys will
appear in the order they were added.
# Python 3.7+
>>> my_dict = {"a": 1, "b": 2, "c": 3}
>>> print(my_dict)
{'a': 1, 'b': 2, 'c': 3}
Hint: Use a stack (Last In, First Out) to track opening parentheses. When
encountering a closing parenthesis, check if it matches the top of the stack. If
the stack is empty (indicating no corresponding opening parenthesis) or is not
empty after checking all characters (indicating unmatched opening
parentheses), the parentheses in the string are considered invalid.
HW2-5
uDesign a function e(n) that takes an input n from the user and returns
the computed value of e. Then, calculate the values of e for n=5, 10, 100.
Hint:
• Use list comprehension
• Use math.factorial(i) to compute factorials
• Use sum(L) to sum the list elements
HW2-7
u Randomly generate four unique digits (0–9) for the user to guess. Provide hints using "A" and "B":
• "A" means the digit and position are correct.
• "B" means the digit is correct but in the wrong position.
u For example, if the correct answer is 1234 and the user guesses 1245, the program should display
2A1B. The game continues until the user guesses correctly (4A0B).
u Additional requirements:
• After each input, check if the four-digit number contains duplicate digits.
If not, display the hint and the number of attempts.
• The program should include at least the following two functions:
— generate_number(): Generates a unique four-digit number from 0–9.
— check_number(guess, answer): Compares the user's guess with the
correct answer and returns the number of "A" and "B".