0% found this document useful (0 votes)
42 views

Python Control Structure 5 Updated

The document discusses Python control flow statements including conditional statements like if/else and iterative statements like for and while loops. It provides examples of using conditional logic and loops to execute blocks of code conditionally or repeatedly. The key aspects covered are if/elif/else statements, for loops iterating over sequences, while loops for indefinite iteration, and using else blocks with while. Examples are given to demonstrate different control structures for tasks like checking conditions, iterating a set number of times, and repeating until a condition is met.

Uploaded by

denny
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Python Control Structure 5 Updated

The document discusses Python control flow statements including conditional statements like if/else and iterative statements like for and while loops. It provides examples of using conditional logic and loops to execute blocks of code conditionally or repeatedly. The key aspects covered are if/elif/else statements, for loops iterating over sequences, while loops for indefinite iteration, and using else blocks with while. Examples are given to demonstrate different control structures for tasks like checking conditions, iterating a set number of times, and repeating until a condition is met.

Uploaded by

denny
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 58

ISOM 3400 – PYTHON FOR BUSINESS ANALYTICS

5. Python Control Structure


Yingpeng Robin Zhu

JUN 29, 2022


(No class on Jul 1, 2022)

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

 Control flow statements


 Conditional statements
 if, if-else, if-elif-else
 Loop/Iterative statements
 for, while
 Transfer statements
 break, continue, pass

7
Control Flow Statements

 A statement is an instruction that a Python interpreter can execute


Assignment Statement
for Statement
if Statement

 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

 Conditional statements act depending on whether a given condition is True or False


 You can execute different blocks of codes depending on the outcome of a condition
 If statement
 If the condition is True, then the True block of code will be executed
 If the condition is False, then the block of code is skipped, and the controller moves
to the next line

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

 If – elif – else statement


 The elif statement checks multiple conditions one by one and if the condition
fulfills, then executes that code

11
Conditional statements

 If – elif – else statement


 The elif statement checks multiple conditions one by one and if the condition
fulfills, then executes that code

12
Conditional statements

 Nested If – else statement


 The nested if-else statement is an if statement inside another if-else statement

else

13
Conditional statements

 Nested If – else statement


 The nested if-else statement is an if statement inside another if-else statement

14
Conditional statements

 An arbitrary number of elif clauses can be specified

 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

 Short Hand If … else


 If you have only one statement to execute, one for if, and one for else, you can put it all on the same
line

This technique is known as Ternary Operators, or Conditional Expressions.


16
Conditional statements

 Conditional Expressions/Ternary Operators

17
Conditional statements

 Conditional Expressions/Ternary Operators

 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

 for loop demo

20
Iterative statements – for loop

 If-else in for loop


 In class exercise: iterate through the numbers from 1 to 10, if the number is even,
print(“Even number:”, i), else, print(“Odd number:”, i)

21
Iterative statements – for loop

 Why use for loop?


 Definite Iteration: When we know how many times, we wanted to run a loop, then
we use count-controlled loops such as for loops. It is also known as definite
iteration. For example, Calculate the percentage of 50 students. here we know we
need to iterate a loop 50 times (1 iteration for each student)
 Reduces the code’s complexity: Loop repeats a specific block of code a fixed
number of times. It reduces the repetition of lines of code, thus reducing the
complexity of the code. Using for loops and while loops we can automate and
repeat tasks in an efficient manner
 Loop through sequences: used for iterating over lists, strings, tuples, dictionaries,
etc., and perform various operations on it, based on the conditions specified by the
user

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

 Single statement while block


 Just like the if block, if the while block consists of a single statement, we can
declare the entire loop in a single line
 Try this code first and how many “Hello Student” would you get?

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

 Why and When to Use while Loop?


 Automate and repeat tasks: as we know, while loops execute blocks of code over
and over again until the condition is met it allows us to automate and repeat tasks
in an efficient manner
 Indefinite Iteration: The while loop will run as often as necessary to complete a
particular task. When the user doesn’t know the number of iterations before
execution, while loop is used instead of a for loop
 Reduce complexity: while loop is easy to write. using the loop, we don’t need to
write the statements again and again. Instead, we can write statements we wanted
to execute again and again inside the body of the loop thus, reducing the
complexity of the code
 Infinite loop: If the code inside the while loop doesn’t modify the variables being
tested in the loop condition, the loop will run forever
31
Transfer statements – break, continue, and pass

32
Transfer statements – break, continue, and pass

 The pass statement is used as a placeholder for future code


 When the pass statement is executed, nothing happens, but you avoid getting an error
when empty code is not allowed
 Empty code is not allowed in loops, function definitions, class definitions, or in if
statements.

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

 A function is a block of code which only runs when it is called


 You can pass data, known as parameters, into a function
 A function can return data as a result

 In Python a function is defined using the def keyword:


def my_function():
  print("Hello from a function")

 To call a function, use the function name followed by parenthesis:


def my_function():
  print("Hello from a function")

my_function()

38
Function Arguments

 Information can be passed into functions as arguments


 Arguments are specified after the function name, inside the parentheses. Arguments
are often shortened to args in python documentations
 You can add as many arguments as you want, just separate them with a comma

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

 By default, a function must be called with the correct number of arguments


 Meaning that if your function expects 1 argument, you have to call the function with 1
argument, not more, and not less. Otherwise, it leads to error

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

 If we call the function without argument, it uses the default 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

 A lambda function is a small anonymous function


 A lambda function can take any number of arguments, but can only have one expression
 The expression is executed, and the result is returned

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

 Almost everything in Python is an


object, with its properties and methods

 A Class is like an object constructor, or a


"blueprint" for creating objects

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

 In object-oriented programming, the idea is that since we have a lot of students


with similar attributes such as names and scores, and need similar methods such
as print, then we shall define a class, such that each student will become an
instance of that 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)

Attributes and methods can be accessed via dot notation

55
The __init__() Function

 To understand the meaning of classes we have to understand the built-in __init__()


function
 All classes have a function called __init__(), which is always executed when the class
is being initiated
 Use the __init__() function to assign values to object properties, or other operations
that are necessary to do when the object is being created

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

You might also like