If statement conditions check krne ke liye hota hai , agar condition true hai to hm us statement ko run krte hai jo ki if block mai likha rhta hai aur agar conditon false hai to hm else statement ko print karate hai.
Syntax:
if (condition): Body of if else: Body of else
# idhar hm colon use kr rhe hai if statement ke baad jo ki hme if statement ke execution ke baare batata hai
#Indentation ka khaas khyl rakhna hai
#Indentation kya hai - Indentation ek white spaces hai , jo ki ek statement ke baad diye jate hai ye batane ke liye ki baaki jo block of code hai wo is particular statement ko belong krta hai , baki programming language mai hm curly braces ka use krte hai yahi same chiz batane ke liye
jaisa ki ap upar syntax mai dekh skte hai hamne if statement ke baad uske block of code ko spaces ke andar likha hai, aayiye ise aur clear banate hai example ki madada se.
example:
-----------------------------------------------------------------------------------------------------------------------
var =10
if var < 0:
print("value is less than zero")
else:
print("value is more than zero")
output:
value is more than zero
#indentation or colon ko bhooliye ga nhi , nhi to error aa jayegi
------------------------------------------------------------------------------
If-elif-else Statement
Python mai switch statement nhi hota , if-elif -else statement python mai switch statement ka kaam krte hai, jaise hi koi bhi condition true milti hai use execute kr dete hai , aur fir statement se bahar aa jate hai.
Agar mai apko if - else statement aur if-elif-else statement ke bich difference bataunga to apko if-elif-else statement clear ho jayega , basically maan lo agar 100 if statement hai aur aur agar pahla if statement correct ho jata hai , lekin fir bhi if -else statement poore 100 statement check krega , lekin agar hm if-elif -else statement ka use kr rhe hai , aur pahla if statement correct hai to ye pahla statement execute krega aur baki ke statement ko check nhi krega , aur bahar aa jayega.
Syntax:
if test expression: Body of if elif test expression: Body of elif else: Body of else
Example:
--------------------------------------------------------------------------------------------
#Simple calculator using if-elif-else statement
a = input(("Enter a operator"))
b = int(input("Enter a first number"))
c = int(input("Enter a Second number"))
if a == '+':
print(b+c)
elif a == '-':
print(b-c)
elif a == '*':
print(b*c)
elif a == '/':
print(b/c)
else:
print("Sorry")
Output:
Enter a operator : + Enter a first number : 50 Enter a Second number : 25 75
# ' == ' ye equality operator kehlata hai , basically ye check krta hai ki right operand aur left operand equal hai ki nhi
-------------------------------------------------------------------------------------
Comments
Post a Comment