Python If-Else Interview Questions and Answers
1. In Python what's the main job of the if, elif and else statements? Can you explain it simply?
The statements if, elif and else are used for conditional operation in a Python program.
So reportedly, they're just like life itself, a program's way of making choices.
The if statement checks for a certain condition, if the condition returns as true, it will execute a certain block of code. If the condition does not return as true, it will check the next condition by elif, which stands for else if. You can have more than one elif to check other conditions.
Otherwise, the default execution will be by the else block if none of the if or elif conditions were true.
It will enable your code to make intelligent decisions and act differently based on situational contexts.
Example:
age = 20
if age < 13:
print("You are a child.")
elif age < 18:
print("You are a teenager.")
else:
print("You are an adult.")
Here's what happens in this example:
First, the program will test whether age is less than 13.
If it is not, it will check to see whether age is less than 18.
If neither of those is true, the else part will just run.
Thus, this is how you guide your program to select the proper action from the different values or inputs.
2. How do you write a basic if statement in Python? What are the key things you need to include?
For example, a very simple use of an if statement could test for the condition 'if True', if that condition held, Python would execute all the code in that block if not, it would just skip it.
The Basic Form of an if
If condition:
# Code to execute if condition is true
Important Things To Note:
The keyword if – This is what starts off the condition check.
A condition – A condition is any expression that yields either true or false.
A colon : – This is needed at the end of the if statement.
An indented code block – The part of the code which executes if the condition is true must be indented (4 spaces or 1 tab).
Example:
temperature = 30
if temperature > 25:
print("It's a hot day!")
In this given case:
At first, it checks if temperature > 25.
Then it prints "It's a hot day!" as 30 is greater than 25.
Nothing would have been printed had the condition been false.
This is the simplest form of the if statement in Python, which with elif and else can be expanded to suit the need.
3. What is the difference between using just if and using elif? When would you pick elif?
Unlike most programming languages, Python uses the condition aspects of the statement as follows:
if, elif and else. They are mainly considered to implement different parts of a code that may run depending on conditions. There is a slight distinction between using just an if clause or using elif institution with it.
Using Just if:
If you join more than one if statements, each statement is checked separately in Python.
Even if at least one of them is already true, multiple statements can run.
Example:
temperature = 30
if temperature > 20:
print("It's warm")
if temperature > 25:
print("It's hot")
Both statements here are true, and Python prints them both.
It's warm
It's hot
Using elif:
Else if is termed elif. When you want to check a different condition, but only if the first one is false. As soon as a condition is true, Python halts the process of checking the rest.
Example:
temperature = 30
if temperature > 35:
print("It's very hot")
elif temperature > 25:
print("It's hot")
Here the first condition is false; thus, Python will move to the elif and sees that it's true. It will print:
It's hot
Then it stops checking further.
So when do you use elif?
Applicable use cases for elif are:
Different possible outcomes, but only one of them should occur.
If you're looking to have Python ignore the others as soon as one is found.
Never intended to happen together.
Quick Summary:
Use if to check a condition.
Use another if when multiple conditions might all be true.
Use elif to check the next condition only if the first didn't pass.
It is a way to keeping your code neat and easy to read as well as making sure not to execute extra code you do not need.
4. What does the else part do in an if elif else setup? Do you always need to have one?
In Python, when you need to capture scenarios that do not met matching conditions of if or elif, you use the else part. In simpler terms, the code in else block only executes if all other conditions proved false.
This is like saying -
"If this is true, do that. Else if this other thing is true, do something else. But if none of these are true, then do this last thing.".
Use of else, always?
No, you don't.
The else part is an optional part, use it only when you want to take a default action when not one condition is met. If you don't want anything to happen when the conditions aren't matched, go ahead and skip the else entirely.
Example:
temperature = 5
if temperature > 30:
print("It's hot!")
elif temperature > 15:
print("It's warm.")
else:
print("It's cold.")
In this way:
If temperature is above 30 → then, it prints "It's hot!"
Whereas, if it's above 15 → print "It's warm."
If neither one of the statements above is true (as here, 5) → else would print "It's cold."
When should you use else?
When you want to cater for all the remaining cases not covered or you've handled it with if or elif.
When it helps to have the default one for the cases that are not already matched.
To make sure something always runs, no matter what.
In brief:
else catches anything that doesn't match your otherwise earlier conditions.
Not always necessary, but useful when you want to cover all the bases.
Becomes easier to read and complete in your code.
5. Is the way you indent your code under if, elif and else just for making it look nice or does it actually mean something in Python?
One more important thing to mention about indentation in Python is that it is a part of the syntax. it is never just for aesthetics. While most programming languages use curly braces for delineating areas of code, Python does grouping of statements on the basis of indentation.
Hence, indentation actually governs the execution of your code.
If indentation is incorrect, the Python interpreter will simply throw an error stating it cannot comprehend the code.
Therefore, indentation is necessary structurally and functionally.
An example can demonstrate this point. Consider a simple script checking temperature and printing a message accordingly.
temperature = 25
if temperature > 30:
# In this line, the indentation implies that it is part of the 'if' block.
print("It's hot!")
elif temperature > 20:
# This line represents 'elif' behavior, being less indented than the 'if'
print("It's warm.")
else:
print("It's cold.") # The line representing an 'else'
So here, the lines following if statements, elif statements and else statements are indented for Python to understand that these lines will only be executed when that specific condition is true. If they weren't indented, Python would be unable to know where that block of code ends, resulting in an error.
The importance of indentation comes from the fact that Python does not employ curly brackets {} like in some other languages, e.g., C, Java, or JavaScript.
Instead, the indentation level determines the scope or block of code. If the indentation is poor, then there will be an error from Python, like IndentationError as it does not know how to group the statements.
Take, for example, we forgot to indent that line after the if statement:
temperature = 10
if temperature > 30:
# This will cause an error because it's not indented correctly
print("It's hot!")
The execution of such a code will generate an error because Python cannot figure out which code belongs within the if block. Therefore, indentation lays out the structure, and without it, one cannot know what falls under the if statement in Python.
Summarizing the Above:
Indentation is important: It indicates to Python which statements are within which block (if, elif or else).
Standard indentation employs four spaces, but tabs are also an option (sticking to spaces for uniformity is almost dogma).
Incorrect indentation results in either an IndentationError or odd behavior in your program.
For the correct functioning of Python programs, it is important to indent properly. Think of indentation as a road map to show the steps of your program to Python. Otherwise, Python won’t know what lines from the code to run, which brings about error.
Hence, while writing Python scripts, keep checking your indentation!
6. How can you check if more than one thing is true in an if statement? Explain how the word and helps with this.
In an if statement in Python, to test for more than one condition to be true, use the logical operator and. When conditions are combined with the and operator, true is returned only when each of the conditions checked is true, when even one is false, the expression as a whole returns false.
Example:
Let us see the scenario of determining whether a person entering the club is more than 18 years of age and holding a valid ID by combining the two conditions using an and operator.
age = 20
has_id = true
if age ≥ 18 and has_id:
print("You can enter the club!")
else:
print("You cannot enter the club")
Explanation:
In an if clause, we check if both conditions are true:
Is he/she old enough (age ≥ 18)?
Does he/she have a valid ID (has_id)?
Here, the and operator between these conditions together implies that both have to pass for the if condition to fire (i.e. they can enter the club). If any of these two conditions fail, the else condition will fire (i.e.You cannot enter the club ).
More Detail:
Considered on its own with each condition present in that expression:
Both being true results in the expression returning a value of True, executing the code in the if-block.
Any false condition results in the expression returning a value of False, whereby the else block executes.
To summarize, and is the simplest operator to check multiple truths in an if statement since it demands that all conditions must be met before that block of code is executed.