Python Interview Questions on Decision Making and Loops

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels. You can observe Python coding questions and answers, python programming interview questions and answers pdf, Python tricky interview questions, Python interview questions for 5 years experience, Tcs python interview questions, Python interview questions and answers, Python interview questions on loops, python decision making and loops, Python interview questions on decorators, Python interview questions machine learning, Python interview questions on dictionary, Python interview questions in deloitte, Python interview questions on algorithms and data structures.

Python Interview Questions on Decision Making and Loops

Control Statements

Control statements are used to control the flow of program execution. They help in deciding the next steps under specific conditions also allow repetitions of the program a certain number of times.
Two types of control statements are as follows:

1. Conditional branching

  • If
    Syntax:
    if (condition): to do statement
    If the condition evaluates to be true only then if code under if block will be executed.
  • if. . .else Syntax:
    if (condition): to do statement else:
    to do statement
  • Nested if statements Syntax:
    if (condition1):
    to dd statement elif(condition2):
    else do this
    elif(condition3):
    else do this

2. Loops

  • while: repeat a block of statements as long as a given condition is true
    Syntax:
    while(condition): ;
    to do statement
  • for: repeat a block of statements for a certain number of times
    , Syntax: ‘
    for < iterating_variable > in sequence:
    Repeat these steps
  • nested loops

Question 1.
What would be the output for the following piece of code?

animals = [ 'cat', 'dog'] .
for pet in animals: .
pet.upper( ) 
print(animals)

Answer:
The output will be [‘cat’, ‘dog’]. The value returned by a pet. upper( ) is not assigned to anything hence it does not update the value in any way.

Question 2.
What would be the output of the following code?

for i in range(len(animals)):
animals[i] = animals[i].upper( ) 
print(animals)

Answer:

[‘CAT’, ‘DOG’]

Question 3.
What would be the output of the following code?

numbers = [1,2,3,4] 
for i in numbers:
numbers.append(i + 1) 
print(numbers)

Answer:
This piece of code will not generate any output as the ‘for’ loop will never stop executing. In every iteration, one element is added to the end of the list and the list keeps growing in size.

Question 4.
What will be the output for the following code?

i = 6
while True:
if i%4 == 0:
break
print(i)
i -= 2

Answer:
6

Question 5.
Write a code to print the following pattern:
*
**
***
****
Answer:

for i in range(1,5):
print("*"*i)

Or

count = 1 
while count < 5:
print(*count) 
count = count + 1

Question 6.
Write code to produce the following pattern:
1
22
333
4444
Answer:
The code will be as follows:

count = 1 
while count < 5:
print(str(count)*count) 
count = count + 1

Question 7.
Write a code to generate the following pattern:
1
12
123
1234
Answer:
The code will be as follows:

count = 1 
string1 =' ' 
while count < 5:
for i in range(1, count+1):
string1 = string1+str(i)
count = count + 1 
print(string1) 
string1 =' '

Question 8.
Write code to spell a word entered by the user.
Answer:
The code will be as follows:

word = input ("Please enter a word : ") 
for i in word: 
print (i)

Output
Please enter a word: Aeroplane
A
e
r
0
P
l
a
n
e

Question 9.
Write code to reverse a string.
Answer:
The code:

string1 = "AeRoPlAnE" 
temp = list (string1) 
count = len(temp)-1 
reverse_str=' ' 
while count>=0:
reverse_str = reverse_str + temp[count] 
count = count-1 
print(reverse_str)

Output

EnAlPoReA

Statements to control a loop
The following three statements can be used to control a loop:

  1. break: breaks the execution of the loop and jumps to the next statement after the loop
  2. continue: takes the control back to the top of the loop without executing the remaining statements
  3. pass: does nothing

Question 10.
What will be the output for the following code?

a = 0
for i in range(5): 
a = a+1 
continue 
print(a)

Answer:
5

Question 11.
What would be the output for the following code?
Answer:
The code:

for item in ('a','b','c','d'): 
print (item) 
if item == 'c' : 
break 
continue
print ("challenge to reach here")

Question 12.
How would you use a “if ” statement to check whether an integer is even ?
Answer:
Code

x = int(input("enter number : ")) 
if x%2 == 0:
print("You have entered an even number")

Output

enter number: 6
You have entered an even number
>>>

Question 13.
How would you use an  “if ” statement to check whether an integer is odd?
Answer:
Code

x = int(input("enter number : ")) 
if x%2 != 0:
print("You have entered an odd number")

Output
enter number: 11
You have entered an odd number

Question 14.
Use an if-else statement to check if a given number is even if yes then display that a message stating that the given number is even else print that the given number is odd.
Answer:
Please have a look at the following code:
Code

x = int(input("enter number : ")) if x%2 == 0:
print("You have entered an even number") else:
print("You have entered an odd number")

Output

enter number: 11
You have entered an odd number
>>>
enter number: 4
You have entered an even number
>>>

Question 15.
What is a ternary operator?
Answer:
The ternary operator is a conditional expression used to compress the if.. .else block in one single line.

[to do if true] if [Expression] else [to do if false]

Code

X = 27
print("You have entered an even number") if x%2
== 0 else print("You have entered an odd number")

