4 Decision Making
4 Decision Making
If Else Statement
• Sequence: executes one statement after the
other from beginning to the end of the
program.
• decision making or selection is implemented
with the help of if..else statements
• The order of execution of the statements in a
program is known as flow of control.
What if we want to get a positive value as an output
irrespective of the values entered for num1 and num2?
•If the condition is true, then the indented statement gets
executed.
•The indented statement implies that its execution is
dependent on the header.
•There is no limit on the number of statements that can
appear under an if block.
Many a times there are situations that require multiple
conditions to be checked and hence may lead to many
alternatives. In such case we can chain the conditions using
if...elif.
•else is optional
•Number of elif is dependent on the number of conditions
•If the first condition is false, the next is checked, and so on. If one of the
condition is true, the corresponding statement(s) executes, and the block
ends.
In most of the programming languages, all the statements inside a block are
put inside curly brackets.
The interpreter checks indentation levels very strictly and throws up syntax
errors if indentation is not correct.
a=5
b=6
if a > b :
print ("a is larger") # Block1
print ("Bye")
else:
print ("b is larger") # Block2
print ("Bye Bye")
Output
b is larger
Bye Bye
Let us write a program to create a four function calculator with the
following requirements:
•displays a message "Please enter a value other than 0" if the user
enters the second number as 0.
Take as input the Total Taxable Income of the employee and display
the tax payable by the employee.
• A number is even if it is perfectly divisible by 2. When the number is
divided by 2, we use the remainder operator % to compute the
remainder. If the remainder is not zero, the number is odd.
Output
Enter a number: 43
43 is Odd
• A leap year is exactly divisible by 4 except for century years (years ending
with 00).
• The century year is a leap year only if it is perfectly divisible by 400. For
example,
❑ 2017 is not a leap year
❑ 1900 is a not leap year
❑ 2012 is a leap year
❑ 2000 is a leap year
# Python program to check if the input year is a leap year or not
year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print(year, ”is a leap year“)
else:
print(year, ”is not a leap year“)
else:
print(year, ”is a leap year“)
else:
print(year, ”is not a leap year“)
Output
2000 is a leap year