PythonCoBan B10
PythonCoBan B10
Lê Ngọc Hiếu
hieu.ln@ou.edu.vn
1. Decision Control
4. Exercises
2
Decision Control
Python if Statement
False
Condition
True
3
if Statement
• Python use if statement to execute a block of code based on a
specified condition.
• Syntax of if statement:
False
if condition: Condition
statement1 True
statement2 statement1
statement2
... ...
statementN statementN
if Statement – Important Notes
• After the condition, there must be a colon.
Correct Incorrect
if Statement – Important Notes
• Python relies on indentation (whitespace at the beginning of a line) to define
scope in the code.
VS
if…else Statement
• Python use if ... else statement to perform an action when a
condition is True and another action when the condition is False.
if condition:
statements in if-block False
Condition
else:
True
statements in else-block
Statements Statements
in if-block in else-block
7
if…elif…else Statement
if condition1:
• Python use if...elif...else
statements in if-block
statement to check multiple
elif condition2: conditions and perform an action
statements in elif-block accordingly.
elif condition3:
statements in elif-block • The elif stands for else if.
...
else:
else-block
8
if…elif…else Statement - Example
9
if…elif…else Statement – Another Example
10
Nested if, elif, else Conditions
• Python supports nested if, elif, and else condition.
11
Nested if, elif, else Conditions
• Python supports nested if, elif, and else condition.
12
Python Ternary Operator
• Syntax of ternary operators:
value_if_true if condition else value_if_false
Begin
Input: h, w
Ye a = h*w
h>0&w>0 s p = (h+w) *2
N
o
Output: Output: S, C
Invalid inputs
End
14
[if] Ex01: Write a program to
compute perimeter and area of a
rectangle given the length and width
of the rectangle.
Begin
Input: h, w
Ye a = h*w
h>0&w>0 s p = (h+w) *2
N
o
Output: Output: S, C
Invalid inputs
End
15
[if] Ex02: Write a program to solve
linear equations.
16
[if] Ex02: Write a program to solve
linear equations.
17
Python Loops
while loops
for loops
18
while loop
• Python uses the while statement to execute a code block repeatedly
as long as a condition is True.
False
while condition: Condition
statement1 True
statement2 statement1
statement2
... ...
statementN statementN
while loop - Example
• Print all integers between 1 and 10.
Correct implementation
Wrong implementation
20
[while] Ex01: Sum of all integers
between 1 and n, where n is a
positive integer inputted by users.
21
[while] Ex01: Sum of all integers
between 1 and n, where n is a
positive integer inputted by users.
Begin
Input: n
i=1
s=0
No Output: s
i <= n End
Yes
s=s+i
i=i+1
22
[while] Ex02: Find greatest common
divisor (GCD) of two positive
integers.
23
[while] Ex02: Find greatest common
divisor (GCD) of two positive
integers.
24
for loop
• A for loop is used for iterating over a sequence, such as list, tuple, set,
range, etc.
• The body of the for loop is executed for each member element in the
sequence.
• Hence, for loop doesn't require explicit verification of a boolean
expression controlling the loop (as in the while loop).
25
for Loop with range() Function
• To loop through a set of code a specified number of times, we can use the
range() function.
• Syntax: for var_name in range(start, stop, step)
Parameter Description
start Optional (default is 0)
An integer number specifying at which position to start.
stop Required.
An integer number specifying at which position to stop
(not included).
step Optional (default is 1)
An integer number specifying the incrementation.
26
for Loop with range() Function - Examples
27
for Loop with range() Function - Examples
Corresponding output
28
for Loop with Sequence Type
• The object of any Python sequence data type can be iterated using the
for statement.
29
for Loop with Sequence Type
• The object of any Python sequence data type can be iterated using the
for statement.
30
[for] Ex01: Sum of all integers
between 1 and n, where n is a
positive integer inputted by users.
33
break statement
• Python use the break statement to terminate a loop prematurely.
• Typically, the break statement is used with the if statement to
terminate a loop when a condition (of the if statement) is True.
break statement
• Python use the break statement to terminate a loop prematurely.
• Typically, the break statement is used with the if statement to
terminate a loop when a condition (of the if statement) is True.
36
break statement
• If the break statement is used in a nested loop, it will terminate the
innermost loop.
• Example:
Output
37
[break] Ex01: Write a program to enter a name (max of 50). Print the
name to the screen. The program stops if quit is entered.
38
[break] Ex02: Input a number. Check if this number is a prime number.
Idea: Count the number of factors. If the number of factors = 2 → it is a prime number.
39
[break] Ex02: Input a number. Check if this number is a prime number.
Idea: Count the number of factors. If the number of factors = 2 → it is a prime number.
Begin
Input: a
count = 0
i=1
No No Output: non-
i <= a count = 2 prime number
Yes
No Yes
a % i == 0 Output: prime
Yes number End
count += 1
i += 1
40
[break] Ex02: Input a number. Check if this number is a prime number.
Idea: Count the number of factors. If the number of factors = 2 → it is a prime number.
41
[break] Ex02: Input a number. Check if this number is a prime number.
Improved version of the previous function
Begin
Input: a
count = 0
i=1
No
i <= a
Yes No Output: non-
No count = 2 prime number
a % i == 0
Yes Yes
count += 1 Output: prime
number End
Yes
count > 2
No
i += 1 42
[break] Ex02: Input a number. Check if this number is a prime number.
Improved version of the previous function
43
•
44
Begin •
Input: a
isprime = False
No
a >= 2
Yes
isprime = True
i=2
No isprime = Yes Output: prime
True number
Yes
Yes No
a % i == 0 isprime = False
No
i += 1
Output: non-
prime number End
45
46
continue statement
• The continue statement is used inside a loop.
• The continue statement skips the current iteration and starts the next
one.
• Typically, the continue statement is used with an if statement to skip
the current iteration once a condition is True.
else in For/While Loop
• The else keyword in a for or while loop specifies a block of code to
be executed when the loop is finished.
48
else in For/While Loop - Example
52
Exercises
53
•
54
•
55
Python Functions
Lê Ngọc Hiếu
hieu.ln@ou.edu.vn
1. Definition of Functions
4. Exercises
57
Definition of Functions
• A function is a block of code which only runs when it is called.
• Functions perform a predefined task and can be called upon in any
program, as per requirement.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
• Two types of functions:
• Build-in functions: pre-defined in Python, present for use.
• User-defined functions: defined by developers in programs.
58
Python Build-in Functions
59
Several Build-in Functions in Python
Functio Description Function Description
n print() Prints to the standard output
abs() Returns the absolute value of device
a number input() Allowing user input
ascii() Returns a readable version of int() Returns an integer number
an object. Replaces none- float() Returns a float number
ascii characters with escape
character max() Returns the largest item in an
iterable
bin() Returns the binary version of
a number min() Returns the smallest item in an
id() Returns the id of an object iterable
type() Returns the type of an object pow()
range() Returns a sequence of round() Rounds a numbers
numbers, starting from 0 and sorted() Returns a sorted list
increments by 1 (by default) sum() Sums the items of an iterator
60
User-defined Functions
61
Defining a Function
• A function has two main parts: a function definition and body.
• Syntax of defining a function:
• Use def keyword
• Docstring and return are optional.
def function_name(parameters):
"""docstring"""
statement1
statement2
...
...
return [expr]
Calling a Function
• To use a function, you need to call it.
• A function call instructs Python to execute the code inside the function.
• To call a function, write the name of the function, followed by the
information that the function needs in parentheses.
• Examples:
63
Function Arguments
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside the
parentheses.
• Functions can have many arguments which are separated by commas.
64
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.
In the example:
• What are parameters?
• What are arguments?
65
Keyword Arguments
• Arguments can be sent with the key = value syntax.
• This way the order of the arguments does not matter.
• Example:
66
Default Parameter Value
• A function can have default parameter values.
• If the function is called without arguments, it uses the default values.
• Example:
67
Arbitrary Arguments
• Add a * before the parameter name in the function definition in case
the number of arguments is not known beforehand.
68
Arbitrary Keyword Arguments
• If the number of keyword arguments is unknown, add a double **
before the parameter name.
69
Exercises
70
1. Write a Python function to find the Max of three numbers.
Function name and parameters: max3(number1, number2, number3)
2. Write a function to compute the perimeter and area of a triangle given side lengths of
the triangle.
Function name and parameters : triangle(side1, side2, side3)
3. Write a Python function to calculate the factorial of a number (a non-negative integer).
The function accepts the number as an argument.
Function name and parameters: factorial(n)
4. Write a Python function that takes a number as a parameter and check the number is
prime or not.
Function name and parameters: isprime(n)
5. Write a Python function that takes a number as a parameter and check the number is a
perfect number.
Function name and parameters: isperfect(n)
6. Implement all exercises in the previous lessons as functions.
72