0% found this document useful (0 votes)
23 views23 pages

INT102 1.3 Conditionals & Iterations

The document covers the basics of conditionals and iterations in Python, detailing various conditional statements such as 'if', 'if else', 'if elif else', and nested conditionals. It also explains the use of loops, including 'for' and 'while' loops, and provides examples of how to implement them in programming tasks. Additionally, it includes programming exercises to reinforce the concepts learned.

Uploaded by

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

INT102 1.3 Conditionals & Iterations

The document covers the basics of conditionals and iterations in Python, detailing various conditional statements such as 'if', 'if else', 'if elif else', and nested conditionals. It also explains the use of loops, including 'for' and 'while' loops, and provides examples of how to implement them in programming tasks. Additionally, it includes programming exercises to reinforce the concepts learned.

Uploaded by

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

INT-102: Python

Unit 1: Conditionals and Iterations

Created By
Mr. Prince Verma
School of Computer Science & Engg.
©LPU CSE101 C Python
Programming
Lovely Professional University
@LPU INT102
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

©LPU CSE101
@LPU C Python
INT102 Programming
if condition
• After the if statement a Boolean expression is used i.e. the condition. If it is
true, then the indented statement gets executed. If not, nothing happens.
• 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.
• Syntax: if condition:
statement(s)

