Module 2 Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

MODULE 2 | PYTHON CONTROL STATEMENTS AL JAMIA ARTS AND SCIENCE COLLEGE

Module 2
1. Control Statements in Python
1. Control Flow:
o It refers to the order in which a program's code is executed.
2. Control Statement:
o A command that controls the flow of program execution.
o Python has three fundamental forms of control: Sequential, Selection, and Iterative.
3. Sequential Control:
o This is the default control structure.
o Instructions are executed in the order they are written, one after another.
o A program with only sequential control is known as a straight-line program.
4. Selection Control:
o Executes instructions selectively based on certain conditions.
o Uses statements like if, else, and elif to decide which code to execute.
5. Iterative Control:
o Repeats the execution of instructions based on a condition.
o Implemented using loops (for and while).
6. Control Structure:
o A combination of control statements that dictate the program's flow.
o A control structure is a set of instructions that determines how the program flows or executes different
parts of the code.

2. Boolean Expressions
 A Boolean expression evaluates to either True or False.

 Python has a Boolean type with two values: True and False.

 Boolean expressions are used in conditions for selection (if statements) and loops (while statements).

Comparison operators used to create Boolean expressions:

 == (Equal to)
 != (Not equal to)
 < (Less than)
 > (Greater than)
 <= (Less than or equal to)
 >= (Greater than or equal to)

1
MODULE 2 | PYTHON CONTROL STATEMENTS AL JAMIA ARTS AND SCIENCE COLLEGE

 Integers and floats can be compared using comparison operators.

 Strings are compared case-sensitively based on Unicode (ASCII) values.

 Example of string comparison:

 Strings are ordered lexicographically (dictionary order) based on Unicode values.

 Use ord() to find the Unicode value of a character (e.g., ord('A') returns 65).

 Boolean literals (True, False) are not quoted; quoting them makes them strings.

 Boolean expressions can be simple comparisons like 10 <= 20.

 Write True and False without quotes (e.g., True, not 'True').
 If you use quotes, they become strings ('True'), not Boolean values. This means they will not
behave like Boolean values in conditions or logical operations.

2
MODULE 2 | PYTHON CONTROL STATEMENTS AL JAMIA ARTS AND SCIENCE COLLEGE

Explanation: Since is_sunny is a Boolean value (True), the condition in the if statement is evaluated as
True, so the output will be "It's a sunny day!"

Explanation: Since is_sunny is a string ('True'), the condition in the if statement is evaluated as True
(because non-empty strings are considered True), so the output will be "It's a sunny day!" However, this is
not the intended usage of Boolean values, as the string 'True' is not equivalent to the Boolean True.

2.2Compound Boolean Expressions


a) Logical expressions use comparison operators combined with Boolean operators: and, or, and
not
A combination of two or more Boolean expressions using logical operators is called a compound Boolean
expression. Boolean operators: AND OR NOT

A B A and B A or B not A
False(0) False(0) False(0) False(0) True(1)
False(0) True(1) False(0) True(1) True(1)
True(1) False(0) False(0) True(1) False(0)
True(1) True(1) True(1) True(1) False(0)

Example:

3
MODULE 2 | PYTHON CONTROL STATEMENTS AL JAMIA ARTS AND SCIENCE COLLEGE

 With Parentheses (not (a == 7 and b == 6)): Applies not to the result of the entire condition inside
the parentheses.
 Without Parentheses (not a == 7 and b == 6): Applies not only to a == 7 before combining with
== 6.

b) Identity operators:

 is: True if both variables refer to the same object (e.g., ps is p)


 is not: True if both variables do not refer to the same object (e.g., ps is not p)

