100% found this document useful (1 vote)
1K views

Chapter-4 Conditional and Iterative Statements in Python

The document discusses conditional statements, iteration, and string manipulation in Python. It covers the if, if-else, and if-elif-else statements, as well as for and while loops. It provides syntax examples and sample programs to find discounts based on amount, determine if a number is prime, calculate digit and reverse sums, and concatenate and replicate strings.

Uploaded by

ashishiet
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
100% found this document useful (1 vote)
1K views

Chapter-4 Conditional and Iterative Statements in Python

The document discusses conditional statements, iteration, and string manipulation in Python. It covers the if, if-else, and if-elif-else statements, as well as for and while loops. It provides syntax examples and sample programs to find discounts based on amount, determine if a number is prime, calculate digit and reverse sums, and concatenate and replicate strings.

Uploaded by

ashishiet
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/ 30

A Presentation on

Conditional Statements, Iteration


And String Manipulation
Conditional Statements
The if statement is the conditional
statement in Python. There are 3
forms of if statement:
1. Simple if statement
2. The if..else statement
3. The If..elif..else statement
Simple if statement
• The if statement • Syntax The header of if
statement, colon
tests a condition & if <condition>: (:) at the end
in case the condition statement
is True, it carries out Body
[statements] of if
some instructions
and does nothing in • e.g.
case the condition is if amount>1000:
False. disc = amount * .10
Example of if statement
• Prog to find discount (10%) if amount is more than 1000.
Price = float (input(“Enter Price ? ” ))
Qty = float (input(“Enter Qty ? ” ))
Amt = Price* Qty
print(“ Amount :” , Amt)
if Amt >1000:
Body of if statement
disc = Amt * .10
(will be executed incase condition is true)
print(“Discount :”, disc)
The if-else statement
• The if - else statement • Syntax
tests a condition and if <condition> :
in case the condition statement Block 1
[statements]
is True, it carries out else :
statements indented statement
below if and in case [statements] Block 2

the condition is False, • e.g.


it carries out if amount>1000:
statement below else. disc = amount * 0.10
else:
disc = amount * 0.05
Example of if-else statement
• Prog to find discount (10%) if amount is more than 1000,
otherwise (5%).
Price = float (input(“Enter Price ? ” ))
Qty = float (input(“Enter Qty ? ” ))
Amt = Price* Qty
print(“ Amount :” , Amt)
if Amt >1000 :
disc = Amt * .10 block 1
print(“Discount :”, disc) (will be executed incase condition is true)

else :
disc = Amt * .05 block 2
print(“Discount :”, disc) (will be executed incase condition is False)
The if..elif statement
• The if - elif statement has • Syntax
multiple test conditions and if <condition1> :
statement
in case the condition1 is Block 1
[statements]
True, it executes statements elif <condition2> :
in block1, and in case the statement
condition1 is False, it moves [statements] Block 2
to condition2, and in case elif <condition3> :
the condition2 is True, statement
[statements] Block 3
executes statements in
:
block2, so on. In case none :
of the given conditions is else :
true, then it executes the statement
statements under else block [statements]
Example of if-elif statement
• Prog to find discount (20%) if amount>3000, disc(10%) if
Amount <=3000 and >1000, otherwise (5%).
Price = float (input(“Enter Price ? ” ))
Qty = float (input(“Enter Qty ? ” ))
Amt = Price* Qty
print(“ Amount :” , Amt)
if Amt >3000 :
disc = Amt * .20 block 1
print(“Discount :”, disc) (will be executed incase condition 1 is true)
elif Amt>1000:
disc = Amt * .10 block 2
print(“Discount :”, disc) (will be executed incase condition2 is True)
else :
block 3
disc = Amt * .05
(will be executed incase both the
print(“Discount :”, disc)
condition1 &conditon2 are False)
Example of Nested if statement
• Prog to find Largest of Three Numbers (X,Y,Z)
X = int (input(“Enter Num1 ? ” ))
Y = int (input(“Enter Num2 ? ” ))
Z = int (input(“Enter Num3 ? ” ))

