0% found this document useful (0 votes)
16 views53 pages

Python MODULE II (Autosaved)

The document provides an overview of Boolean expressions and control statements in Python, including the use of logical operators (and, or, not) and the structure of if, elif, and else statements. It also covers looping constructs such as while and for loops, including their syntax and examples, as well as control flow mechanisms like break, continue, and else in loops. Additionally, it discusses nested loops and the concept of infinite loops, along with practical programming examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views53 pages

Python MODULE II (Autosaved)

The document provides an overview of Boolean expressions and control statements in Python, including the use of logical operators (and, or, not) and the structure of if, elif, and else statements. It also covers looping constructs such as while and for loops, including their syntax and examples, as well as control flow mechanisms like break, continue, and else in loops. Additionally, it discusses nested loops and the concept of infinite loops, along with practical programming examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 53

Boolean expressions

• A boolean expression (or logical expression)


evaluates to one of two states true or false.
• Python provides the boolean type that can be
either set to False or True.
• The not keyword can also be used to inverse a
boolean type.
• Eg: print(10 > 5)
Compound Boolean expressions
• Simple Boolean expressions can be chained
with the logical operators and , or and not.
• These are called compound Boolean
expressions.
• Eg:
– print(10>5 and 5>2)
– print(10<5 and 5>2)
– Print(10<5 or 5>2)
• Decisions are often based on more than one
factor.
• Example,
– you might decide to buy a shirt only if you like it
AND it costs less than R100.
– you might decide to go out to eat tonight if you
don’t have anything in the fridge OR you don’t feel
like cooking.
– you might only want to go to the concert tomorrow
if it is NOT raining.
• Conditions which consist of simpler conditions
joined together with AND, OR and NOT are
referred to as compound conditions.
• The and operator
• The AND operator in Python is and. A
compound expression made up of two
subexpressions and the and operator is only
true when both subexpressions are true:
• Eg:
– if mark >= 50 and mark < 65:
print("Grade B")
and is a binary operator so it must be given two operands. Each
subexpression must be a valid complete expression:
• The or operator
• The OR operator in Python is or.
• A compound expression made up of two
subexpressions and the or operator is true
when at least one of the subexpressions is true.
• This means that it is only false in the case
where both subexpressions are false, and is
true for all other cases.
• The not operator
• The NOT operator, not in Python, is a unary
operator: it only requires one operand.
• It is used to reverse an expression,
Precedence rule for boolean expression

1. Not
2. And
3. or
Short circuit evaluation/lazy evaluation
• Python does not evaluate the second operand
when the result is known by the first operand
alone and is called short circuit(lazy) evaluation.
• This is to speed up the evaluation.
• Eg: for logical expressions combined with and,
Python uses a short circuit technique to check if
the first sub expression is False, then the whole
statement must be False. So it returns False.
Control statements
• Control flow of a program: the order in which the
code executes.
• Control statement: a statement that determines the
control flow of a set of instructions.
• Control structure: a set of instructions and the control
statements controlling their execution.
• 3 fundamental forms of control:
– Sequential control
– Selection control
– Iterative control
Sequential control
• Implicit form of control.
• Instructions are executed in the order that
they are written.
• If a program contains only sequential control,
that is called a straight-line program.
Selection control
• Provided by a control statement that
selectively executes instructions.
• Selection control statements are also known
as decision making statements or conditional
statements.
• These statements enable the computer to
decide which block of code to be executed
based on some conditions.
Iterative control
• Provided by an iterative control statement
that repeatedly executes instructions.
• Iteration: the process of executing the same
block of code over and over many times.
• Loop: a programming structure that
implements iteration.
If statement in python
• "if statement" is written by using ‘if’ keyword
• Python supports the usual logical conditions
from mathematics:
– Equals: a == b
– Not Equals: a != b
– Less than: a < b
– Less than or equal to: a <= b
– Greater than: a > b
– Greater than or equal to: a >= b
• Python relies on indentation (whitespace at the beginning
of a line) to define scope in the code.
• Other programming languages often use curly-brackets for
this purpose.
• If statement begins with keyword ‘if’. The expression
followed is a boolean expression that determine whether
or not the body will be executed. A colon(:) must follow
the expression. There may be one or more statements to
be executed if the condition is true. The statements within
a block must all be indented the same number of spaces
from the left.
if (a < b):
Print(a)
This if statement will print an error.
If(a < b):
print(a)
This if statement will give the correct result
• Elif
– if the previous conditions were not true, then try
this condition.
– Eg:
• a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
• Else
– The else keyword catches anything which isn't
caught by the preceding conditions.
• Eg:
– a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
• Short hand if:
– If you have only one statement to execute, you
can put it on the same line as the if statement.
– Eg:
• if a > b: print("a is greater than b")
• 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.
– Eg:
• a=2
b = 330
print("A") if a > b else print("B")
• This technique is known as ternary operators or
conditional expressions
Flow chart for if-else
Flow chart for if-elif-else statement
Nested if-else

