Data Science · मराठी आवृत्ती · Python basics
P5.2 Python मध्ये if आणि else कसं लिहायचं?
हे का शिकायचं?
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: जोडा.
Python आणि इतर भाषा: तुलना
या भाषा शिकायची गरज नाही. Python किती सोपा वाचायला आहे ते दाखवण्यासाठी ही table आहे.
| भाषा | Code |
|---|---|
| Python | if x > 30: (then indented lines) |
| Java | if (x > 30) { ... } else { ... } |
| JavaScript | if (x > 30) { ... } else { ... } |
| Go | if 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 दिली आणि नंतर ती वापरली.