Output

You have entered an odd number

Question 16.
What would be the output of the following code? Why?
i = j = 10 if i > j:
print(“i is greater than j”) elif i<= j:
print(“i is smaller than j”) else:
print(“both i and j are equal”)
Answer:
The output of the above code will be:
i is smaller than j
i is equal to j.
So, the second condition elif i>j evaluates to true and so, the message printed in this block is displayed.

Question 17.
How can the following piece of code be expressed in one single line?
i = j = 10 if i > j :
print(“i is greater than j”)
elif i< j:
print(“i is smaller than j”)
else:
print(“both i and j are equal”)
Answer:
print (“i is greater than j” if i > j else “i is smaller than j” if i < j else “both i and j are equal”)

Question 18.
What will be the output for the following code?
i = 2 j = 16
minimum_val = i < j and i or j minimum_val
Answer:
2

Question 19.
What is the meaning of conditional branching?
Answer:
Deciding whether certain sets of instructions must be executed or not based on the value of an expression is called conditional branching.

Question 20.
What would be the output for the following code?
a = 0
b = 9
i = [True,False] [a > b]
print(i)
Answer:
The answer would be “True”. This is another ternary syntax: [value_if_false, value_if_true][testcondition]
In the above code a < b, therefore the test condition is false. Hence, ‘i’ will be assigned the value of value_if_false which in this case is set to “True”.

Question 21.
What is the difference between the continue and pass statement?
Answer:
pass does nothing whereas continue starts the next iteration of the loop.

Python Looping

Question 22.
What are the two major loop statements?
Answer:
for and while

Question 23.
Under what circumstances would you use a while statement rather than for?
Answer:
The while statement is used for simple repetitive looping and the for statement is used when one wishes to iterate through a list of items, such as database records, characters in a string, etc.

Question 24.
What happens if you put an else statement after a block?
Answer:
The code in the else block is executed after the for loop completes, unless a break is encountered in the for loop execution, in which case the else block is not executed.

Question 25.
Explain the use of break and continue in Python looping.
Answer:
The break statement stops the execution of the current loop, and transfers control to the next block. The continue statement ends the current block’s execution and jumps to the next iteration of the loop.

Question 26.
When would you use a continue statement in a for loop?
Answer:
When processing a particular item was complete; to move on to the next, without executing further processing in the block.
The continued statement says, “I’m done processing this item, move on to the next item.”

Question 27.
When would you use a break statement in a for loop?
Answer:
When the loop has served its purpose. As an example, after finding the item in a list searched for, there is no need to keep looping. The break statement says, “I’m done in this loop; move on to the next block of code.”

Question 28.
What is the structure of a for loop?
Answer:
for <item> in <sequence>:… The ellipsis represents a code block to be executed, once for each item in the sequence. Within the block, the item is available as the current item from the entire list.

Question 29.
What is the structure of a while loop?
Answer:
while <condition>:… The ellipsis represents a code block to be executed until the condition becomes false. The condition is an expression that is considered true unless it evaluates to 0, null or false.

Question 30.
Use a for loop and illustrate how you would define and print the characters in a string out, one per line.
Answer:
my String = “I Love Python”
for my Char in my String:
print myChar

Question 31.
even the string “I LoveQPython” uses a for loop and illustrates printing each character up to, but not including the Q.
Answer:
my String = “I Love Python”
for my car in my String:
if my car = ‘Q’:
break
print myChar

Question 32.
Given the string “I Love Python” print out each character except for the spaces, using a for a loop.
Answer:
my String = “I Love Python”
for myChar in my String:
if myChar — ‘ ‘ ,
continue print myChar

Question 33.
Illustrate how to execute a loop ten times.
Answer:
i = 1
while i < 10:
i+=1

Question 34.
When using a while loop, a condition was encountered that made staying in the loop pointless, what statement is used to transfer control?
Answer:
The break statement is used to terminate the processing of the loop and move on to the next block of code.

Question 35.
How is execution in the while loop block abandoned, but the loop itself is not exited?
Answer:
The continue statement is used to terminate the processing of the block and move control to the next iteration of the loop.

Question 36.
What is a looping use of the range( ) function?
Answer:
The range function is used to generate a sequence of numbers for iteration. For example range(5) returns the list [0,1, 2, 3, 4] This list could be used in a a loop.

Question 37.
Can the else clause be used after a while loop? When is it executed? ,
Answer:
Yes. The else block is executed after the while condition becomes false, but not if the while loop is exited with a break statement.

Question 38.
Illustrate how the range( ) and len( ) functions be used to iterate over the indices of a sequence?
Answer:
myltems = [T, ‘Love’, ‘Python’]
for i in rangeden(myltems)):
print i, myltems[i]

Question 39.
How is the body of a loop defined?
Answer:
The body of the loop is defined by indentation.

Question 40.
How are loops nested?
Answer:
Ever greater levels of indentation.

Question 41.
Illustrate a nested loop that uses the following list IT, ‘Love’, ‘Python’] and outputs each character on a separate line.
Answer:
myltems = [T, ‘Love’, ‘Python’]
for myWord in myltems:
for myChar in myWord:
print myChar