• Nested if-else statements in Python involve


placing one if statement inside another.
• This allows for more complex decision
making processes, where multiple
conditions need to be evaluated
sequentially.
• Syntax
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else
statement(s)
elif expression4:
statement(s)
else:
statement(s)
x = 15
if x > 10:
print("x is greater than 10")
if x % 2 == 0:
print("x is also even")
else:
print("x is odd")
else:
print("x is not greater than 10")
Multiway decision in python
• If you need to test more than two possible situations, multi-way selection
control statement if-elif-else can be used.
• Python executes only one block in the chain.
• When a test passes the code following that test is executed and skips the
rest of the tests.
if mark >= 80:
grade = A
elif mark >= 65:
grade = B
elif mark >= 50:
grade = C
else:
grade = D
Python Loops

• Python has two primitive loop commands:


– while loops
– for loops
While Loop in Python
• In python, a while loop is used to execute a block of statements
repeatedly until a given condition is satisfied.
• When the condition becomes false, the line immediately after the loop in
the program is executed.
Syntax :

while expression:
statement(s)
• All the statements indented by the same number of character spaces after
a programming construct are considered to be part of a single block of
code.
• Python uses indentation as its method of grouping statements.
count = 0
while (count < 3):
count = count + 1
print("Hello")
Output
Hello
Hello
Hello
break Statement

• With the break statement we can stop the loop


even if the while condition is true:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output
1
2
3
Continue statement :

• With the continue statement we can stop the current


iteration, and continue with the next.
• Eg:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Output
1
2
4
5
6
Else statement:

• With the else statement we can run a block of code once


when the condition no longer is true.
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Output
1
2
3
4
5
i is no longer less than 6
Python For Loops

• Python For loop is used for sequential traversal i.e.


it is used for iterating over an iterable like String,
Tuple, List, Set or Dictionary.
• With the for loop we can execute a set of
statements, once for each item in a list, tuple, set
etc.
• The for loop does not require an indexing variable
to set beforehand.
For Loops Syntax
for var in iterable:
# statements
Example
• Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Output
apple
banana
cherry
• Looping Through a String :
• Even strings are iterable objects, they contain a
sequence of characters:
Loop through the letters in the word "banana":
for x in "banana":
print(x)
Output
b
a
n
a
n
a
The break Statement :

• With the break statement we can stop the loop


before it has looped through all the items:
• Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Output
apple
banana
The continue Statement :

• With the continue statement we can stop the


current iteration of the loop, and continue with the
next:
• Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
Output
apple
cherry
The range() Function:

• To loop through a set of code a specified


number of times, we can use
the range() function,
• The range() function returns a sequence of
numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a
specified number.
• Example
• for x in range(6):
print(x)
• The range() function defaults to 0 as a starting value
• it is possible to specify the starting value by adding a
parameter:
– range(2, 6)
– which means values from 2 to 6 (but not including 6):
• Example
for x in range(2, 6):
print(x)
Output
2
3
4
5
• The range() function defaults to increment the sequence by 1.
• it is possible to specify the increment value by adding a third
parameter.
• Example
for x in range(2, 30, 4):
print(x)
Output
2
6
10
14
18
22
26
Else in For Loop
• The else keyword in a for loop specifies a block
of code to be executed when the loop is
finished:
• Example
– Print all numbers from 0 to 5, and print a message
when the loop has ended:
• for x in range(6):
print(x)
else:
print("Finally finished!")
Output
0
1
2
3
4
5
Finally finished!
Nested Loops
• A nested loop is a loop inside a loop.
• The "inner loop" will be executed one time for
each iteration of the "outer loop":
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)
Output
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
The pass Statement :

• for loops cannot be empty.


• if you have a for loop with no content, put in
the pass statement to avoid getting an error.
• Example
• for x in [0, 1, 2]:
pass
while Loop

With the while loop we can execute a set of statements as


long as a condition is true.
i=1
while i < 6:
print(i)
i += 1
Output
1
2
3
4
5
break
i=1
while i < 6:
print(i)
if (i == 3):
break
i += 1
output
1
2
3
Infinite loops
• An infinite loop that never ends; it never
breaks out of the loop.
• So, whatever is in the loop gets executed
forever, unless the program is terminated.
• For certain situations, an infinite loop may be
necessary.
• A very basic way of creating an infinite loop in
Python is to use a while statement.
• Eg:
while True:
print("hello world")
• This goes on forever and ever, unless the
program is terminated.
1. Program to find largest among two numbers.
2. Program to check whether a given year is leap
year or not.
3. Program to implement arithmetic calculator
using elif and else.
4. Program to find largest among three numbers
using nested –if statement.
5.Program to check whether the given number is
palindrome or not.
6. Program to find factorial of a given number
using for loop.

You might also like