Link to the previous post: https://statinfer.com/104-1-3-python-objects/
In this post we will go through some commonly used conditional operations.
- if-then-else statement
- for loop
- break in for loop
If-Then-Else statement
If Condition
In [100]:
age=60
if age<50:
print("Group1")
print("Done with If")
If-else statement
In [101]:
age=60
if age<50:
print("Group1")
else:
print("Group2")
print("Done with If else")
Multiple else conditions in if
In [102]:
marks=75
if(marks<30):
print("fail")
elif(marks<60):
print("Second Class")
elif(marks<80):
print("First Class")
elif(marks<100):
print("Distinction")
else:
print("Error in Marks")
In [103]:
marks=20
if(marks<30):
print("fail")
elif(marks<60):
print("Second Class")
elif(marks<80):
print("First Class")
elif(marks<100):
print("Distinction")
else:
print("Error in Marks")
Nested if
In [104]:
x=45
if(x<50):
print("Number is less than 50")
if(x<40):
print ("Number is less than 40")
if(x<30):
print("Number is less than 30")
else:
print("Number is greater than 30")
else:
print("Number is greater than 40")
else:
print("Number is greater than 50")
In [105]:
x=35
if(x<50):
print("Number is less than 50")
if(x<40):
print ("Number is less than 40")
if(x<30):
print("Number is less than 30")
else:
print("Number is greater than 30")
else:
print("Number is greater than 40")
else:
print("Number is greater than 50")
For loop
Example-1
In [107]:
my_num=1
for i in range(1,20):
my_num=my_num+1
print("my num value is", my_num)
i=i+1
Example-2
In [108]:
sumx = 0
x=1
for x in range(1,20):
sumx = sumx + x
print(sumx)
Break Statement in for loop
- To stop execution of a loop
- Stopping the loop in midway using a condition
In [110]:
sumx = 0
x=1
for x in range(1,200):
sumx = sumx + x
if(sumx>500):
break
print(sumx)
The next post is about Python Packages.
Link to the next post :https://statinfer.com/104-1-5-python-packages/