if X>Y:
if X > Z:
Largest = X
else:
Largest = Z
else:
if X > Z:
Largest = X
else:
Largest = Z
print(“Largest Number :”, Largest)
Assignments
• WAP to input a number and check whether it is Even or Odd.
• WAP to input a number print its Square if it is odd, otherwise print
its square root.
• WAP to input a Year and check whether it is a Leap year.
• WAP to input a number check whether it is Positive or Negative or
ZERO.
• WAP to input Percentage Marks of a students, and find the grade as
per following criterion:
Marks Grade
>=90 A
75-90 B
60-75 C
Below 60 D
LOOPS
• It is used when we want to execute a sequence of
statements (indented to the right of keyword for) a
fixed number of times.
• Syntax of for statement is as follows:
– i) with range() function
– ii) with sequence
The for Loop
Starting Ending Step
• Syntax 1: value value value

for <Var> in range (val1, val2, Val3):


Statements to be repeated

• Syntax 2: List or a String

for <Var> in <Sequence> :


Statements to repeat
The range() function
• range( 1 , n): 1) range( 1 , 7): will produce
will produce a list having 1, 2, 3, 4, 5, 6.
values starting from 1,2,3… 2) range( 1 , 9, 2): will produce
upto n-1. 1, 3, 5, 7.
The default step size is 1 3) range( 5, 1, -1): will produce
• range( 1 , n, 2): 5, 4, 3, 2.
will produce a list having 3) range(5): will produce
values starting from 1,3,5…
upto n-1. 0,1,2,3,4.
The step size is 2 default start value is 0
for loop implementation
Sum=0 Sum=0
for i in range(1, 11): For i in range(10, 1, -2):
print(i) print(i)
Sum=Sum + i Sum=Sum + i
print(“Sum of Series”, Sum) print(“Sum of Series”, Sum)
OUTPUT: OUTPUT:
1 10
2 8
: :
10 2
Sum of Series: 55 Sum of Series: 30
for loop: Prog check a number for PRIME
METHOD 1 METHOD 2: using loop else

num= int(input(“Enter Num?”)) num= int(input(“Enter Num?”))


flag=1 for i in range(2, num//2+1):
for i in range(2, num//2+1): if num%i == 0:
if num%i == 0: print(“It is Prime No.”)
flag = 0 break
break else:
if flag == 1: print(“It is Not a Prime No.”)
print(“It is Prime No.”)
else: Note: the else clause of a loop will be
print(“It is Not a Prime No.”) executed only when the loop
terminates normally (not when
break statement terminates the
loop)
Nested for Loop
for i in range ( 1, 6 ):
print( )
for j in range (1, i + 1):
print(“@”, end=“ ”)

Will produce following output


@
@@
@@@
@@@@
@@@@@
The while Loop
• It is a conditional loop, which repeats the statements with in itself as
long as condition is true.
• The general form of while loop is:
while <condition> :
Statement loop body
[Statements] (these statements repeated until
condition becomes false)
• Example: OUTPUT
k = 1, sum=0 1
while k <= 4 : 2
print (k) 3
sum=sum + k 4
print(“Sum of series:”, sum) Sum of series: 10
while loop: Implementation
• Prog. To find digit sum • Prog. To find reverse
num = int(input(“No.?”)) num = int(input(“No.?”))
ds = 0 rev = 0
while num>0 : while num>0 :
ds = ds +num % 10 d = num % 10
num = num // 10 rev = rev*10 + d
print(“Digit Sum :”, ds) num = num // 10
print(“Reverse :”, rev)
Strings: indexing
• A string can be traversed both sides (with help of
index):
• Examples: let t = “WelCome” then indexing will be as under:

Thus, t [ 2] will give “l” & t[-2] will give “m”


t [0] will give “W” & t[-1] will give “e”
Basic String Operators
a) String Concatenation Operator (+) b) String Replication Operator (*)
the + operator creates a new The '*' operator when used with
string by joining the operand String, then it creates a new
strings. string that is a number of
e.g. replications of the input string.
"Hello" + "Students" e.g.
will result into : "HelloStudents" "XY" * 3 will give: "XYXYXY"
"3" * 4 will give: "3333“
'11' + ‘22’ will give: ‘1122'
"a" + "5" will give : "a5" "5" * "7" is invalid
'123' + 'abc' will give: '123abc‘

