Conditional & For Loop
Conditional & For Loop
Control statements are used to control the flow of execution of program. The control is executed
in three ways.
1. Sequential
2. Selection/Condition
3. Iteration
if statement
Simple if
Syntax:
if <condition>:
statement-1 STATEMENT-2
statement-3
if True: print("Hello")
print("Continue")
if True:
Indent is a space
In python block is defined by changing indent.
A block cannot defined without any statements. pass
Pass is a null operation — when it is executed, nothing happens. It is useful as a placeholder when
a statement is required syntactically, but no code needs to be executed.
if True: pass
if True:
print("Continue")
if <condition>: pass
xxxxxxx
yyyyyyyy
zzzzzzzz
pass pass
if ..else
Syntax:
if condition:
statement-1
STATEMENT-2
else:
statement-3
statement-4
statement-5
if ..else
Syntax:
if condition:
statement-1
statement-2
else:
statement-3
statement-4
statement-5
if num%2==0:
print(num,"is even")
else:
print(num,"is odd")
# write a program to read name and age of person and find elg to
vote
name=input("Enter name")
age=int(input("Enter age"))
if age>=18:
print(name,"elg to vote")
else:
Syntax:
if <codition1>:
statement-1
statement-2
elif <condition2>:
statement-3
statement-4
elif <condition3>:
statement-5
statement-6
else:
statement-7
statement-8
if num>0:
print(num,"is +ve")
elif num<0:
print(num,"is -ve")
else:
print("zero")
ord(),chr()
========
ord(c)
>>> ord('A')
65
>>> ord('B')
66
>>> ord('a')
97
>>> ord('z')
122
>>> ord('0')
48
>>> ord('9')
57
chr(i)
>>> chr(97)
'a'
>>> chr(65)
'A'
>>> chr(48)
'0'
>>> chr(57)
'9'
print(ch,"is in uppercase")
print(ch,"is in lowercase")
else:
print(ch)
else:
ASCII Chart
A 65 a 97
B 66 b 98
C 67
D 68
E 69
….
Z 90
x=ord(ch)
x=x+32
print(chr(x))
x=ord(ch)
x=x-32
print(chr(x))
else:
if <condition1>:
if <condition2>:
statement-1
else:
statement-2
else
statement-3
statement-4
# login application
user=input("UserName")
pwd=input("Password")
if user=="nit":
if pwd=="nit123":
print("welcome to my application")
else:
print("invalid password")
else:
print("invalid username")
# banking application
accno=int(input("Enter Accno"))
bal=float(input("Enter Balance"))
if ttype=="withdraw":
if tamt<bal:
bal=bal-tamt
print("Transaction Completed")
else:
print("Insuff balance")
elif ttype=="deposit":
bal=bal+tamt
print("Transaction Completed")
else:
print("Account ",accno)
print("Balance ",bal)
if num1>num3:
print(num1,"is max")
else:
print(num3,"is max")
elif num2>num3:
print(num2,"is max")
else:
print(num3,"is max")
whie loop
Syntax:
while <condition>:
statement-1
statement-2
statement-3
Statement-1 and statement-2 are executed until given condition is
True. If condition is false it execute statement-3.
5x1=5
5x2=10
5x3=15
5x4=20
….
5x10=50
i=1
while i<=10:
p=num*i
print(num,"x",i,"=",p)
i+=1
# 4!=4x3x2x1=24
# 0!=1
fact=1
while num>=1:
fact=fact*num
num=num-1
print("Factorial is ",fact)
# write a program to find input number is prime or not
# num=5
# 1 2
i=1
c=0
while i<=num:
if num%i==0:
c=c+1
i=i+1
if c==2:
print(num,"is prime")
else:
count=0
num=abs(num)
while num!=0:
num=num//10
count=count+1
print(count)
n=int(input("enter n value"))
num=0
while num<n:
print(num**2)
num=num+1
s=0
while num>0:
r=num%10
s=s+r
num=num//10
The for statement is used to iterate over the elements of a sequence (such as
a string, tuple or list) or other iterable object:
Syntax:
for loop each time read one element/item from sequence or iterable and
execute statement-1,statement-2. This repeating is done until all the
elements read from sequence/iterable. After reading all the elements it
execute statement-3.
# write a program to count number of vowels in a given string
c=0
if ch in "aeiouAEIOU":
c=c+1
acount=0
dcount=0
scount=0
acount+=1
dcount+=1
else:
scount+=1
print("Alphabet count",acount)
str2=""
x=ord(ch)
x=x-32
str2=str2+chr(x)
else:
str2=str2+ch
print(str1)
print(str2)
str2=""
for ch in str1:
x=ord(ch)+32
str2=str2+chr(x)
else:
str2=str2+ch
print(str1)
print(str2)
range
class range(stop)
class range(start, stop[, step])
The arguments to the range constructor must be integers (either built-in int
or any object that implements the __index__ special method). If the step
argument is omitted, it defaults to 1. If the start argument is omitted, it
defaults to 0. If step is zero, ValueError is raised.
For a positive step, the contents of a range r are determined by the formula
r[i] = start + step*i where i >= 0 and r[i] < stop.
For a negative step, the contents of the range are still determined by the
formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.
range
class range(stop)
class range(start, stop[, step])
The arguments to the range constructor must be integers (either built-in int
or any object that implements the __index__ special method). If the step
argument is omitted, it defaults to 1. If the start argument is omitted, it
defaults to 0. If step is zero, ValueError is raised.
For a positive step, the contents of a range r are determined by the formula
r[i] = start + step*i where i >= 0 and r[i] < stop.
For a negative step, the contents of the range are still determined by the
formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.
range(5) stop=5,start=0,step=1 0 1 2 3 4
r=range(5)
for value in r: # 0 1 2 3 4
print(value,end=' ')
print()
print(value,end=' ')
print()
print(value,end=' ')
r1=range(1,10) # start=1,stop=10,step=1
print(value,end=' ')
print()
r2=range(1,10,2) # start=1,stop=10,step=2
print(value,end=' ')
print()
print(value,end=' ')
print()
print(value,end=' ')
print()
print()
print(value)
print(value,end=' ')
print(value,end=' ')
print()
print()
print(value,end=' ')
for value in r:
print(value)
r2=range(97,123)
for x in r1:
print(chr(x),end=' ')
print()
for x in r2:
print(chr(x),end=' ')
for n in range(ord('A'),ord('Z')):
print(n)
for i in range(1,11):
print(num,"*",i,"=",num*i)
# Write a program to find input number is prime or not
num=int(input("Enter number")) # 5
c=0
for i in range(1,num+1): # 1 2 3 4 5
c=c+1
if c==2:
print(num,"is prime")
else:
For loop is used to read elements/items from a sequence and execute block
of statements.
#a b
# 0 1 1 2 3 5 8 ...n
# a b a+bc
a=0
b=1
print(a,b,end=' ')
for i in range(2,n+1):
c=a+b
print(c,end=' ')
a,b=b,c
Nested Loops
Syntax
num=2
while num<=n:
i=1
c=0
while i<=num:
if num%i==0:
c=c+1
i=i+1
if c==2:
print(num)
num=num+1
Printing Pyramid Stars
i=1
while i<=n:
k=0
j=1
while j<=n-i:
j=j+1
while k!=2*i-1:
print("*",end=" ")
k=k+1
print()
i=i+1
i=n
while i>=1:
k=0
j=1
while j<=n-i:
j=j+1
while k!=2*i-1:
print("*",end=" ")
k=k+1
print()
i=i-1
Break
Continue
c=0
if num%2==0:
print(num)
c=c+1
if c==10:
break
c=0
# write a program to print first 10 odd numbers from 1 to 50
if num%2!=0:
print(num)
c=c+1
if c==10:
break
num=2
pcount=0
while num<=100:
i=1
c=0
while i<=num:
if num%i==0:
c=c+1
i=i+1
if c==2:
print(num,end=' ')
pcount=pcount+1
if pcount==10:
break
num=num+1
continue
for i in range(1,11): # 1 2 3 4 5 6 7 8 9 10
if i%2==0:
continue
print(i,end=' ')
after continue if any statement is given that statement is not executed.
Python allows to write for and while loop statement with else.
This else is executed after execution of while and for loop.
This else is not executed if the loop is terminated using break
statement.
fact=1
while num>0:
fact=fact*num
num=num-1
else:
print(fact)
for i in range(1,11):
print(i)
else:
print("else block")
# write a program to print sum of first 10 even number from 1 to
n
esum=0
c=0
if num%2==0:
print(num,end=' ')
esum=esum+num
c=c+1
if c==10:
break
else:
if c==10:
print(esum)
formatting strings
Syntax:
%d decimal integer
%o octal integer
%x hexadecimal integer
%b binary integer
%f float in fixed format
%e float in expo format
%s string
Example:
n1=10
n2=20
print("%d,%d"%(n1,n2))
print("%d %d %d %d %d %d"%(10,20,30,40,50,60))
print("%d %d %d %d %d "%(10,20,10+20,10-20,10*20))
Write a program to print first 10 prime numbers from 1 to 100
num=2
pcount=0
while num<=100:
i=1
c=0
while i<=num:
if num%i==0:
c=c+1
i=i+1
if c==2:
print(num,end=' ')
pcount=pcount+1
if pcount==10:
break
num=num+1
continue
for i in range(1,11): # 1 2 3 4 5 6 7 8 9 10
if i%2==0:
continue
print(i,end=' ')
after continue if any statement is given that statement is not executed.
Python allows to write for and while loop statement with else.
This else is executed after execution of while and for loop.
This else is not executed if the loop is terminated using break
statement.
fact=1
while num>0:
fact=fact*num
num=num-1
else:
print(fact)
for i in range(1,11):
print(i)
else:
print("else block")
# write a program to print sum of first 10 even number from 1 to
n
esum=0
c=0
if num%2==0:
print(num,end=' ')
esum=esum+num
c=c+1
if c==10:
break
else:
if c==10:
print(esum)
formatting strings
Syntax:
%d decimal integer
%o octal integer
%x hexadecimal integer
%b binary integer
%f float in fixed format
%e float in expo format
%s string
Example:
n1=10
n2=20
print("%d,%d"%(n1,n2))
print("%d %d %d %d %d %d"%(10,20,30,40,50,60))
print("%d %d %d %d %d "%(10,20,10+20,10-20,10*20))
x=65
print("x=%d,x=%o,x=%x"%(x,x,x))
# input:
# output:
base=float(input("enter base"))
height=float(input("enter height"))
area=0.5*base*height
# input:
# 100 200
#output:
x,y=s.split(" ")
n1=int(x)
n2=int(y)
“string”.format(list of values)
# each replacement field is identified with index or name
x=10
y=20
#0 1 2
output:
sum of 10 and 20 is 30
sum of 20 and 10 is 30
30 is sum of 10 and 20
10 and 20 is 30
10 and 20 is 30
Syntax of format is
{fieldname/index:formatspecifier}
Fill,align,sign,width,groupting-options,type
Type:
Type Meaning
'b' Binary format. Outputs the number in base 2.
Character. Converts the integer to the corresponding unicode
'c'
character before printing.
'd' Decimal Integer. Outputs the number in base 10.
'o' Octal format. Outputs the number in base 8.
Hex format. Outputs the number in base 16, using lower-case letters
'x'
for the digits above 9.
Hex format. Outputs the number in base 16, using upper-case letters
'X'
for the digits above 9.
Number. This is the same as 'd', except that it uses the current locale
'n'
setting to insert the appropriate number separator characters.
x=65
print("{:d},{:o},{:x},{:b},{:n}".format(x,x,x,x,x))
p=1234567
print("{:d}".format(p))
print("{:n}".format(p))
n1=10
n2=100
n3=1000
n4=10000
print("{:6d}".format(n1))
print("{:6d}".format(n2))
print("{:6d}".format(n3))
print("{:6d}".format(n4))
The meaning of the various alignment options is as follows:
Option Meaning
Forces the field to be left-aligned within the available space (this is
'<'
the default for most objects).
Forces the field to be right-aligned within the available space (this
'>'
is the default for numbers).
'^' Forces the field to be centered within the available space.
n1=65
n2=456
n3=6578
n4=78956
print("{:6d}\n{:6d}\n{:6d}\n{:6d}".format(n1,n2,n3,n4))
print("{:<6d}{:<6d}{:<6d}{:<6d}".format(n1,n2,n3,n4))
print("{:^6d}\n{:^6d}\n{:^6d}\n{:^6d}".format(n1,n2,n3,n4))
The sign option is only valid for number types, and can be one of the
following:
Option Meaning
indicates that a sign should be used for both positive as well as
'+'
negative numbers.
indicates that a sign should be used only for negative numbers
'-'
(this is the default behavior).
indicates that a leading space should be used on positive numbers,
space
and a minus sign on negative numbers
a=+65
b=-85
print("{:+d}".format(a)) # +65
print("{:+d}".format(b)) # -85
print("{:-d}".format(a)) #65
print("{:-d}".format(b)) # -85
print("{: d}".format(a)) # 65
The available presentation types for floating point and decimal values are:
Type Meaning
Exponent notation. Prints the number in scientific notation using the
'e'
letter ‘e’ to indicate the exponent. The default precision is 6.
Exponent notation. Same as 'e' except it uses an upper case ‘E’ as the
'E'
separator character.
Fixed-point notation. Displays the number as a fixed-point number.
'f'
The default precision is 6.
Fixed-point notation. Same as 'f', but converts nan to NAN and inf to
'F'
INF.
a=1.567
print(a)
b=1567e-2
print(b)
print("{:f}".format(a))
print("{:e}".format(b))
n1=1.45
n2=12.2
n3=145.789
n4=1567.4568
print("{:10.2f}".format(n1))
print("{:10.2f}".format(n2))
print("{:10.2f}".format(n3))
print("{:10.2f}".format(n4))
Type Meaning
's' String format. This is the default type for strings and may be omitted.
name1="rajesh"
name2="kishore"
name3="james"
print("{:10s}".format(name1))
print("{:10s}".format(name2))
print("{:10s}".format(name3))
print("{:>10s}".format(name1))
print("{:>10s}".format(name2))
print("{:>10s}".format(name3))
print("{:^10s}".format(name1))
print("{:^10s}".format(name2))
print("{:^10s}".format(name3))
name1="rajesh"
name2="kishore"
name3="james"
print("{:*<10s}".format(name1))
print("{:*<10s}".format(name2))
print("{:*<10s}".format(name3))
print("{:*>10s}".format(name1))
print("{:*>10s}".format(name2))
print("{:*>10s}".format(name3))
print("{:*^10s}".format(name1))
print("{:*^10s}".format(name2))
print("{:*^10s}".format(name3))
f-string
a=10
b=20
c=30
print(f'{a},{b},{c}')
x=1.5
y=1.25
print(f'{x},{y}')
print(f'{x:5.2f},{y:5.2f}')