0% found this document useful (0 votes)
13 views73 pages

A1244014546 - 20248 - 5 - 2025 - 3 Conditionals

The document provides an overview of conditionals and iterations in Python, detailing how to use input functions, conditional statements (if, elif, else), and loops (for, while). It explains the importance of indentation, the use of logical operators, and various control flow statements such as break and continue. Additionally, it includes examples and exercises to reinforce the concepts discussed.

Uploaded by

AMAR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views73 pages

A1244014546 - 20248 - 5 - 2025 - 3 Conditionals

The document provides an overview of conditionals and iterations in Python, detailing how to use input functions, conditional statements (if, elif, else), and loops (for, while). It explains the importance of indentation, the use of logical operators, and various control flow statements such as break and continue. Additionally, it includes examples and exercises to reinforce the concepts discussed.

Uploaded by

AMAR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 73

Conditionals

and
Iterations
Keyboard Input
• input(): built in function to get data from keyboard.
• Takes data in the form of string.
• Eg:
>>> input1 = input ()
What are you waiting for?
>>> print input1
What are you waiting for?
•Before calling input, it is a good idea to print a message telling the user what to input.
This message is called a prompt.
•A prompt can be supplied as an argument to input.
• Eg:
>>> name = input ("What...is your name? ")
What...is your name? Arthur, King of the Britons!
>>> print name
Arthur, King of the Britons!
• If we expect the response to be an integer, then type conversion needs
to be done.
• Eg:
prompt = "What is the airspeed velocity of an unladen swallow?"
speed =int(input(prompt))
Conditional Execution

• To write useful programs we need the ability to check conditions and


change the behaviour of the program accordingly.
• Different conditional statements in python are:
– IF
– IF ---Else (Alternative Execution)
– IF--- ELIF---- ELSE (Chained Conditionals)
– Nested Conditionals
If Condition
• If x > 0:
print "x is positive“
• The Boolean expression after the if statement is called the condition. If it is true,
then the indented statement gets executed. If not, nothing happens.
• Structure of If
– HEADER:
FIRST STATEMENT
...
LAST STATEMENT
If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")
Indentation