"a" + 5 is invalid
• Note: both operands must be Note: operands must be one string
strings. & other Number
Membership Operators: (in & not in)

in : returns True if a character not in: returns True if a


or a substring exists in th character or a substring does
e given string, False not exists in the given string,
otherwise. False otherwise.

"a" in "Rajat" gives: True "a" not in "Rajat" gives: False


"Raj" in "Rajat" gives: True "Raj“ not in "Rajat" gives: False
"67" in "1234" gives: False "67" not in "1234" gives: True
ord() & chr() functions
ord() function: chr() function:
It gives ASCII value of a it is opposite of ord() fu
single character nction
ord ("a") : 97 chr(97) : “a"
ord ("Z") : 90 chr(90) : “Z"
ord("0") : 48 chr(48) : “0”
String Slice : part of a string containing some
contiguous characters from the string. Let word=“WelCome”

Then,
word [0:7] will give : WelCome
word [0:3] will give : Wel
word [2:5] will give : lCo (2,3,4)
word [-6:-3] will give : elC (-6,-5,-4)
word [ :5] will give : WelCo (0,1,2,3,4)
word [3: ] will give : Come (5,6,7,8)
STRING FUNCTIONS & METHODS:
1. string.capitalize():
it gives the copy of string with its first character
capitalized.
e.g. if t = "sumit rana” then R= t.capitalize()
will create a copy of string in R as,
R = "Sumit rana“
STRING FUNCTIONS & METHODS:
2. string.find(subString [,start [,end]):
it returns the lowest index in the string where the
subString is found with in the slice range of start &
end, returns -1 if subString not found.
e.g. t="We are learning Strings. Strings are used in Python"
k = "Strings"
t.find(k) gives : 16 (index no.)
t.find(k,20) gives : 25 (index no.)
t.find(k,20,30) will search from index 20 to 30
t.find(“Hello”) gives : -1 ( as string is not found)
STRING FUNCTIONS & METHODS:
3. string.isalnum(): it gives True, if the characters in the st
ring are alphanumeric (alphabet or number) and there
is atleast one character, False otherwise.
e.g. t ="Hello123” then t.isalnum() gives True
t ="Hello 123” then t.isalnum() gives False

4. string.isalpha(): it gives True if the characters in the


string are alphabet only and there is atleast one
character, False otherwise.
e.g. t ="Hello123” then t.isalnum() gives False
t = "Hello” then t.isalnum() gives True
STRING FUNCTIONS & METHODS:
5. string.isdigit(): it gives True if the characters in the strin
g are digits onlyand there should be atleast one charact
er, False otherwise.
e.g. t ="Hello123“ then t.isalnum() gives False
t= "123” then t.isalnum() gives True

6. string.islower(): this function gives True, if all letters in


given string are lowercase, otherwise it gives False.
e.g.: if t="sunday" then t.islower() gives True
if t="Sunday" then t.islower() gives False

7. string.isupper(): opposite of islower()


STRING FUNCTIONS & METHODS:
8. string.isspace(): it gives True if there are only
whitespace characters in the string, False otherwise.
e.g. if t=" " then t.isspace() gives True
if t=" S" then t.isspace() gives False
9. string.upper(): this function gives a copy of the string
converted to uppercase.
e.g.: if t="SUNday12" then
x=t.upper() will store "SUNDAY12" in x.
10. string.lower(): opposite of upper()
11. len(string): this function gives the length of given
string. e.g. Len(“Top Brand”) gives 9
for loop with string
e.g.1: e.g. 2:
for ch in “Hello” : T = “Hello”
print(ch) for ch in T :
print(ch)

Output: Output:
H H
e e
l l
l l
o o
for loop with string
e.g.1: e.g. 2:
T = “Hello” T = “Hello”
Len= len(T) Len= len(T)
for i in range(Len) : for i in range(0,Len) :
print(T[i]) print(T[i])

Output: Output:
H H
e e
l l
l l
o o

You might also like