Introduction To Programming 2
Python
Department of Computer Engineering
Astana IT University
Zamart Ramazanova
Senior-Lecturer
[Link]@[Link]
December, 2024
Topics
• Conditional Statements (if, if-else, elif)
• Logical Operators (not, and, or)
• Boolean Variables
• Introduction to Repetition Structures
• The while Loop: a Condition-Controlled Loop
• The for Loop: a Count-Controlled Loop
• Strings
2
CHAPTER 4
Decision
Structures and
Boolean Logic
CHAPTER 5
Repetition
Structures
3
Conditional Statements
• Conditional statements allow to make
decisions based on the values of variables or
the result of comparisons
• Python control flow statements are as follows:
The if statement
The if-else statement
The nested-if statement
The if-elif-else statement
4
The if Statement
5
The if Statement
• Control structure: logical design that
controls order in which set of
statements execute
• Sequence structure: set of statements
that execute in the order they appear
• Decision structure: specific action(s)
performed only if a condition exists
• Also known as selection structure
6
The if Statement (cont’d.)
• In flowchart, diamond represents
true/false condition that must be tested
• Actions can be conditionally executed
• Performed only when a condition is true
• Single alternative decision structure:
provides only one alternative path of
execution
• If condition is not true, exit the structure
7
The if Statement (cont’d.)
• Python syntax:
if condition:
Statement(s)
Note the colon after the boolean-
expression.
All of the statements controlled
by the if must be indented the
same amount.
8
If Statement Example
In file if_example.py:
9
Boolean Expressions and
Relational Operators
• Boolean expression: expression tested
by if statement to determine if it is true
or false
• Example: a > b
• true if a is greater than b; false otherwise
• Relational operator: determines
whether a specific relationship exists
between two values
• Example: greater than (>)
10
Boolean Expressions and
Relational Operators (cont’d.)
• >= and <= operators test more than one
relationship
• It is enough for one of the relationships to
exist for the expression to be true
• == operator determines whether the
two operands are equal to one another
• Do not confuse with assignment operator (=)
• != operator determines whether the
two operands are not equal
11
Boolean Expressions and
Relational Operators (cont’d.)
• Many logical expressions use Relational Operators:
• Logical expressions can be combined with logical
operators:
12
The if-else Statement
• Dual alternative decision structure: two
possible paths of execution
– One is taken if the condition is true, and the
other if the condition is false
• Syntax: if condition:
statements
else:
other statements
• if clause and else clause must be aligned
• Statements must be consistently indented
13
The if-else Statement
The if-else statement is used when you want something
to specific to happen if the Boolean expression is true and
If you want something else to happen if it is false
14
The if-else Statement
(cont’d.)
A two-way If-else statement executes one of two actions,
depending on the value of a Boolean expression.
General form:
i f boolean-expression:
true-case-statement(s)
else:
false-case-statement(s)
Note the colons after the boolean-expression and after the
else. All of the statements in both if and else branches should
be indented the same amount. 15
If-else Statement Example
In file [Link]:
16
The if-elif-else Statement
• if-elif-else statement: special version of
a decision structure
• Makes logic of nested decision structures simpler to
write
• Can include multiple elif statements
• Syntax: if condition_1:
statement(s)
elif condition_2:
statement(s) Insert as many elif clauses
elif condition_3: as necessary.
statement(s)
else
statement(s)
17
The if-elif-else Statement
(cont’d.)
18
The if-elif-else Statement
(cont’d.)
• Alignment used with if-elif-else
statement:
• if, elif, and else clauses are all aligned
• Conditionally executed blocks are consistently
indented
• if-elif-else statement is never required,
but logic easier to follow
• Can be accomplished by nested if-else
• Code can become complex, and indentation can cause
problematic long lines
19
If-elif-else Statement Example
In file [Link]:
20
Logical Operators
• Logical operators: operators that can
be used to create complex Boolean
expressions
• and operator and or operator: binary
operators, connect two Boolean expressions
into a compound Boolean expression
• not operator: unary operator, reverses the
truth of its Boolean operand
21
Logical Operators (cont’d.)
• In Python, Logical operators are used on conditional statements
(either True or False).
• They perform Logical AND, Logical OR and Logical
NOT operations
22
The and Operator
• Takes two Boolean expressions as
operands
• Creates compound Boolean expression that is
true only when both sub expressions are true
• Can be used to simplify nested decision
structures
• Truth table for
the and operator
23
The or Operator
• Takes two Boolean expressions as
operands
• Creates compound Boolean expression that is
true when either of the sub expressions is true
• Can be used to simplify nested decision
structures
• Truth table for
the or operator
24
Short-Circuit Evaluation
• Short circuit evaluation: deciding the
value of a compound Boolean
expression after evaluating only one
sub expression
• Performed by the or and and operators
• For or operator: If left operand is true, compound
expression is true. Otherwise, evaluate right
operand
• For and operator: If left operand is false,
compound expression is false. Otherwise, evaluate
right operand
25
The not Operator
• Takes one Boolean expressions as
operand and reverses its logical value
• Sometimes it may be necessary to place
parentheses around an expression to clarify
to what you are applying the not operator
• Truth table for the not operator
26
Checking Numeric Ranges with
Logical Operators
• To determine whether a numeric value
is within a specific range of values, use
and
Example: x >= 10 and x <= 20
• To determine whether a numeric value
is outside of a specific range of values,
use or
Example: x < 10 or x > 20
27
Logical Operators Example
28
Boolean Variables
• Boolean variable: references one of two
values, True or False
• Represented by bool data type
• Commonly used as flags
• Flag: variable that signals when some
condition exists in a program
• Flag set to False condition does not exist
• Flag set to True condition exists
29
Boolean Variables Example
30
Maybe take a break?
Introduction to Repetition
Structures
• Often have to write code that performs
the same task multiple times
• Disadvantages to duplicating code
• Makes program large
• Time consuming
• May need to be corrected in many places
• Repetition structure: makes computer
repeat included code as necessary
• Includes condition-controlled loops and count-
controlled loopsc
32
The while Loop: a Condition-
Controlled Loop
• while loop: while condition is true, do
something
• Two parts:
• Condition tested for true or false value
• Statements repeated as long as condition is true
• In flow chart, line goes back to previous part
• General format:
while condition:
statements
33
The while Loop: a Condition-
Controlled Loop (cont’d.)
The majority of programming
languages include syntax to repeat
operations.
while loop is one option. General form:
while condition:
statement(s)
Meaning: as long as the condition
remains true, execute the statements.
As with conditionals (if/elif/else), all of
the statements in the body of the
loop must be indented the
same amount.
34
The while Loop: a Condition-
Controlled Loop (cont’d.)
• In order for a loop to stop executing,
something has to happen inside the
loop to make the condition false
• Iteration: one execution of the body of
a loop
• while loop is known as a pretest loop
– Tests condition before performing an iteration
• Will never execute if condition is false to start with
• Requires performing some steps prior to the loop
35
The while Loop Example
Print i as long as i is less than 6:
In this example, we need to define an indexing
variable, i, which we set to 1.
36
The for Loop: a Count-
Controlled Loop
• Count-Controlled loop: iterates a specific
number of times
Use a for statement to write count-controlled
loop
• Designed to work with sequence of data items
– Iterates once for each item in the sequence
• General format:
for variable in [val1, val2, etc]:
statements
• Target variable: the variable which is the target
of the assignment at the beginning of each
iteration
37
The for Loop
In a for loop, you typically know how many times you’ll
execute.
General form:
for var in sequence:
statement(s)
Meaning: assign each element
of sequence in turn to var and
execute the statements.
As usual, all of the statements
in the body must be indented
the same amount.
38
The for Loop Example
• A for loop is used for iterating over a
sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
39
The for Loop Example
• A for loop is used for looping through a
String
40
The for Loop
41
Using the range Function with
the for Loop
• The range function simplifies the
process of writing a for loop
• range returns an iterable object
• Iterable: contains a sequence of values that can be
iterated over
• range characteristics:
• One argument: used as ending limit
• Two arguments: starting value and ending
limit
• Three arguments: third argument is step value
42
Loops Comparison
43
Using the Target Variable Inside
the Loop
• Purpose of target variable is to
reference each item in a sequence as
the loop iterates
• Target variable can be used in
calculations or tasks in the body of the
loop
Example: calculate square root of each
number in a range
44
Example: calculate square root
of each number in a range
45
• Sometimes the programmer does not
know exactly how many times the loop
will execute
• Can receive range inputs from the user,
place them in variables, and call the
range function in the for clause using
these variables
Be sure to consider the end cases: range
does not include the ending limit
46
Turtle Graphics: Using Loops to
Draw Designs
• This for loop iterates eight times to draw the
octagon:
47
Basic String Operations
• Many types of programs perform
operations on strings
• In Python, many tools for examining
and manipulating strings
• Strings are sequences, so many of the tools
that work with sequences (such as ranges,
lists, and tuples) also can be used
with strings
48
String Operations
• Strings in python are surrounded by
either single quotation marks, or
double quotation marks.
49
Accessing the Individual
Characters in a String
• To access an individual character in a
string:
• Use a for loop
• Format: for character in string:
• Useful when need to iterate over the whole string, such
as to count the occurrences of a specific character
• Each ‘character’ is simply a string of length 1
• Use indexing
• Each character has an index specifying its position in
the string, starting at 0
• Format: character = my_string[i]
50
51
Testing, Searching, and
Manipulating Strings
• You can use the in operator to
determine whether one string is
contained in another string
• General format: string1 in string2
• string1 and string2 can be string literals or
variables referencing strings
• Similarly you can use the not in
operator to determine whether one
string is not contained in another string
52
String Methods
• Strings in Python have many types of
methods, divided into different types of
operations
• General format:
[Link](arguments)
• Some methods test a string for
specific characteristics
• Generally Boolean methods, that return True
if a condition exists, and False otherwise
53
Copyright © 2018 Pearson Education, Inc.
String Methods (cont’d.)
Implement a function that prompts the user for an int
and error checks it. Keep prompting until they enter an int
54
Copyright © 2018 Pearson Education, Inc.
String Methods (cont’d.)
• Some methods create and return a
modified version of the string
• Simulate strings as mutable objects
• String comparisons are case-sensitive
• Uppercase characters are distinguished from
lowercase characters
• lower and upper methods can be used for
making case-insensitive string comparisons
55
Copyright © 2018 Pearson Education, Inc.
String Methods (cont’d.)
56
Copyright © 2018 Pearson Education, Inc.
String Methods (cont’d.)
• Programs commonly need to search for
substrings
• Several methods to accomplish this:
• endswith(substring): checks if the string
ends with substring
• Returns True or False
• startswith(substring): checks if the
string starts with substring
• Returns True or False
57
Copyright © 2018 Pearson Education, Inc.
String Methods (cont’d.)
• Several methods to accomplish this
(cont’d):
• find(substring): searches for
substring within the string
• Returns lowest index of the substring, or if the
substring is not contained in the string, returns -1
• replace(substring, new_string):
• Returns a copy of the string where every
occurrence of substring is replaced with
new_string
58
Copyright © 2018 Pearson Education, Inc.
String Methods (cont’d.)
59
Copyright © 2018 Pearson Education, Inc.
The Repetition Operator
• Repetition operator: makes multiple
copies of a string and joins them
together
• The * symbol is a repetition operator when
applied to a string and an integer
• String is left operand; number is right
• General format: string_to_copy * n
• Variable references a new string which
contains multiple copies of the original string
60
Copyright © 2018 Pearson Education, Inc.
Splitting a String
• split method: returns a list containing
the words in the string
• By default, uses space as separator
• Can specify a different separator by passing it
as an argument to the split method
• Also referred to as parsing a string.
61
Copyright © 2018 Pearson Education, Inc.
Summary
• This chapter covered:
• Conditional statements, including
• Single alternative condition structures
• Dual alternative conditon structures
• Nested decision structures
• Relational operators and logical operators as used in
creating Boolean expressions
• Boolean variables
• Repetition structures
• Infinite loops and how they can be avoided
• range function as used in for loops
• String and methods
62