Python if else
Python Conditional statements (If else)
1)if
Syntax :
if(condition) :
s1
This is used to execute the mentioned statement s1 if the given condition is true and skip the execution of statement when the condition is false.
Example:
x=int(input())
if(x>0):
print ("positive")
Here if the input is greater than zero it will be printed as positive otherwise no output will be shown.
2)else
Syntax :
else :
S1
Here S1 is the statement that is needed to be executed when if condition fails.
Example:
x=int(input ())
if(x>0):
print ("positive")
else:
print ("negative")
In this case all the other numbers which doesn't fall under if condition will be printed as negative.
3)elif(condition):
This is used in case of multiple conditions.
Example:
x=int(input ())
if(x>0):
print ("positive")
elif(x<0):
print ("negative")
else:
print ("zero")
Here elif is used when there is a need of providing multiple conditions.
Now let's see few examples for using these conditional statements.
Exercise
1)To find whether the given number is positive or negative.
Solution:
x=int(input("Enter number"))
if(x>0):
print ("Positive")
elif(x<0):
print ("Negative")
else:
print ("zero")
2)To find whether the given number is odd or even.
Solution:
x=int(input ("Enter number"))
if(x%2=0):
print ("Even")
else:
print ("Odd")
3) To find the greatest of three numbers
Solution:
a=int(input("Enter first number"))
b=int(input("Enter second number"))
c=int(input ("Enter third number"))
if(a>b)and(a>c):
print (a)
elif(b>a)and(b>c):
print(b)
else:
print (c)
4)To find whether the given number is divisible by 5 and 10
Solution:
n=int(input ("Enter number"))
if(n%10=0):
print (n,"is divisible by 5 and 10")
else:
print (n,"is not divisible by 5 and 10")
5)To print grade for the given total marks
Solution:
Mark=int(input ("Enter marks")
if(Mark>450):
print ("A")
elif(Mark>400):
print ("B")
elif(Mark>350):
print ("C")
elif(Mark>300):
print ("D")
else:
print ("Fail")
Comments
Post a Comment