Python me If-Else kya hota hai?


Real life me hum hamesha conditions ke hisaab se decisions lete hain — "Agar baarish ho rahi hai toh chhaata lo, warna mat lo." Python me bhi exactly yahi hota hai. if-else ka use karke hum program ko batate hain ki kaunsi condition True hone par kya karna hai.

Python me 4 tarike hain conditions likhne ke :-

Note :- Python me indentation (spaces) bahut zaroori hai. if ke andar ka code 4 spaces ya 1 Tab se andar likhna padta hai — warna error aayega.



1. if Statement

Sabse simple condition. Agar condition True hai toh andar wala code chalega, False hai toh kuch nahi hoga.

Syntax
if condition:
    # yeh code tabhi chalega jab condition True ho

Example 1: Simple if — age check karna

Python
In [1]:
1
Output

Example 2: if — number positive hai ya nahi

Python
In [1]:
1
Output


2. if-else Statement

Jab condition True ho toh if wala block chalega, aur jab condition False ho toh else wala block chalega. Dono me se hamesha ek hi chalega.

Syntax
if condition:
    # True hone par yeh chalega
else:
    # False hone par yeh chalega

Example 1: Pass / Fail check karna

Python
In [1]:
1
Output

Example 2: Even ya Odd number check karna

Python
In [1]:
1
Output

Example 3: Do numbers me se bada kaun sa hai

Python
In [1]:
1
Output


3. if-elif-else Statement

Jab 2 se zyada conditions check karni hon toh elif use karte hain. Python upar se neeche ek ek condition check karta hai aur jo pehle True ho us block ko chalata hai, baki sab skip ho jaate hain.

Syntax
if condition1:
    # condition1 True hone par
elif condition2:
    # condition2 True hone par
elif condition3:
    # condition3 True hone par
else:
    # koi bhi condition True na ho toh

Example 1: Grade system — marks ke hisaab se grade dena

Python
In [1]:
1
Output

Example 2: Number positive, negative ya zero hai?

Python
In [1]:
1
Output

Example 3: Weekday ya Weekend check karna

Python
In [1]:
1
Output


4. Nested if Statement

Jab ek if ke andar doosra if likha ho usse Nested if kehte hain. Iska use tab hota hai jab ek condition ke saath aur ek condition bhi check karni ho.

Example 1: Login check — username aur password dono sahi hone chahiye

Python
In [1]:
1
Output

Example 2: Teen numbers me sabse bada kaun sa hai

Python
In [1]:
1
Output


5. Shorthand if-else (Ternary Operator)

Agar condition aur result simple ho toh ek hi line me if-else likh sakte hain. Isse Ternary Operator ya Shorthand if-else kehte hain.

Syntax
value = "True wala" if condition else "False wala"

Example 1: Adult ya Minor — ek line me check

Python
In [1]:
1
Output

Example 2: Max of two numbers — shorthand se

Python
In [1]:
1
Output



Quick Summary — if-else ek nazar me

TypeUse Kab KaroExample
ifSirf ek condition check karni hoif age >= 18:
if-elseDo raste — True ya Falseif pass: ... else: ...
if-elif-else2 se zyada conditionsGrades, menus, etc.
Nested ifCondition ke andar conditionLogin check, etc.
ShorthandSimple ek-line conditionx = "A" if n>90 else "B"