Galle, LK--:--5/6 sites live

If else statement in Python

අන්තිමට model එකකට decision එකක් ගන්න වෙනවා — "probability 0.5ට වැඩිනම්, yes කියලා predict කරන්න." ඒ decision එකේ core එකේ තියෙන්නෙ if/else statement එකක්.

Every model eventually makes a decision — "if probability > 0.5, predict yes." That decision, at its core, is an if/else statement.

3 May 20263 min readSelf Guide · Stage 13#Python & Data Basics#Python Fundamentals#Machine learning

Lesson 6 of 64 · Part 1 · Python & Data Basics · Python Fundamentals · bilingual notes (English + සිංහල)

Why this matters. Every model eventually makes a decision — "if probability > 0.5, predict yes." That decision, at its core, is an if/else statement.

සිංහලෙන්: අන්තිමට model එකකට decision එකක් ගන්න වෙනවා — "probability 0.5ට වැඩිනම්, yes කියලා predict කරන්න." ඒ decision එකේ core එකේ තියෙන්නෙ if/else statement එකක්.

What you'll use this for. You'll use this to clean messy data ("if value is missing, fill it with the average") before you ever train a model.

සිංහලෙන්: Model එකක් train කරන්නත් කලින්, අපිරිසිදු data clean කරන්න මේක පාවිච්චි කරනවා ("value එක නැත්නම්, average එකෙන් පුරවන්න").

Key principles

  • Only one branch ever runs. Python checks conditions top to bottom and stops at the first True — later elif blocks are simply skipped.
    එකම ශාඛාවක් විතරයි කවදාවත් run වෙන්නෙ

Walkthrough

simple if else statement

ExamplePython
a = 30
b = 50

if (a>b):
  print('a is the greatest number')
else:
  print('b is the greatest number')

Output

Output
b is the greatest number
ExamplePython
a = int(input('Enter the first number : '))
b = int(input('Enter the second number : '))

if (a>b):
  print('First number is the greatest')
else:
  print('Second number is the greatest')

Output

Output
Enter the first number : 16
Enter the second number : 20
Second number is the greatest

if elif else statement

ExamplePython
a = 15
b = 25
c = 30

if (b<a>c):
  print('a is the greatest number')
elif (a<b>c):
  print('b is the greatest number')
else:
  print('c is the greatest number')

Output

Output
c is the greatest number

nested if statement

ExamplePython
a = 20
b = 40
c = 60

if (a>b):
  if (a>c):
    print('a is the greatest number')
  else:
    print('c is the greatest number')
else:
  if (b>c):
    print('b is the greatest number')
  else:
    print('c is the greatest number')

Output

Output
c is the greatest number

Keep going: ← Lesson 5 · Lesson 7 → · Track it in the Self Guide