Conditionals are an important part of any program as they allow you to make decisions based on certain scenarios and outcome of a particular block of code. Like all other programming languages, Python also has if… else statement blocks which evaluate expressions and execute subsequent depending on whether the condition is true or false.
The syntax of the conditionals in Python is fairly simple:
if xyz == 1: print(“True”) #any subsequent code goes in this indented body else: print(“False”) #any subsequent code goes in this indented body which will execute assuming condition is false.
The above block of code gives us an idea of how if… else statements generally work in Python. No matter how complex your program may be, there is a chance that you will be working with at least 1 if… else statement to evaluate certain scenarios and proceed with either Plan A or Plan B.
There is also another keyword called elif which stands for else, if. It can be used in conjunction with the above keywords to make the program even more versatile.
if xyz == 1: print(“True”) #any subsequent code goes in this indented body elif xyz >1: print(“In else if block”) else: print(“False”) #any subsequent code goes in this indented body which will execute assuming condition is false.
As you can see the program syntax is relatively simple. Now let us go over a few examples in which if… else statements are being used for better understanding.
Given below the code checks if a number is an Armstrong number or not. An Armstrong number or narcissistic number is one that is equal to the sum of the digits raised to the power of the base of the number.
Let us see how we can check through if… else statements.
num = 1000 while num<=9999: d= num//10000 d1 = num%10000//1000 d2 = num%1000//100 d3 = num%100//10 d4 = num%10 num2 = d1**4+d2**4+d3**4+d4**4+d**4 if num == num2: print(num, "Armstrong number") num=num+1
The above code prints all Armstrong numbers between 1000 and 9999. It firsts separates the digits and the calculates the sum raised to the power of 4, individually for all digits and verifies via if… else statements whether the new number is equal to the original number.
Likewise, we can also have nested conditions in Python for added scenarios and more verification. The example below takes two inputs of light and temperature and predicts whether the camera will be on or off based on nested conditionals and use of elif.
oplg = 0.01 optemp = 0 opl = float(input("Enter light level:")) opt= float(input("Enter temperature level:")) if opl<oplg: if opt>optemp: print("Camera is off") elif opt<optemp: print("Camera is on") elif opl>oplg: if opt>optemp: print("Camera is on") elif opt<optemp: print("Camera is off")
With those 2 examples in mind, you can easily use if.. else in your own Python programs for any sort of decision making. Remember to keep in mind the indented block of code because that is what will separate different conditions and their resulting code blocks.