Python Control Structure 5 Updated
Python Control Structure 5 Updated
1
About Assignments
The first assignment will be announced and uploaded by next Monday (one week to
finish the assignment)
The second assignment?
Slides:
The slides that I shared with you the night before the class might have the answers
towards some in class exercises hidden, to motivate your practice
The updated slides with the answers will be uploaded after the class
2
Last Lab Tasks
3
Last Lab Tasks
4
Last Lab Tasks
5
Class Objectives
Imagine that you have a list of student names, and you want to print the names with
Michael and James, how could you do that?
6
Class Objectives
7
Control Flow Statements
The key thing to note about Python's control flow statements and program structure is
that it uses indentation to mark blocks
Hence the amount of white space (space or tab characters) at the start of a line is very
important. This generally helps to make code more readable but can catch out new
users of python
8
Conditional statements
9
Conditional statements
If – else statement
The if-else statement checks the condition:
Executes the if block of code when the condition is True
Executes the else block of code when the condition is False
else
10
Conditional statements
11
Conditional statements
12
Conditional statements
else
13
Conditional statements
14
Conditional statements
Once one of the expressions is True and its suite is executed, none of the remaining
expressions are tested
There can be only one else clause, and it must be specified last
15
Conditional statements
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement
17
Conditional statements
Same as:
18
Iterative statements – for loop
for loop is used to iterate over a sequence such as a list, string, tuple, or other iterable
objects such as range
Using a for loop in Python we can automate and repeat tasks in an efficient manner
19
Iterative statements – for loop
20
Iterative statements – for loop
21
Iterative statements – for loop
22
Iterative statements – while loop
Python While Loop is used to execute a block of statements repeatedly until a given
condition is satisfied
And when the condition becomes false, the line immediately after the loop in the
program is executed
While loop falls under the category of indefinite iteration. Indefinite iteration means
that the number of times the loop is executed isn’t specified explicitly in advance
23
Iterative statements – while loop
24
Iterative statements – while loop
The while loop statement repeatedly executes a code block while a particular condition
is true
The while loop requires relevant variables to be ready, in this example, we need to define an indexing variable,
count, which we set to 1
25
Iterative statements – while loop
The while loop statement repeatedly executes a code block while a particular condition
is true
Note: remember to increment count, or else the loop will continue forever
26
Iterative statements – while loop
Demo: check how many times a given number can be divided by 3 before it is less than
or equal to 10
27
The else Statement in While Loop
With the else statement we can run a block of code once when the condition no longer
is true
Demo 2: Print a message once the condition is false
28
Iterative statements – while loop
Demo 3: we want a user to enter any number between 100 and 500. We will keep
asking the user to enter a correct input until he/she enters the number within a given
range
29
Iterative statements – while loop
If there are multiple statements in the block that makes up the loop body, they can be separated by semicolons (;)
30
Iterative statements – while loop
32
Transfer statements – break, continue, and pass
33
Transfer statements – break, continue, and pass
34
Transfer statements – break, continue, and pass
In class exercise: Assume that we have a student name list, and we want to print out
the names in this list until we print out “James” (including “James”)
35
Transfer statements – break, continue, and pass
In class exercise: Assume that we have a student name list, and we want to print out
the names in this list except “James”
36
Class Objectives
Python Functions
What are functions? How to call a function?
Arguments
Lambda
Python Classes and Objects
What are classes? How to create a class?
What are objects?
Inheritance
37
Python Functions
my_function()
38
Function Arguments
39
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that
are passed into a function
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition
An argument is the value that is sent to the function when it is called
40
Number of Arguments
41
Arbitrary Arguments, *args
If you do not know how many arguments that will be passed into your function, add a *
before the parameter name in the function definition
Arbitrary arguments are often shortened to *args in Python documentations
This way the function will receive a tuple of arguments, and can access the items
accordingly
42
Keyword Arguments
You can also send arguments with the key = value syntax
This way the order of the arguments does not matter
43
Arbitrary Keyword Arguments, **kwargs
If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function definition
This way the function will receive a dictionary of arguments, and can access the items
accordingly
44
Default Argument Value
45
Passing a List as an Argument
You can send any data types of argument to a function (string, number, list, dictionary
etc.), and it will be treated as the same data type inside the function
If you send a List as an argument, it will still be a List when it reaches the function
46
Return Values
Recall: Similar to the default
A function can return values by defined, use the return statement method in Python, right?
47
Try / Except Statement (optional)
In Python, try and except are used to handle exceptions (= errors detected during
execution). With try and except, even if an exception occurs, the process can be
continued without terminating
Try to define a function as below:
48
Try / Except Statement (optional)
49
Lambda Function
50
Lambda Function
51
Why Use Lambda Function?
The power of lambda is better shown when you use them as an anonymous function
inside another function
Say you have a function definition that takes one argument, and that argument will be
multiplied with an unknown number
Use that function definition to make a function that always doubles the number you
send in
52
Python Classes and Objects
Python is an object-oriented
programming language
53
Python Classes and Objects
Class is a user-defined prototype for an object, that defines a set of attributes that
characterize any object of the class, and methods that can be performed on any
object of the class
54
Python Classes and Objects
Create a Class
To create a class, use the keyword class
Create a class named MyClass, with a property named x
class MyClass:
x = 5
Create Object
Now we can use the class named MyClass to create objects
Create an object named p1, and print the value of x
p1 = MyClass()
print(p1.x)
55
The __init__() Function
56
Object Method
Objects can also contain methods. Methods in objects are functions that belong to
the object
Note: The self parameter is a reference to the current instance of the class and is used to access variables
that belong to the class
57
Jupyter Notebook
58