c) Membership operators:

 in: True if a variable is in a specified sequence (e.g., 'good' in 'this is a great example')
 not in: True if a variable is not in a specified sequence (e.g., 'good' not in 'this is a great
example')

Example:

4
MODULE 2 | PYTHON CONTROL STATEMENTS AL JAMIA ARTS AND SCIENCE COLLEGE

2.3 Short-Circuit (Lazy) Evaluation:

Stops evaluating a Boolean expression as soon as the result is determined.


and Operator:

 If the first operand is False, the whole expression is False regardless of the second operand.

and Expression:

 Python evaluates from left to right.


 If the first sub-expression is False, it skips evaluating the second sub-expression.

or Operator:

 If the first operand is True, the whole expression is True regardless of the second operand.

or Expression:

 Python evaluates from left to right.


 If the first sub-expression is True, it skips evaluating the second sub-expression.

5
MODULE 2 | PYTHON CONTROL STATEMENTS AL JAMIA ARTS AND SCIENCE COLLEGE

3. Selection control:
 A selection control statement provides selective execution of instructions.
 It controls the execution of a given set of instructions.
 In some cases, a programmer wants a block of code to execute when a specific condition is satisfied.
 Python provides selection control statements, also known as decision-making or conditional statements.
 Selection control statements evaluate single or multiple test expressions.
 The result of these test expressions is either True or False.
 The outcome of the condition determines which block of code will execute:

 If the condition is True, one block is executed.


 If the condition is False, another block or no block may execute.

3.1. if statement
The if statement is the simplest form. It takes a condition and evaluates to either True or False.If
the condition is True, then the True block of code will be executed, and if the condition is False, then
the block of code is skipped, and The controller moves to the next line.
Syntax: if condition:
# Statements to execute if
# condition is true

flowchart Example

Output:

3.2. if-else statement


The if-else statement checks the condition and executes the if block of code when the condition is True, and if the
condition is False, it will execute the else block of code.
Syntax:
if (condition): # Executes this block if, condition is true
else: # Executes this block if ,condition is false

6
MODULE 2 | PYTHON CONTROL STATEMENTS AL JAMIA ARTS AND SCIENCE COLLEGE

flowchart Example

Output:

3.3.if-elif-else Multi-Way selection:


In Python, the if-elif-else condition statement has an elif blocks to chain multiple conditions one after
another. This is useful when you need to check multiple conditions.

Syntax

if (condition):
statement
elif (condition):
statement
else:
statement

flowchart Example

Output:

7
MODULE 2 | PYTHON CONTROL STATEMENTS AL JAMIA ARTS AND SCIENCE COLLEGE

3.4. Nested if-else:


In Python, the nested if-else statement is an if statement inside another if-else statement. It is allowed in
Python to put any number of if statements in another if statement.

Syntax:
if condition1:

if condition2: statements1

else:

statements2

else:

Statement 3Statement n

flowchart Example

Output:

4. Iterative control
 Iteration refers to executing the same block of code repeatedly.
 A loop is a programming structure that implements iteration.
 In Python, iterative control statements allow repeated execution of a set of instructions.
 These iterative control structures are often called loops because of their repeated execution.
 Two types of iteration in programming:

8
MODULE 2 | PYTHON CONTROL STATEMENTS AL JAMIA ARTS AND SCIENCE COLLEGE

o Definite iteration: The number of iterations is known before the loop starts.
 Examples:
 Displaying numbers from 1 to 100.
 Displaying numbers from 1 up to a user input limit.
 Getting a specified number of inputs from the user.
o Indefinite iteration: The number of iterations is unknown and depends on a condition being
met.
 Examples:
 Displaying numbers from 1 onwards and asking the user each time if they
want to continue.
 Getting inputs from the user until a specific end sequence is entered.
 Python supports two iterative control statements: while and for.

4.1. The while statement:


I. while loop:

In Python, The while loop statement repeatedly executes a code block while a particular condition is
true.

In a while-loop, every time the condition is checked at the beginning of the loop, and if it is true, then
theloop’s body gets executed. When the condition became False, the controller comes out of the block.

Syntax flowchart Example


Initialization

while condition:

Body of while loop Output:

4.2. The for statement:

II. for loop:

Using for loop, we can iterate any sequence or iterable variable. The sequence
can bestring, list, dictionary, set, or tuple.

9
MODULE 2 | PYTHON CONTROL STATEMENTS AL JAMIA ARTS AND SCIENCE COLLEGE

Syntax: flowchart Example


for element in sequence:

body of for loop

Output:

4.3. range() function:


The range() function in Python generates a sequence of numbers and is commonly used in loops. It can
accept one, two, or three arguments, which control the start, stop, and step of the sequence.

Here’s a detailed explanation with examples:

1. Basic syntax:
o range(stop) generates numbers from 0 up to but not including stop.
o range(start, stop) generates numbers from start up to but not including stop.
o range(start, stop, step) generates numbers from start to stop - 1 with a step size of
step.

10
MODULE 2 | PYTHON CONTROL STATEMENTS AL JAMIA ARTS AND SCIENCE COLLEGE

The following examples show how range can be used to produce a variety of sequences:

11
MODULE 2 | PYTHON CONTROL STATEMENTS AL JAMIA ARTS AND SCIENCE COLLEGE

4.3. break & continue Statement on Loops:


i) Break Statement in Python
 The break statement is used to exit a loop prematurely when a certain condition is met.

 It immediately stops the loop and proceeds with the code after the loop.

ii) Continue Statement in Python


 The continue statement skips the rest of the loop body for the current iteration and moves to the next
iteration.
 It does not terminate the loop, but it skips to the next cycle of the loop.

12
MODULE 2 | PYTHON CONTROL STATEMENTS AL JAMIA ARTS AND SCIENCE COLLEGE

In summary:

 break exits the loop.


 continue skips the current iteration but continues the loop.

13
MODULE 2 | PYTHON CONTROL STATEMENTS AL JAMIA ARTS AND SCIENCE COLLEGE

4.4. else Clause on Loops:


 The else clause can be used with for and while loops in Python.

 It executes only if the loop completes normally, without hitting a break statement.

14
MODULE 2 | PYTHON CONTROL STATEMENTS AL JAMIA ARTS AND SCIENCE COLLEGE

Summary:

 The else block runs if the loop does not break.

4.5. Nested Loops:


Definition: A nested loop is a loop inside another loop. The inner loop runs completely for each iteration of
the outer loop.

Explanation:

 The outer loop (i) runs from 0 to 2.


 For each value of i, the inner loop (j) runs from 0 to 1.
 This prints every combination of i and j.

15
MODULE 2 | PYTHON CONTROL STATEMENTS AL JAMIA ARTS AND SCIENCE COLLEGE

Summary:

 Nested loops allow you to perform repeated actions within repeated actions. For each time the outer loop runs,
the inner loop runs completely.

4.6. Infinite Loops:


 An infinite loop is a loop that runs indefinitely without a terminating condition. This usually occurs when the
loop's condition is always true.

Example:

Explanation:

 The while True: statement creates a loop that never ends because the condition True is always
satisfied.
 This will keep printing "This will print forever" until the program is forcibly stopped (e.g., using Ctrl
+ C in the terminal).

Causes of Infinite Loops:

1. Condition Never Becomes False: If the loop's condition is designed to always evaluate as true.
2. Missing Loop Control: Forgetting to update variables that control the loop condition.

16
MODULE 2 | PYTHON CONTROL STATEMENTS AL JAMIA ARTS AND SCIENCE COLLEGE

Explanation:

 This loop will print the value of count (which is 0) indefinitely because count never changes, so the
condition count < 5 remains true.

Breaking Out of Infinite Loops:

 You can stop an infinite loop using keyboard interrupts like Ctrl + C in most programming environments.
 It’s essential to ensure that your loops have proper conditions to avoid accidental infinite loops.

17

You might also like