• Python relies on indentation (whitespace at the


beginning of a line) to define scope in the code.
• If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an
error
If Condition
• There is no limit on the number of statements that can appear in the
body of an if statement, but there has to be at least one.
• Occasionally, it is useful to have a body with no statements (usually as a
place keeper for code you haven't written yet). In that case, you can use
the pass statement, which does nothing.
The pass Statement

• if statements cannot be empty, but if you for some


reason have an if statement with no content, put in
the pass statement to avoid getting an error.

a = 33
b = 200

if b > a:
pass
Elif

• The elif keyword is Python's way of saying "if the


previous conditions were not true, then try this
condition".
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.
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")
You can also have an else without the elif:

• a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Short Hand If

• If you have only one statement to execute, you can put


it on the same line as the if statement.
• One line if statement:
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:
• One line if else statement:
a = 2
b = 330
print("A") if a > b else print("B")
You can also have multiple else
statements on the same line:

• One line if else statement, with 3 conditions:


a = 330
b = 330
print("A") if a > b else print("=") if a ==
b else print("B")
And
• The and keyword is a logical operator, and is used to
combine conditional statements:

• Test if a is greater than b, AND if c is greater than a:


a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or

• The or keyword is a logical operator, and is used to combine


conditional statements:

• Test if a is greater than b, OR if a is greater than c:


a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is
True")
NOT

• The not keyword is a logical operator, and is used to reverse the


result of the conditional statement:

• Test if a is NOT greater than b:


a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Nested if

• You can have if statements inside if statements, this is


called nested if statements.
x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
If Condition
• There is no limit on the number of statements that can appear in the
body of an if statement, but there has to be at least one.
• Occasionally, it is useful to have a body with no statements (usually as a
place keeper for code you haven't written yet). In that case, you can use
the pass statement, which does nothing.
Alternative Execution
• A second form of the if statement is alternative execution, in which there
are two possibilities and the condition determines which one gets
executed.
• Eg:

The alternatives are called branches.


Continue….

• Since the condition must be true or false, exactly one of the


alternatives will be executed. The alternatives are called branches,
because they are branches in the flow of execution.
Chained Conditionals
• Sometimes there are more than two possibilities and we need more
than two branches.

NOTE: There is no limit of the number of elif statements, but the last
branch has to be an else statement
Nested conditionals
• One conditional can also be nested within another.
if 0 < x and x < 10:
print "x is a positive single digit.“

• Python provides an alternative syntax that is similar to mathematical


notation:
Shortcuts for Conditions
• Numeric value 0 is treated as False
• Empty sequence "", [] is treated as False
• Everything else is True
if m%n:
(m,n) = (n,m%n)
else:
gcd = n
Avoid Nested If
• For example, We can rewrite the following code using a single
conditional:
if 0 < x:
if x < 10:
print "x is a positive single digit.“
Better way:
if 0 < x and x < 10:
print "x is a positive single digit."
ITERATION
Doing the Same Thing Many Times
• Its possible to do something repeatedly by just writing it all out.
• Print ‘hello’ 5 times
>>> print('Hello!')
Hello
>>> print('Hello!')
Count n Hello
times >>> print('Hello!')
Hello
>>> print('Hello!')
Hello
Statements >>> print('Hello!')
Hello
Iteration and Loops
• A loop repeats a sequence of statements
• A definite loop repeats a sequence of statements a predictable number
of times

Count n
times

Statements
For loop
#Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
• NOTE: The for loop does not require an indexing variable
to set beforehand.
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)
The for Loop

• Python’s for loop can be used to iterate a definite number of times


for <variable> in range(<number of times>): <statement>
• Use this syntax when you have only one statement to repeat
for <variable> in range(<number of times>):
<statement-1>
<statement-2>

<statement-n> >>> for x in range(3):
... print('Hello!')
... print('goodbye')
•Use indentation to format two or ...
Hello!
more statements below the loop goodbye
Hello!
header goodbye
Hello!
goodbye
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.
• Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
• The range() function defaults to 0 as a starting value, however 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).
• The range() function defaults to increment the sequence by 1, however it is possible
to specify the increment value by adding a third parameter: range(2, 30, 3):
Range Function

• Range returns an immutable sequence objects of integers between the given


start integer to the stop integer.
• range() constructor has two forms of definition:
– range(stop)
– range(start, stop, step)
• start - integer starting from which the sequence of integers is to be returned
• integer before which the sequence of integers is to be returned.
The range of integers end at stop - 1.
– step (Optional) - integer value which determines the increment between each integer in the
sequence
Using the Loop Variable
• The loop variable picks up the next value in a sequence on each pass
through the loop
• The expression range(n) generates a sequence of ints from 0
through n - 1
loop variable
Counting from 1 through n

• The expression range(low, high) generates a sequence of ints from low


through high - 1
Counting from n through 1

• The expression range(high, low, step) generates a sequence of ints from


high through low+1.
Skipping Steps in a Sequence

• The expression range(low, high, step) generates a sequence of ints


starting with low and counting by step until high - 1 is reached or
exceeded
Else in For Loop

The else keyword in a for loop specifies a block of


code to be executed when the loop is finished

for x in range(6):
print(x)
else:
print("Finally finished!")
The else block will NOT be executed
if the loop is stopped by a break statement.

Break the loop when x is 3, and see what happens


with the else blocK

for x in range(6):
if x == 3: break
print(x)
else:
print("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", “papaya", "cherry"]

for x in adj:
for y in fruits:
print(x, y)
The pass Statement

• for loops cannot be empty, but if you for some reason have a for loop with no
content, put in the pass statement to avoid getting an error.

for x in [0, 1, 2]:


pass
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
• Exit the loop when x is "banana", but this time the break
comes before the print:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
break
print(x)
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)
While Loop
• Note: remember to increment i, or else the loop will
continue forever.