E.g.: If x > 0:
print ("x is positive “)

©LPU CSE101
@LPU C Python
INT102 Programming
if else condition (Alternative Execution)
• It is a second form of the if statement, in which there are two possibilities and
the condition determines which one gets executed.
• The condition is either true or false, thus exactly one of the alternatives will
be executed. The alternatives are called branches.
• Syntax: if condition:
statement(s)
else:
statement(s)
E.g.: if x%2 == 0:
print (x, "is even“)
else:
print (x, "is odd“)
©LPU CSE101
@LPU C Python
INT102 Programming
if elif else condition (Chained Execution)
• It is a form of the if statement, in which there are more than two possibilities
and thus more than two branches are required.
• There is no limit of the number of elif statements, but the last branch
has to be an else statement
• Syntax: if condition1: E.g.: if x < y:
statement(s) print (x, "is less than", y)
elif condition2: elif x > y:
statement(s) print (x, "is greater than", y)
else: else:
statement(s) print (x, "and", y, "are equal ")

©LPU CSE101
@LPU C Python
INT102 Programming
Nested conditionals
• It is a form of the if statement, in which one conditional can also be nested
within another.
E.g.: if x == y:
print (x, "and", y, "are equal")
else:
if x < y:
print (x, "is less than", y)
else:
print (x, "is greater than", y)

©LPU CSE101
@LPU C Python
INT102 Programming
Example
• It is a form of the if statement, in which one conditional can also be nested
within another.
E.g.: if 0 < x and x < 10:
print "x is a positive single digit. "

OR

if 0 < x < 10:


print "x is a positive single digit."

©LPU CSE101
@LPU C Python
INT102 Programming
Shortcuts for Conditions
• Numeric value 0 is treated as False
• Empty sequence "", [] is treated as False
• Everything else is True
E.g. if m%n:
(m,n) = (n,m%n)
else:
gcd = n

©LPU CSE101
@LPU C Python
INT102 Programming
Avoid Nested If
• We can rewrite the following code using a single conditional:

E.g.: 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."

©LPU CSE101
@LPU C Python
INT102 Programming
Programs
• Q1. WAP to find even and odd numbers
• Q2. WAP to find whether number is a prime number or not.
• Q3. Write a Python program to check a triangle is equilateral, isosceles or
scalene.

©LPU CSE101
@LPU C Python
INT102 Programming
Iterations
• It’s possible to do something repeatedly by just writing it all out
• Print ‘hello’ 5 times
E.g.: print("Hello!")
Count n print("Hello!")
times
print("Hello!")
print("Hello!")
print("Hello!")
Statements
Output: Hello
Hello
Hello
Hello
Hello
©LPU CSE101
@LPU C Python
INT102 Programming
Iterations
• A loop repeats a sequence of statements.
• A definite loop repeats a sequence of statements a predictable number of
times.
• E.g. Print ‘hello’ 3 times.

E.g.: print("Hello!") Count n


E.g.: for x in range(3):
print("Hello!") times print('Hello!')
print("Hello!") Output: Hello
Output: Hello Hello
Hello Statements Hello
Hello

©LPU CSE101
@LPU C Python
INT102 Programming
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

©LPU CSE101
@LPU C Python
INT102 Programming
range function

Range Function Output


Range(5) [0,1,2,3,4]
Range(1,5) [1,2,3,4]
Range(1,10,2) [1,3,5,7,9]
Range(5,0,-1) [5,4,3,2,1]
Range(5,0,-2) [5,3,1]
Range(-4,4) [-4,-3,-2,-1,0,1,2,3]
Range(1,1) empty
Range(0,1) 0
Range(0) empty

©LPU CSE101
@LPU C Python
INT102 Programming
for Loop
• Python’s for loop can be used to iterate a definite number of times.
– Syntax when you have only one statement to repeat:
for <variable> in range(<number of times>): <statement>
– Syntax when you have only one statement to repeat:
for <variable> in range(<number of times>): E.g.: for x in range(3):
<statement-1> print('Hello!’)
<statement-2> print('goodbye')
Output: Hello!

goodbye
<statement-n> Hello!
goodbye
Hello!
goodbye
©LPU CSE101
@LPU C Python
INT102 Programming
for Loop
• 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 int from 0 through n - 1

E.g.1: for x in range(5): print(x)


Output: 0
1
2
3
4
E.g.2: list(range(5)) #Show as a list
Output: [0, 1, 2, 3, 4]

©LPU CSE101
@LPU C Python
INT102 Programming
for Loop
• Changing range of for loop:
– range(low, high) generates a sequence of ints from low through high – 1.
– range(low, high,step) generates a sequence of ints from low through high – 1.
– range(high, low, step) generates a sequence of ints from high through low+1 by
step.

E.g.3: E.g.4: E.g.5:


for x in range(1, 6): print(x) for x in range(6, 1, -1): print(x) for x in range(1, 6, 2): print(x)
Output: 1 Output: 6 Output: 1
2 5 3
3 4 5
4 3 list(range(1, 6, 2)) #Show as a list
5 2 Output: [1, 3, 5]
©LPU CSE101
@LPU C Python
INT102 Programming
Using a for Loop in a Real Problem
• An investor deposits $10,000 principal = 10000
with a agency and receives a rate = 0.06
statement predicting the interest term = 5
rate of 6% for a period of 5 years. totalinterest = 0
WAP to prints the beginning for year in range(1,term+1):
interest = principal * rate
principal, the interest earned for
print("Year:",year)
each year, total amount earned
print(" Principal:",principal)
and the final principal.
print(" Interest:",interest)
principal = principal + interest
totalinterest = totalinterest + interest
print("Total Interest:",totalinterest)
print("Total Principal:",principal)
©LPU CSE101
@LPU C Python
INT102 Programming
while Loop
• A for loop is used when a program knows it needs to repeat a block of code
for a certain number of times.
• A while loop is used when a program needs to loop until a particular
condition occurs.
– Syntax when you have only one statement to repeat:
while condition: <statement>
– Syntax when you have only one statement to repeat:
while condition: :
<statement-1>

<statement-n>

©LPU CSE101
@LPU C Python
INT102 Programming
while Loop
• Evaluate Condition(0 or 1):
– If condition is false(0), exit the while condition and continue
execution in next statement.
– If condition is true(1), execute each of the statement in the body and
go back to step 1.
E.g.: i = 0 Output: 0
while i < 5: 1
print(i) 2
i + =1 3
4

©LPU CSE101
@LPU C Python
INT102 Programming
Programs
• Q1. 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.
• Q2. WAP that accepts a word from the user and reverse it.
• Q3. WAP to check whether an alphabet is a vowel or consonant.(solved)
• Q4. WAP to find those numbers which are divisible by 7 and multiples of 5,
between 1500 and 2700.
• Q5. WAP to find sum of n natural numbers.(solved)
• Q6. WAP to find factorial of a number. (Solved)

©LPU CSE101
@LPU C Python
INT102 Programming
Programs
• Q7. WAP to get the Fibonacci series between 0 to 50.(Solved)
• Q8. WAP 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“.

©LPU CSE101
@LPU C Python
INT102 Programming
Any
Questions?
©LPU CSE101
@LPU C Python
INT102 Programming

You might also like