Ravindra Bagale · Data Scienceसर्व coursesया course चे lessonsशोधाEnglish

Data Science · मराठी आवृत्ती · Python basics

P5.2 Python मध्ये if आणि else कसं लिहायचं?

By Ravindra Bagale

हे का शिकायचं?

Condition खरी असेल तेव्हाच काही code चालवायचा असतो — उदा. मोठ्या order ला free delivery.

हे काय आहे?

if condition: नंतरचा indent केलेला code condition True असेल तेव्हा चालतो. else: खालचा code False असेल तेव्हा. Colon आणि 4 spaces indent विसरू नका.

कसं करायचं?

Step 1. if condition: लिहा.

Step 2. खालचा code 4 spaces आत लिहा.

Step 3. गरज असेल तर else: जोडा.

1. Check the condition2. True? → run the if block3. False? → run the else block4. Continue with the next line
वरून खाली वाचा: code पासून result पर्यंतचा प्रवास

Python आणि इतर भाषा: तुलना

या भाषा शिकायची गरज नाही. Python किती सोपा वाचायला आहे ते दाखवण्यासाठी ही table आहे.

भाषाCode
Pythonif x > 30: (then indented lines)
Javaif (x > 30) { ... } else { ... }
JavaScriptif (x > 30) { ... } else { ... }
Goif x > 30 { ... } else { ... }

उदाहरणं: copy करा आणि चालवा

उदाहरण A: एकच if

हा code चालवा:

balance = 75
if balance < 100:
    print("Low balance warning")

तुम्हाला दिसणारा output:

Low balance warning

याचा अर्थ: Condition True होती म्हणून आतला code चालला.

उदाहरण B: if सोबत else

हा code चालवा:

age = 15
if age >= 18:
    print("Adult ward")
else:
    print("Children's ward")

तुम्हाला दिसणारा output:

Children's ward

याचा अर्थ: Condition False झाली की else चा code चालतो. दोनपैकी एकच भाग चालतो.

उदाहरण C: निर्णयावरून value ठरवा

हा code चालवा:

minutes = 42
if minutes > 30:
    status = "Late"
else:
    status = "On time"
print(status)

तुम्हाला दिसणारा output:

Late

याचा अर्थ: if/else ने variable ला value दिली आणि नंतर ती वापरली.