• The while loop requires relevant variables to be ready,


in this example we need to define an indexing
variable, i, which we set to 1.
Flow of Execution for WHILE Statement
Looping Until User Wants To Quit
The break Statement

• With the break statement we can stop the loop even if the
while condition is true:

• Exit the loop when i is 3:


i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
The continue Statement

• With the continue statement we can stop the current iteration, and
continue with the next:

• Continue to the next iteration if i is 3:

i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
The else Statement

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


once when the condition no longer is true:
• Print a message once the condition is false
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
program to display numbers from 1 to 5

# initialize the variable


i=1
n=5
# while loop from i = 1 to 5
while i <= n:
print(i)
i=i+1
Printing those numbers divisible by either

5 or 7 within 1 to 50 using a while loop


i=1
while i<51:
if i%5 == 0 or i%7==0 :
print(i, end=' ')
i+=1
program to calculate the sum of numbers
until the user enters zero

total = 0
number = int(input('Enter a number: '))
# add numbers until number is zero
while number != 0:
total += number # total = total + number
# take integer input again
number = int(input('Enter a number: '))
print('total =', total)
Exercise
1. Write a password guessing program to keep track of how many times the
user has entered the password wrong. If it is more than 3 times, print "You
have been denied access." and terminate the program. If the password is
correct, print "You have successfully logged in." and terminate the
program.
2. Write a program that asks for two numbers. If the sum of the numbers is
greater than 100, print "That is a big number" and terminate the program.
3. Write a Python program that accepts a word from the user and reverse it.
4. Write a python program to find those numbers which are divisible by 7
and multiples of 5, between 1500 and 2700.
5. Write a Python program to get the Fibonacci series between 0 to 50.
6. Write a Python program which iterates the integers from 1 to 50. For multiples of
three print "Fizz" instead of the number and for the multiples of five print "Buzz".
For numbers which are multiples of both three and five print "FizzBuzz“
7. Write a Python program to check whether an alphabet is a vowel or consonant.
8. Write a Python program to check a triangle is equilateral, isosceles or scalene.
Note :An equilateral triangle is a triangle in which all three sides are equal.
A scalene triangle is a triangle that has three unequal sides.
An isosceles triangle is a triangle with (at least) two equal sides.
Top 20 Python Coding Questions and
Answers for Programming
• https://www.prepbytes.com/blog/python/top-20-coding-questions-
for-basic-python-programming/
1.Palindrome Check: Write a function that takes a string as input and returns
True if it's a palindrome (reads the same forwards and backwards), and False
otherwise.
2.FizzBuzz: Write a program that prints the numbers from 1 to 100. But for
multiples of 3, print "Fizz" instead of the number, and for the multiples of 5, print
"Buzz". For numbers which are multiples of both 3 and 5, print "FizzBuzz".
3.Factorial Calculation: Write a function that calculates the factorial of a given
positive integer n using recursion.
4.List Comprehension - Even Squares: Write a one-liner list comprehension that
generates a list of squares of even numbers from 1 to 10.
5.Word Frequency Counter: Write a function that takes a string as input and
returns a dictionary containing the frequency of each word in the string. Ignore
punctuation and convert all words to lowercase.
6.Reverse a String: Write a function to reverse a string without using any built-in string
reversal functions or slicing.
7.Duplicate Removal: Write a function that takes a list as input and returns a new list with
all the duplicate elements removed while maintaining the original order.
8.Matrix Transposition: Write a function to transpose a given square matrix (list of lists).
9.Anagram Check: Write a function that takes two strings as input and returns True if they
are anagrams of each other, and False otherwise.
10.Prime Number Check: Write a function that takes an integer as input and returns True
if it's a prime number, and False otherwise.

You might also like