Python If...Else

  • Python uses boolean logic to evaluate conditions.
  • The boolean values True and False are returned when an expression is evaluated.
  • Use conditions to solve different problems.

Prerequisites

  • Python operators knowledge is required to understand python if..else conditions.
  • We use operators with if...else statements to take the programmatic decisions.

conditions syntax

  • if...else syntax
  • use it if we have only two possible conditions
if <condition>:
   <statement>
else:
   <statement>
  • if...elif...else syntax
  • use it when we have 3 or more possible conditions
if <condition>:
   <statement>
elif <condition>:
   <statement>
# add more elif we have more conditions
else:
   <statement>
  • let's use python conditions to solve the problems

Note: if alone can be use used without elif or else. elif and else are optional conditions. so, use these only when needed.

student exam result

  • let's write a program to find if student passed in the exam or not.
  • Student will fail in the exam if he/she gets less than 50 marks.
student_marks = 60
pass_marks = 50

if student_marks >= pass_marks:
   print("Hurray")
else:
   print("Meh")
# Output: Hurray
  • try out the above code by changing the values for student_marks

find max of two numbers

  • let's write the program to find the largest of given two numbers num1 = 10 and num2 = 20
num1 = 10
num2 = 20

if num1 > num2:
   print(f"max = {num1}")
elif num2 > num1:
   print(f"max = {num2}")
else:
   print(f"both are equal")
# output: max = 20
  • Try out the above code by changing the values of num1 and num2

find max of three numbers

  • let's write the program to find the largest of given two numbers num1 = 10, num2 = 20 and num3 = 30
num1 = 10
num2 = 20
num3 = 30

if num1 >= num2 and num1 >= num3:
   print(f"max = {num1}")
elif num2 >= num1 and num2 >= num3:
   print(f"max = {num2}")
else:
   print(f"max = {num3}")

# output: max = 30

welcome adulthood - nested conditions

  • write a program to check if person is adult and if adult then print welcome message.
  • Check if the person is graduated then say "congrats"
  • if the person has license then say "happy driving"
age = 19
isGraduated = False
hasLicense = True

# Look if person is 18 years or older
if age >= 18:
   print("You're 18 or older. Welcome to adulthood!")

   if isGraduated:
      print('Congratulations with your graduation!')
   if hasLicense:
      print('Happy driving!')

summary

  • We solved few problems by using the concepts learned so far.
  • We can solve more problems by using the python conditions.
  • We can use nested if...else conditions.

TODO: You will need to find out problems and solve it using python conditions.

References