Python conditional statements MCQ: Set 1

Python conditional statements MCQ

1). What is the purpose of an if statement in Python?

a) To check if a condition is True or False
b) To perform a loop
c) To define a function
d) To import a module

Correct answer is: a) To check if a condition is True or False
Explanation: The if statement allows you to execute a block of code only if a specific condition is met.

2). Identify the correct syntax for an if statement?

a) if condition:
b) if condition then:
c) if (condition)
d) if (condition) then

Correct answer is: a) if condition:
Explanation: The correct syntax for an if statement in Python is “if condition:”

3). What is the purpose of the elif statement?

a) To check another condition if the if condition is False
b) To end the execution of the program
c) To execute a block of code repeatedly
d) To define a variable

Correct answer is: a) To check another condition if the if condition is False
Explanation: The elif statement allows you to check an additional condition if the if condition is False.

4). Which keyword is used to denote the else statement in Python?

a) otherwise
b) ifnot
c) else
d) elseif

Correct answer is:c) else
Explanation: The else keyword is used to denote the else statement in Python.

5). What is the purpose of the else statement?

a) To define a variable
b) To end the execution of the program
c) To execute a block of code if all previous conditions are False
d) To import a module

Correct answer is:c) To execute a block of code if all previous conditions are False
Explanation: The else statement allows you to execute a block of code if none of the previous conditions are True.

6). Which of the following is the correct syntax for an if-else statement?

a) if condition: else:
b) if (condition) else:
c) if condition: else
d) if (condition): else:

Correct answer is:a) if condition: else:
Explanation: The correct syntax for an if-else statement in Python is “if condition: else:”

7). What is the output of the following code?

				
					
   x = 5
   if x > 10:
       print("A")
   elif x > 7:
       print("B")
   elif x > 3:
       print("C")
   else:
       print("D")
				
			

Correct answer is:c) C
Explanation: The condition x > 3 is True, so the output will be “C”.

8). What happens if there are multiple elif statements and more than one condition is True?

a) Only the first True condition is executed
b) All True conditions are executed
c) None of the True conditions are executed
d) An error is raised

Correct answer is:a) Only the first True condition is executed
Explanation: Once a True condition is found, the corresponding block of code is executed, and the rest of the conditions are skipped.

9). Which of the following is the correct way to nest if statements in Python?

a) if condition1: if condition2:
b) if condition1: elif condition2:
c) if condition1: else: if condition2:
d) if condition1: if condition2: else:

Correct answer is:a) if condition1: if condition2:
Explanation: You can nest if statements by placing one if statement inside another if statement.

10). What is the output of the following code?

				
					    x = 10
    if x > 5:
        print("A")
    if x > 7:
        print("B")
    if x > 15:
        print("C")
    else:
        print("D")
				
			

a) A B C D
b) A B D
c) A D
d) B D
Correct answer is:b) A B D
Explanation: The conditions x > 5 and x > 7 are True, so “A” and “B” will be printed. The condition x > 15 is False, so “D” will be printed.

11). Which logical operator is used to combine multiple conditions in an if statement?

a) &&
b) ||
c) ^
d) and

Correct answer is: d) and
Explanation: The logical operator “and” is used to combine multiple conditions in an if statement.

12). What is the output of the following code?

				
					    x = 5
    y = 10
    if x > 3 and y < 15:
        print("A")
    else:
        print("B")
				
			

a) A
b) B
c) A B
d) No output

Correct answer is:a) A
Explanation: Both conditions x > 3 and y < 15 are True, so “A” will be printed.

13). What is the output of the following code?

				
					    x = 5
    y = 10
    if x > 3 or y < 5:
        print("A")
    else:
        print("B")
				
			

a) A
b) B
c) A B
d) No output

Correct answer is:b) B
Explanation: Only the condition x > 3 is True, but the condition y < 5 is False. Since the logical operator “or” requires at least one True condition, “B” will be printed.

14). What is the output of the following code?

				
					    x = 7
    if x > 5:
        print("A")
        if x > 10:
            print("B")
    else:
        print("C")
				
			

a) A
b) A B
c) A C
d) No output

Correct answer is:a) A
Explanation: The condition x > 5 is True, so “A” will be printed. The nested if statement is skipped because the condition x > 10 is False.

15). Which of the following is the correct way to write an if-else statement without using elif?

a) if condition: then
b) if condition: else
c) if condition: else then
d) if condition: else:

Correct answer is:d) if condition: else:
Explanation: The correct syntax for an if-else statement without using elif is “if condition: else:”

16). What is the output of the following code?

				
					    x = 5
    if x > 3:
        print("A")
    elif x > 5:
        print("B")
    else:
        print("C")
				
			

a) A
b) B
c) C
d) No output

Correct answer is:a) A
Explanation: The condition x > 3 is True, so “A” will be printed. The condition x > 5 is not checked because the first if condition is True.

17). How many levels of nested if statements are allowed in Python?

a) 1
b) 2
c) 3
d) No limit

Correct answer is:d) No limit
Explanation: Python allows you to nest if statements as many times as needed.

18). What is the output of the following code?

				
					    x = 10
    if x > 5:
        if x < 15:
            print("A")
        else:
            print("B")
    else:
        print("C")
				
			

a) A
b) B
c) A B
d) No output

Correct answer is:a) A
Explanation: Both conditions x > 5 and x < 15 are True, so “A” will be printed. The else statement is skipped.

19). What is the output of the following code?

				
					
    x = 5
    if x > 3:
        print("A")
    if x > 5:
        print("B")
    else:
        print("C")
				
			

a) A
b) B
c) A B
d) A C

Correct answer is:c) A B
Explanation: The condition x > 3 is True, so “A” will be printed. The condition x > 5 is False, so “B” will not be printed. The else statement is skipped.

20). What is the output of the following code?

				
					    x = 10
    if x > 15:
        print("A")
    elif x > 10:
        print("B")
    else:
        print("C")
				
			

a) A
b) B
c) C
d) No output

Correct answer is:c) C
Explanation: The condition x > 15 is False. The condition x > 10 is also False. Therefore, the else statement is executed, and “C” is printed.

21). What is the output of the following code?

				
					    x = 5
    if x < 3:
        print("A")
    elif x < 7:
        print("B")
    elif x < 10:
        print("C")
    else:
        print("D")
				
			

a) A
b) B
c) C
d) D

Correct answer is:b) B
Explanation: The condition x < 7 is True, so “B” will be printed. The elif condition x < 10 is also True, but only the first True condition is executed.

22). What is the output of the following code?

				
					    x = 10
    if x > 5:
        print("A")
        if x > 15:
            print("B")
        else:
            print("C")
    else:
        print("D")
				
			

a) A B
b) A C
c) A C D
d) No output

Correct answer is:b) A C
Explanation: The condition x > 5 is True, so “A” will be printed. The nested if statement is skipped because the condition x > 15 is False. The else statement is executed, and “C” is printed.

23). What is the output of the following code?

				
					    x = 10
    if x > 5:
        print("A")
    if x > 15:
        print("B")
    else:
        print("C")
				
			

a) A
b) B
c) A C
d) C

Correct answer is:a) A C
Explanation: The condition x > 5 is True, so “A” will be printed. The condition x > 15 is False, so “B” will not be printed. The else statement is executed, and “C” is printed.

24). What is the output of the following code?

				
					    num = 5 
    if num%3 == 0:
        print("Number is divisible by 3")
    else:
        print("Number is not divisible by 3")
				
			

a) Number is divisible by 3
b) Number is not divisible by 3
c) SyntaxError
d) ValueError

Correct answer is:b) Number is not divisible by 3
Explanation: The condition num % 3 == 0 is False because 5 divided by 3 leaves a remainder of 2. Therefore, the code will print “Number is not divisible by 3”.

25). What is the purpose of the following code?

				
					    for i in range(1, 31):
        if i % 3 == 0:
            print(i, end=" ")

				
			

a) To print all numbers from 1 to 30
b) To print all multiples of 3 from 1 to 30
c) To print all even numbers from 1 to 30
d) To print all odd numbers from 1 to 30

Correct answer is:b) To print all multiples of 3 from 1 to 30
Explanation: The code uses a for loop to iterate through numbers in the range from 1 to 30.

Python Loop MCQ : Set 4

Python Loop MCQ

1). What is the output of the following code?

for i in range(5):
    if i % 2 == 0:
        continue
    print(i)

a) 1 3
b) 0 2 4
c) 1 2 3 4
d) 0 1 2 3 4

Correct answer is: a) 1 3
Explanation: The if condition checks if i is divisible by 2 (i.e., odd). If it is odd, the continue statement is executed, skipping the remaining code for that iteration.

2). What is the output of the following code?

i = 1
while i <= 5:
    print(i)
    i += 1
else:
    print(“Loop completed”)

a) 1 2 3 4 5
Loop completed
b) 1 2 3 4 5 6
Loop completed
c) 2 3 4 5 6
Loop completed
d) 1 2 3 4 5 6 7
Loop completed

Correct answer is: a) 1 2 3 4 5
Loop completed
Explanation: The while loop prints the value of i and increments it until i becomes greater than 5. After completing all iterations, the else block is executed and prints “Loop completed”.

3). What is the output of the following code?

for i in range(1, 6):
    if i == 3:
        break
    print(i)

a) 1 2
b) 1 2 3
c) 1 2 3 4 5
d) 2 3 4 5

Correct answer is: a) 1 2
Explanation: The for loop iterates from 1 to 5. When i becomes 3, the break statement is executed, terminating the loop prematurely.

4). What is the output of the following code?

i = 0
while i < 3:
    print(i)
    i += 1
    if i == 2:
        break

a) 0 1
b) 0 1 2
c) 0 1 2 3
d) 0

Correct answer is: a) 0 1
Explanation: When i is equal to 2, the break statement is executed, terminating the loop prematurely.

5). What is the output of the following code?

i = 0
while i < 5:
    i += 1
    if i == 3:
        continue
    print(i)

a) 1 2 4 5
b) 1 2 3 4 5
c) 1 3 4 5
d) 2 3 4 5

Correct answer is: c) 1 3 4 5
Explanation: When i is equal to 3, the continue statement is executed, skipping the remaining code for that iteration.

6). What is the output of the following code?

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    if number % 2 == 0:
        continue
    print(number)

a) 1 2 3 4 5
b) 1 3 5
c) 2 4
d) 1

Correct answer is: b) 1 3 5
Explanation: The code iterates over the list `numbers`. When a number is even, the `continue` statement is executed, skipping the remaining code for that iteration.

7). Which loop in Python allows the execution of a block of code for a fixed number of times?
a) while loop
b) for loop
c) do-while loop
d) until loop

Correct answer is: b) for loop
Explanation: The `for` loop in Python allows the execution of a block of code for a fixed number of times, iterating over a sequence or collection.

8). What is the output of the following code?

for i in range(5, 0, -1):
    print(i)

a) 5 4 3 2 1
b) 1 2 3 4 5
c) 0 1 2 3 4
d) 4 3 2 1 0

Correct answer is: a) 5 4 3 2 1
Explanation: The `range()` function starts from 5 and decrements by 1 until it reaches 1 (excluding 0). The numbers are then printed in reverse order.

9). What is the output of the following code?

i = 0
while i < 5:
    if i == 3:
        break
    print(i)
    i += 1

a) 0 1 2 3 4
b) 0 1 2
c) 0 1 2 3
d) 0

Correct answer is: b) 0 1 2
Explanation: The `break` statement is executed when `i` becomes 3, terminating the loop prematurely.

10). What is the output of the following code?

numbers = [1, 2, 3, 4, 5]
for index in range(len(numbers)):
    if numbers[index] % 2 == 0:
        break
    print(numbers[index])

a) 1 2 3 4 5
b) 1 3 5
c) 2 4
d) 1

Correct answer is: d) 1
Explanation: The code iterates over the indices of the `numbers` list. When an even number is encountered, the `break` statement is executed, terminating the loop.

11). What is the output of the following code?

i = 1
while True:
    print(i)
    i += 1
    if i == 5:
        break

a) 1 2 3 4
b) 1 2 3 4 5
c) 1 2 3 4 5
d) The program enters an infinite loop.

Correct answer is: a) 1 2 3 4
Explanation: The `while` loop continues indefinitely until the ‘break’ statement is executed when `i` becomes 5.

12). What is the output of the following code?

for i in range(1, 6):
    if i % 2 == 0:
        break
    print(i)

a) 1
b) 1 2
c) 1 3 5
d) 1 2 3 4 5

Correct answer is: a) 1
Explanation: The `break` statement is executed when an even number is encountered, terminating the loop after the first iteration.

13). What is the output of the following code?

i = 0
while i < 5:
    i += 1
    if i % 2 == 0:
        continue
    print(i)

a) 1 2 3 4 5
b) 1 3 5
c) 2 4
d) 1 2 4 5

Correct answer is: b) 1 3 5
Explanation: The `continue` statement is executed when an even number is encountered, skipping the remaining code for that iteration.

14). What is the output of the following code?

for i in range(5):
    print(i)

a) 0 1 2 3 4
b) 0 1 2 3
c) 1 2 3 4 5
d) 1 2 3 4

Correct answer is: a) 0 1 2 3 4
Explanation: The `for` loop iterates from 0 to 4 (excluding 5), printing the value of `i` at each iteration.

15). What is the output of the following code?

i = 1
while i <= 3:
    print(i)
    i += 1
    if i == 2:
        continue

a) 1 2 3
b) 1 2
c) 1 2 3 4
d) 1

Correct answer is: a) 1 2 3
Explanation: The `continue` statement does not have any effect in this case as it is placed after the increment statement.

16). What is the output of the following code?

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    if number == 3:
        break
    print(number)

a) 1 2 3 4 5
b) 1 2
c) 1 2 3
d) 1 2 4 5

Correct answer is: b) 1 2
Explanation: The `break` statement is executed when the number 3 is encountered, terminating the loop prematurely.

17). What is the output of the following code?

i = 0
while i < 5:
    print(i)
    i += 1
    if i == 3:
        continue

a) 0 1 2 3 4
b) 0 1 3 4
c) 0 1 2 3 4 5
d) 0 1 2 4

Correct answer is: a) 0 1 2 3 4
Explanation: The `continue` statement is executed when `i` is equal to 3, skipping the remaining code for that iteration.

18). What is the output of the following code?

for i in range(3):
    for j in range(i):
        print(i, j)

a) No output
b) 0 0
1 0
1 1
2 0
2 1
c) 0 0
1 0
1 1
2 0
d) 0 0
1 0
1 1

Correct answer is: c) 0 0
1 0
1 1
2 0
Explanation: The outer loop iterates three times, and for each iteration, the inner loop iterates `i` times, where `i` represents the current value of the outer loop.

19). What is the output of the following code?

i = 0
while i < 3:
    i += 1
    print(i)
    if i == 2:
        break

a) 1 2
b) 1 2 3
c) 0 1 2
d) 0 1 2 3

Correct answer is: a) 1 2
Explanation: The `break` statement is executed when `i` becomes 2, terminating the loop prematurely.

20). What is the output of the following code?

for i in range(1, 6):
    print(i)
else:
    print(“Loop completed”)

a) 1 2 3 4 5
Loop completed
b) 1 2 3 4 5 6
Loop completed
c) 2 3 4 5 6
Loop completed
d) 1 2 3 4 5 6 7
Loop completed

Correct answer is: a) 1 2 3 4 5
Loop completed
Explanation: The `else` block is executed after the completion of all iterations of the `for` loop.

21). What is the output of the following code?

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    print(number)
    if number == 3:
        break
else:
    print(“Loop completed”)

a) 1 2 3
Loop completed
b) 1 2 3 4 5
Loop completed
c) 1 2 3 4 5
d) 1 2 3 4

Correct answer is: a) 1 2 3
Loop completed
Explanation: The `break` statement is executed when the number 3 is encountered, terminating the loop prematurely. The `else` block is not executed in this case.

22). What is the output of the following code?

i = 0
while i < 5:
    if i == 2:
        i += 1
        continue
    print(i)
    i += 1

a) 0 1 2 3 4
b) 0 1 2 3
c) 0 1 3 4
d) 0 1 2 4

Correct answer is: b) 0 1 2 3
Explanation: The `continue` statement is executed when `i` is equal to 2, skipping the remaining code for that iteration.

23). What is the output of the following code?

for i in range(3):
    for j in range(3):
        if i == j:
        break
        print(i, j)

a) No output
b) 0 1
1 2
c) 0 1
0 2
1 2
d) 0 1
0 2
1 1
1 2

Correct answer is: a) No output
Explanation: The `break` statement is executed when `i` is equal to `j`, causing the inner loop to terminate for each iteration of the outer loop.

24). What is the output of the following code?

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    if number == 3:
        continue
    print(number)

a) 1 2 3 4 5
b) 1 3 4 5
c) 1 2 4 5
d) 2 3 4 5

Correct answer is: c) 1 2 4 5
Explanation: The `continue` statement is executed when the number 3 is encountered, skipping the remaining code for that iteration.

25). What is the output of the following code?

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    print(number)
    if number == 3:
        break
else:
    print(“Loop completed”)

a) 1 2 3
Loop completed
b) 1 2 3 4 5
Loop completed
c) 1 2 3 4 5
d) 1 2 3 4

Correct answer is: a) 1 2 3
Loop completed
Explanation: The `break` statement is executed when the number 3 is encountered, terminating the loop prematurely. The `else` block is not executed in this case.

Python Loop MCQ : Set 3

Python Loop MCQ

1). What is the output of the following code?

for i in range(5):
    if i == 2:
        break
    print(i)
else:
    print(“Loop completed”)

a) 0 1
b) 0 1 2
c) 0 1 2 3 4
d) Loop completed

Correct answer is: a) 0 1
Explanation: The for loop iterates from 0 to 4. When i becomes 2, the break statement is executed, terminating the loop prematurely.

2). Which loop control statement is used to terminate the entire program execution in Python?
a) stop
b) exit
c) terminate
d) quit

Correct answer is: b) exit
Explanation: The exit() function is used to terminate the entire program execution, not just loops.

3). What is the output of the following code?

i = 1
while i < 5:
    print(i)
    if i == 3:
        exit()
    i += 1

a) 1 2
b) 1 2 3 4
c) 1 2 3
d) The program terminates prematurely.

Correct answer is: d) The program terminates prematurely.
Explanation: The exit() function is used to terminate the entire program execution, not just loops. In this case, the program exits when i becomes 3.

4). What is the output of the following code?

for i in range(3):
    for j in range(2):
        print(i, j)
    else:
        print(“Inner loop completed”)
else:
print(“Outer loop completed”)

a) 0 0
0 1
1 0
1 1
2 0
2 1
Inner loop completed
Inner loop completed
Inner loop completed
Outer loop completed
b) 0 0
0 1
1 0
1 1
2 0
2 1
Inner loop completed
Inner loop completed
Inner loop completed
c) 0 0
0 1
1 0
1 1
Inner loop completed
2 0
2 1
Inner loop completed
Inner loop completed
Outer loop completed
d) 0 0
0 1
1 0
1 1
2 0
2 1
Inner loop completed
Inner loop completed
Outer loop completed

Correct answer is: a) 0 0
0 1
1 0
1 1
2 0
2 1
Inner loop completed
Inner loop completed
Inner loop completed
Outer loop completed
Explanation: The inner loop executes normally for each iteration of the outer loop. The else block after the inner loop is executed if the inner loop completes all its iterations without encountering a break statement. The outer loop’s else block is executed after the outer loop finishes all its iterations without encountering a break statement.

5). What is the output of the following code?

i = 1
while i <= 3:
     print(i)
     i += 1
else:
    print(“Loop completed”)

a) 1 2 3
Loop completed
b) 1 2 3 4
Loop completed
c) 2 3 4
Loop completed
d) Loop completed

Correct answer is: a) 1 2 3
Loop completed
Explanation: The while loop prints the value of i and increments it until i becomes greater than 3. After completing all iterations, the else block is executed and prints “Loop completed”.

6). What is the output of the following code?

i = 1
while i <= 3:
    print(i)
    i += 1
    if i == 2:
        continue
else:
print(“Loop completed”)

a) 1 2 3
b) 1 2
c) 1 2 3 4
d) 1

Correct answer is: a) 1 2 3
Explanation: The continue statement, when executed, skips the remaining code for the current iteration and moves to the next iteration. In this case, it does not have any effect as it is placed after the increment statement.

7). What is the output of the following code?

for i in range(3):
    if i == 2:
        exit()
    print(i)
else:
   print(“Loop completed”)

a) 0 1
b) 0 1 2
c) 0 1 2 3
d) The program terminates prematurely.

Correct answer is: d) The program terminates prematurely.
Explanation: The exit() function is used to terminate the entire program execution, not just loops. In this case, the program exits when i become 2.

8). What is the output of the following code?

for i in range(1,50):
    if i%7 == 0 and i%5 == 0:
        print(i, end=” “)

a) 28
b) 25
c) 35
d) 49

Correct answer is: c)35
Explanation: The code iterates over the range of numbers from 1 to 49 (excluding 50). For each number, it checks if the number is divisible by both 7 and 5. If the condition is true, the number is printed

9). What is the output of the following code?

for i in range(1, 6):
    if i % 2 == 0:
        break
    print(i)

a) 1
b) 1 2
c) 1 3 5
d) 1 2 3 4 5

Correct answer is: a) 1
Explanation: The if condition checks if i is divisible by 2 (i.e., even). When i becomes 2, the break statement is executed, terminating the loop after the first iteration.

10). What is the output of the following code?

i = 1
while i <= 5:
    print(i)
    i += 2

a) 1 2 3
b) 1 3 5
c) 2 4 6
d) 1

Correct answer is: b) 1 3 5
Explanation: The while loop prints the value of i and increments it by 2 until i becomes greater than 5.

11). What is the output of the following code?

for i in range(5):
    if i == 3:
        continue
    print(i)

a) 0 1 2 4
b) 0 1 2 3 4
c) 1 2 3 4
d) 0 1 2

Correct answer is: a) 0 1 2 4
Explanation: When i is equal to 3, the continue statement is executed, skipping the remaining code for that iteration.

12). What is the output of the following code?

for i in range(0,11):
    if i != 3 or i != 6:
        print(i,end=” “)

a) 0 1 2 3 4 5 6 7 8 9 10
b) 0 1 2 4 5 6 7 8 9 10
c) 0 1 2 3 4 5 7 8 9 10
d) 0 1 2 3 4 5 6 7 8 9

Correct answer is: b) 0 1 2 4 5 6 7 8 9 10
Explanation: The condition i != 3 or i != 6 is always true for any value of i. This is because if i is 3, then it is not equal to 6, and vice versa. As a result, the condition does not exclude any values of i. Therefore, the code will print all the numbers from 0 to 10, except 3 and 6.

13). What is the output of the following code?

i = 1
while i < 5:
    print(i)
    if i == 3:
        break
    i += 1

a) 1 2 3
b) 1 2 3 4
c) 1 2 3 4 5
d) 3

Correct answer is: a) 1 2 3
Explanation: The while loop executes until i is less than 5. When i becomes 3, the break statement is executed, terminating the loop prematurely.

14). What is the purpose of the else block in a loop?
a) It is executed if the loop encounters an error.
b) It defines the initial condition of the loop.
c) It specifies the code to execute after the loop finishes normally.
d) It breaks the loop prematurely.

Correct answer is: c) It specifies the code to execute after the loop finishes normally.
Explanation: The else block in a loop is executed when the loop completes all its iterations without encountering a break statement.

15). What is the output of the following code?

for i in range(3):
    print(i)
else:
    print(“Loop completed”)

a) 0 1 2
Loop completed
b) 1 2 3
Loop completed
c) 0 1 2 3
Loop completed
d) 1 2 3 4
Loop completed

Correct answer is: a) 0 1 2
Loop completed
Explanation: The for loop iterates from 0 to 2, and after completing all iterations, the else block is executed and prints “Loop completed”.

16). What is the output of the following code?

for i in range(1, 6):
    if i % 2 == 0:
        print(i)

a) 2 4
b) 1 3 5
c) 1 2 3 4 5
d) 1 2 3 4

Correct answer is: a) 2 4
Explanation: The if condition checks if i is divisible by 2 (i.e., even). If it is even, the print statement is executed, displaying the value of i.

17). What is the output of the following code?

num1 = 0
num2 = 1
count = 0

while count < 10:
    print(num1,end=” “)
    n2 = num1 + num2
    num1 = num2
    num2 = n2
    count += 1

a) 0 1 1 2 3 5 8 13 21 34
b) 0 1 2 3 4 5 6 7 8 9
c) 1 2 3 4 5 6 7 8 9 10
d) 0 1 1 3 4 7 11 18 29 47

Correct answer is: a) 0 1 1 2 3 5 8 13 21 34
Explanation: The given code implements the Fibonacci sequence using a while loop. In each iteration, it prints the value of num1 and calculates the next Fibonacci number by updating the values of num1 and num2. The loop continues for 10 iterations, printing the Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34.

18). What is the output of the following code?

i = 0
while i < 5:
    i += 1
    if i == 3:
        continue
    print(i)

a) 1 2 4 5
b) 1 2 3 4 5
c) 2 4 5
d) 1 2 3 5

Correct answer is: a) 1 2 4 5
Explanation: When i is equal to 3, the continue statement is executed, skipping the remaining code for that iteration.

19). What is the output of the following code?

i = 1
while i <= 5:
    print(i)
    i += 2

a) 1 2 3 4 5
b) 1 3 5
c) 2 4 6
d) 1

Correct answer is: b) 1 3 5
Explanation: The while loop prints the value of i and increments it by 2 until i becomes greater than 5.

20). What is the output of the following code?

i = 1
while i <= 3:
    print(i)
    i += 1
    if i == 2:
        continue

a) 1 2 3
b) 1 2
c) 1 2 3 4
d) 1

Correct answer is: a) 1 2 3
Explanation: The continue statement, when executed, skips the remaining code for the current iteration and moves to the next iteration. In this case, it does not have any effect as it is placed after the increment statement.

21). What is the output of the following code?
    
    for i in range(5):
        if i == 2:
            break
        print(i)
    else:
        print(“Loop completed”)
    
    a) 0 1
    b) 0 1 2
    c) 0 1 2 3 4
    d) Loop completed
 
Correct answer is: a) 0 1
Explanation: The for loop iterates from 0 to 4. When i becomes 2, the break statement is executed, terminating the loop prematurely.
 
22). Which loop control statement is used to terminate the entire program execution in Python?
    a) stop
    b) exit
    c) terminate
    d) quit
 
    Correct answer is: b) exit
    Explanation: The exit() function is used to terminate the entire program execution, not just loops.
 
23). What is the output of the following code?
    
    i = 1
    while i < 5:
        print(i)
        if i == 3:
            exit()
        i += 1
    
    a) 1 2
    b) 1 2 3 4
    c) 1 2 3
    d) The program terminates prematurely.
 
Correct answer is: d) The program terminates    prematurely.
Explanation: The exit() function is used to terminate the entire program execution, not just loops. In this case, the program exits when i becomes 3.
 
24). What is the output of the following code?
    
    for i in range(3):
        for j in range(2):
            print(i, j)
    
    a) 0 0
       0 1
       1 0
       1 1
       2 0
       2 1
    b) 0 0
       0 1
       1 0
       1 1
       2 0
    c) 0 0
       0 1
       1 0
       1 1
    d) 0 0
       0 1
 
Correct answer is: a) 0 0
       0 1
       1 0
       1 1
       2 0
       2 1
Explanation: The outer loop iterates three times, and for each iteration, the inner loop iterates twice, resulting in a total of six outputs.
 
25). What is the output of the following code?
    
    for i in range(3):
        print(i)
    else:
        print(“Loop completed”)
    
    a) 0 1 2
       Loop completed
    b) 1 2 3
       Loop completed
    c) 0 1 2 3
       Loop completed
    d) 1 2 3 4
       Loop completed
 
Correct answer is: a) 0 1 2
       Loop completed
Explanation: The for loop iterates from 0 to 2, and after completing all iterations, the else block is executed and prints “Loop completed”.

Python Loop MCQ : Set 2

Python Loop MCQ

1). Which loop control statement is used to terminate the loop prematurely and transfer control to the next iteration?
a) continue
b) exit
c) break
d) pass

Correct answer is: c) break
Explanation: The break statement is used to terminate a loop prematurely and transfer control to the next statement after the loop.

2). What is the output of the following code?

				
					    i = 1
    while i < 5:
        print(i)
        if i == 3:
            break
        i += 1
				
			

a) 1 2 3
b) 1 2 3 4
c) 1 2 3 4 5
d) 3

Correct answer is: a) 1 2 3
Explanation: The while loop executes until i is less than 5. When i becomes 3, the break statement is executed, terminating the loop prematurely.

3). Which loop control statement is used to skip the remaining code in the current iteration and move to the next iteration?
a) continue
b) exit
c) break
d) pass

Correct answer is: a) continue
Explanation: The continue statement is used to skip the remaining code in the current iteration and move to the next iteration.

4). What is the output of the following code?

				
					for i in range(1, 6):
        if i == 3:
            continue
        print(i)
				
			

a) 1 2 4 5
b) 1 2 3 4 5
c) 1 2 3
d) 1 2 4

Correct answer is: a) 1 2 4 5
Explanation: When i is equal to 3, the continue statement is executed, skipping the remaining code for that iteration.

5). What is the purpose of the pass statement in Python loops?
a) It terminates the loop.
b) It defines the initial condition of the loop.
c) It specifies the code to execute after the loop finishes normally.
d) It acts as a placeholder for future code.

Correct answer is: d) It acts as a placeholder for future code.
Explanation: The pass statement is a null operation in Python. It is used as a placeholder when a statement is syntactically required but no action is needed.

6). What is the output of the following code?

				
					    for i in range(3):
        pass
    print("Loop completed")
				
			

a) Loop completed
b) 0 1 2
Loop completed
c) 1 2 3
Loop completed
d) 0 1 2 3
Loop completed

Correct answer is: a) Loop completed
Explanation: The pass statement has no effect on the loop execution in Python. It is used as a placeholder. After the loop is completed, “Loop completed” is printed.

7). Which loop control statement is used to terminate the entire loop structure in Python?

a) continue
b) exit
c) break
d) pass

Correct answer is: c) break
Explanation: The break statement terminates the innermost loop structure it is inside. If used in a nested loop, it terminates the inner loop.

8). What is the output of the following code?

				
					for i in range(3):
        for j in range(3):
            if j == 2:
                break
            print(i, j)
				
			

a) 0 0
0 1
1 0
1 1
2 0
2 1
b) 0 0
0 1
1 0
1 1
2 0
c) 0 0
0 1
1 0
1 1
1 2
2 0
2 1
d) 0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2

Correct answer is: b) 0 0
0 1
1 0
1 1
2 0
Explanation: The inner loop terminates prematurely when j equals 2 due to the break statement. The outer loop continues normally.

9). Which loop control statement is used to terminate the entire loop structure and move to the next iteration of the outer loop in nested loops?
a) continue
b) exit
c) break
d) pass

Correct answer is: c) break
Explanation: The break statement, when used in a nested loop, terminates the innermost loop structure and moves to the next iteration of the outer loop.

10). What is the output of the following code?

				
					for i in range(3):
        for j in range(3):
            if j == 2:
                continue
            print(i, j)
				
			

a) 0 0
0 1
1 0
1 1
2 0
2 1
b) 0 0
0 1
1 0
1 1
2 0
c) 0 0
0 1
1 0
1 1
1 2
2 0
2 1
d) 0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2

Correct answer is: a) 0 0
0 1
1 0
1 1
2 0
Explanation: The continue statement skips the remaining parts of the inner loop for that iteration when j equals 2. It moves to the next iteration of the inner loop.

11). What is the output of the following code?

				
					    for i in range(3):
        for j in range(3):
            if j == 2:
                break
            print(i, j)
            else:
                print("Inner loop completed")
    else:
        print("Outer loop completed")
				
			

a) 0 0
0 1
Inner loop completed
1 0
1 1
Inner loop completed
2 0
2 1
Inner loop completed
Outer loop completed
b) 0 0
0 1
1 0
1 1
2 0
2 1
Inner loop completed
Inner loop completed
Inner loop completed
Outer loop completed
c) 0 0
0 1
1 0
1 1
Inner loop completed
2 0
2 1
Inner loop completed
Inner loop completed
Outer loop completed
d) 0 0
0 1
Inner loop completed
1 0
1 1
Inner loop completed
2 0
2 1
Outer loop completed

Correct answer is:
c) 0 0
0 1
1 0
1 1
Inner loop completed
2 0
2 1
Inner loop completed
Inner loop completed
Outer loop completed
Explanation: The inner loop executes normally for each iteration of the outer loop. The else block after the inner loop is executed if the inner loop completes all its iterations without encountering a break statement. The outer loop’s else block is executed after the outer loop finishes all its iterations without encountering a break statement.

12). Which loop control statement is used to terminate the entire loop structure and stop further iterations?
a) continue
b) exit
c) break
d) pass

Correct answer is: b) exit
Explanation: The exit statement is not a built-in loop control statement in Python. It is not used to terminate loops instead, it is typically used to terminate the entire program execution.

13). What is the output of the following code?

				
					for i in range(3):
        for j in range(3):
            if j == 2:
                exit()
            print(i, j)
				
			

a) 0 0
0 1
b) 0 0
0 1
1 0
1 1
c) 0 0
0 1
1 0
1 1
2 0
2 1
d) The program terminates prematurely.

Correct answer is: d) The program terminates prematurely.
Explanation: The exit() function is not a built-in loop control statement in Python. It is typically used to terminate the entire program execution, not just loops.

14). What is the output of the following code?

				
					    i = 1
    while i < 5:
        print(i)
        i += 1
        if i == 3:
            exit());
				
			

a) 1 2
b) 1 2 3 4
c) 1 2 3
d) The program terminates prematurely.

Correct answer is: d) The program terminates prematurely.
Explanation: The exit() function is not a built-in loop control statement in Python. It is typically used to terminate the entire program execution, not just loops. In this case, the program exits when i becomes 3.

15). Which loop control statement is used to restart the current iteration from the beginning of the loop?
a) continue
b) restart
c) break
d) pass

Correct answer is: a) continue
Explanation: The continue statement is used to skip the remaining code for the current iteration and move to the next iteration from the beginning of the loop.

16). What is the output of the following code?

				
					for i in range(5):
        if i == 3:
            continue
        print(i)
				
			

a) 0 1 2 4
b) 0 1 2 3 4
c) 1 2 3 4
d) 0 1 2

Correct answer is: a) 0 1 2 4
Explanation: When i is equal to 3, the continue statement is executed, skipping the remaining code for that iteration.

17). What is the output of the following code?

				
					numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
even = 0
odd = 0

for val in numbers:
   	if val%2 == 0:
        	even += 1
    	else:
        	odd += 1
				
			

print(“Number of even numbers: “,even)
print(“Number of odd numbers: “,odd)

a) Number of even numbers: 4, Number of odd numbers: 5
b) Number of even numbers: 5, Number of odd numbers: 4
c) Number of even numbers: 0, Number of odd numbers: 0
d) Number of even numbers: 9, Number of odd numbers: 0

Correct answer is: a) Number of even numbers: 4, Number of odd numbers: 5
Explanation: The given code iterates over the numbers tuple and counts the number of even and odd numbers. In the provided tuple, there are 4 even numbers (2, 4, 6, 8) and 5 odd numbers (1, 3, 5, 7, 9). The final output will display the count of even and odd numbers accordingly.

18). What is the output of the following code?

				
					
    i = 1
    while i < 5:
        print(i)
        if i == 3:
            break
        i += 1
				
			

a) 1 2 3
b) 1 2 3 4
c) 1 2 3 4 5
d) 3

Correct answer is: a) 1 2 3
Explanation: The while loop executes until i is less than 5. When i becomes 3, the break statement is executed, terminating the loop prematurely.

19). What is the purpose of the else block in a loop?

a) It is executed if the loop encounters an error.
b) It defines the initial condition of the loop.
c) It specifies the code to execute after the loop finishes normally.
d) It breaks the loop prematurely.

Correct answer is: c) It specifies the code to execute after the loop finishes normally.
Explanation: The else block in a loop is executed when the loop completes all its iterations without encountering a break statement.

20). What is the output of the following code?

				
					    for i in range(3):
        print(i)
    else:
        print("Loop completed")
				
			

a) 0 1 2
Loop completed
b) 1 2 3
Loop completed
c) 0 1 2 3
Loop completed
d) 1 2 3 4
Loop completed

Correct answer is: a) 0 1 2
Loop completed
Explanation: The for loop iterates from 0 to 2, and after completing all iterations, the else block is executed and prints “Loop completed”.

21). What is the output of the following code?

				
					
    for i in range(1, 6):
        if i % 2 == 0:
            print(i)
				
			

a) 2 4
b) 1 3 5
c) 1 2 3 4 5
d) 1 2 3 4

Correct answer is: a) 2 4
Explanation: The if condition checks if i is divisible by 2 (i.e., even). If it is even, the print statement is executed, displaying the value of i.

22). What is the output of the following code?

				
					    num = 1231254315
    str1 = str(num)
    D1 = {}
    for val in str1:
    	D1[val] = str1.count(val)
 
    print(D1)
				
			

a) {‘1’: 3, ‘2’: 2, ‘3’: 2, ‘4’: 1, ‘5’: 2}
b) {‘1’: 1, ‘2’: 1, ‘3’: 1, ‘4’: 1, ‘5’: 1}
c) {‘1’: 1, ‘2’: 2, ‘3’: 1, ‘4’: 2, ‘5’: 1}
d) {‘1’: 2, ‘2’: 1, ‘3’: 2, ‘4’: 1, ‘5’: 1}

Correct answer is: a) {‘1’: 3, ‘2’: 2, ‘3’: 2, ‘4’: 1, ‘5’: 2}
Explanation: The code counts the occurrence of each digit in the variable num and stores the counts in a dictionary D1. The final dictionary D1 contains the counts of digits in the original number num. The correct counts are: ‘1’: 2, ‘2’: 2, ‘3’: 2, ‘4’: 1, ‘5’: 1.

23). What is the output of the following code?

				
					    i = 0
    while i < 5:
        i += 1
        if i == 3:
            continue
        print(i)

				
			

a) 1 2 4 5
b) 1 2 3 4 5
c) 2 4 5
d) 1 2 3 5

Correct answer is: a) 1 2 4 5
Explanation: When i is equal to 3, the continue statement is executed, skipping the remaining code for that iteration.

24). What is the output of the following code?

				
					    i = 1
    while i <= 5:
        print(i)
        i += 2
				
			

a) 1 2 3 4 5
b) 1 3 5
c) 2 4 6
d) 1

Correct answer is: b) 1 3 5
Explanation: The while loop prints the value of i and increments it by 2 until i becomes greater than 5.

25). What is the output of the following code?

				
					    i = 1
    while i <= 3:
        print(i)
        i += 1
        if i == 2:
            continue
				
			

a) 1 2 3
b) 1 2
c) 1 2 3 4
d) 1

Correct answer is: a) 1 2 3
Explanation: The continue statement, when executed, skips the remaining code for the current iteration and moves to the next iteration. In this case, it does not have any effect as it is placed after the increment statement.

Python Loop MCQ : Set 1

Python Loop MCQ

1). What is a loop in Python?
a) A data structure
b) A control flow statement
c) A mathematical operation
d) A file handling technique

Correct answer is: b) A control flow statement
Explanation: A loop is a control flow statement that allows executing a block of code repeatedly until a certain condition is met.

2). Which loop in Python allows executing a block of code a fixed number of times?
a) for loop
b) while loop
c) do-while loop
d) nested loop

Correct answer is: a) for loop
Explanation: The for loop in Python is used to iterate over a sequence or range a fixed number of times.

3). What is the output of the following code?

				
					  for i in range(5):
       print(i)
				
			

a) 0 1 2 3 4
b) 1 2 3 4 5
c) 0 1 2 3
d) 1 2 3 4

Correct answer is: a) 0 1 2 3 4
Explanation: The range function generates a sequence of numbers from 0 to 4 (exclusive), and the for loop prints each number in the sequence.

4). Which keyword is used to exit a loop prematurely in Python?
a) continue
b) exit
c) break
d) return

Correct answer is: c) break
Explanation: The break keyword is used to exit a loop prematurely, skipping the remaining iterations.

5). What is the output of the following code?

				
					   i = 0
   while i < 5:
       print(i)
       i += 1
				
			

a) 0 1 2 3 4
b) 1 2 3 4 5
c) 0 1 2 3
d) 1 2 3 4

Correct answer is: a) 0 1 2 3 4
Explanation: The while loop executes as long as the condition (i < 5) is true. The variable i is incremented by 1 in each iteration of the loop.

6). Which loop in Python allows executing a block of code as long as a condition is true?
a) for loop
b) while loop
c) do-while loop
d) nested loop

Correct answer is: b) while loop
Explanation: The while loop repeatedly executes a block of code as long as a condition is true.

7). What is the output of the following code?

				
					   i = 5
   while i > 0:
       print(i)
       i -= 1
				
			

a) 5 4 3 2 1
b) 1 2 3 4 5
c) 5 4 3 2
d) 1 2 3 4

Correct answer is: a) 5 4 3 2 1
Explanation: The while loop executes as long as the condition (i > 0) is true. The variable i is decremented by 1 in each iteration.

8). Which statement is used to skip the current iteration and move to the next iteration in a loop?
a) continue
b) exit
c) break
d) pass

Correct answer is: a) continue
Explanation: The continue statement skips the current iteration of a loop and moves to the next iteration.

9). What is the output of the following code?

				
					  for i in range(1, 6):
       if i == 3:
           continue
       print(i)
				
			

a) 1 2 4 5
b) 1 2 3 4 5
c) 1 2 3
d) 1 2 4

Correct answer is: a) 1 2 4 5
Explanation: The continue statement skips the iteration when i equals 3, so only the numbers 1, 2, 4, and 5 are printed.

10). Which loop allows executing a block of code at least once, even if the condition is initially false?
a) for loop
b) while loop
c) do-while loop
d) nested loop

Correct answer is: c) do-while loop
Explanation: Python doesn’t have a built-in do-while loop. However, we can achieve a similar behavior using a while loop with a condition at the end.

11). What is the output of the following code?

				
					    i = 5
    while True:
        print(i)
        i -= 1
        if i == 0:
            break
				
			

a) 5 4 3 2 1
b) 1 2 3 4 5
c) 5 4 3 2
d) 1 2 3 4

Correct answer is: a) 5 4 3 2 1
Explanation: The while loop executes indefinitely since the condition is always true. The break statement is used to exit the loop when i reaches 0.

12). Which loop is used to iterate over the elements of a sequence, such as a list or a string, in Python?

a) for loop
b) while loop
c) do-while loop
d) nested loop

Correct answer is: a) for loop
Explanation: The for loop in Python is commonly used to iterate over the elements of a sequence, such as a list or a string.

13). What is the output of the following code?

				
					    my_list = ['apple', 'banana', 'cherry']
    for item in my_list:
        print(item)
				
			

a) apple banana cherry
b) 1 2 3
c) 0 1 2
d) TypeError: ‘int’ object is not iterable

Correct answer is: a) apple banana cherry
Explanation: The for loop iterates over each element in the list `my_list` and prints them.

14). Which loop is used when we need to execute a section of code multiple times, with each iteration based on the results of the previous iteration?

a) for loop
b) while loop
c) do-while loop
d) nested loop

Correct answer is: b) while loop
Explanation: The while loop is useful when we need to repeat a section of code multiple times, and the number of iterations depends on the results of the previous iteration.

15). What is the output of the following code?

				
					    i = 1
    while i < 5:
        print(i)
        i += 2
				
			

a) 1 3 5
b) 1 2 3 4
c) 1 2 3
d) 1 3

Correct answer is: a) 1 3 5
Explanation: The while loop executes as long as the condition (i < 5) is true. The variable i is incremented by 2 in each iteration.

16). What is the purpose of the range() function in a for loop?
a) It generates a sequence of numbers.
b) It defines the number of iterations.
c) It iterates over the elements of a list.
d) It breaks the loop prematurely.

Correct answer is: a) It generates a sequence of numbers.
Explanation: The range() function generates a sequence of numbers that can be used to control the number of iterations in a for loop.

17). What is the output of the following code?

				
					for i in range(3, 9, 2):
        print(i)
    
				
			

a) 3 5 7
b) 1 3 5 7
c) 3 6 9
d) 1 2 3 4 5 6 7 8

Correct answer is: a) 3 5 7
Explanation: The range function generates a sequence of numbers starting from 3 (inclusive) and ending at 9 (exclusive) with a step size of 2. The for loop iterates over this sequence and prints each number.

18). Which loop allows nesting one loop inside another loop?
a) for loop
b) while loop
c) do-while loop
d) nested loop

Correct answer is: d) nested loop
Explanation: Nested loops refer to the technique of having one loop inside another loop.

19). What is the output of the following code?

				
					for i in range(1, 4):
        for j in range(1, 4):
            print(i * j)
				
			

a) 1 2 3 2 4 6 3 6 9
b) 1 1 1 2 2 2 3 3 3
c) 1 2 3 1 2 3 1 2 3
d) 1 2 3 3 6 9

Correct answer is: a) 1 2 3 2 4 6 3 6 9
Explanation: The outer loop iterates over the values 1, 2, and 3, while the inner loop iterates over the same values. The product of i and j is printed in each iteration.

20). Which loop in Python is best suited for iterating over a dictionary?
a) for loop
b) while loop
c) do-while loop
d) nested loop

Correct answer is: a) for loop
Explanation: The for loop is commonly used to iterate over the keys or values of a dictionary in Python.

21). What is the output of the following code?

				
					my_dict = {'grapes': 2, 'banana': 3, 'blue-berry': 4}
for key in my_dict:
    print(key)
				
			

a) grapes banana blue-berry
b) 1 2 3
c) 0 1 2
d) TypeError: ‘int’ object is not iterable

Correct answer is: a) grapes banana blue-berry
Explanation: The for loop iterates over the keys of the dictionary `my_dict` and prints them.

22). Which statement can be used to modify the flow of a loop, allowing the next iteration to skip some parts of the loop’s code block?
a) continue
b) exit
c) break
d) pass

Correct answer is: a) continue
Explanation: The continue statement allows skipping the remaining parts of the loop’s code block for the current iteration and moving to the next iteration.

23). What is the output of the following code?

				
					for i in range(8):
        if i % 2 == 0:
            continue
        print(i)
				
			

a) 1 3 5 7
b) 0 2 4
c) 0 1 2 3 4 5
d) 1 2 3 4 5

Correct answer is: a) 1 3 5 7
Explanation: The if condition checks if i is divisible by 2 (i.e., even). If it is even, the continue statement is executed, and the loop skips the remaining code for that iteration.

24). What is the purpose of the else block in a loop?

a) It is executed if the loop encounters an error.
b) It defines the initial condition of the loop.
c) It specifies the code to execute after the loop finishes normally.
d) It breaks the loop prematurely.

Correct answer is: c) It specifies the code to execute after the loop finishes normally.
Explanation: The else block in a loop is executed when the loop completes all its iterations without encountering a break statement.

25). What is the output of the following code?

				
					    for i in range(5):
        print(i)
    else:
        print("Loop completed")
				
			

a) 0 1 2 3 4
Loop completed
b) 1 2 3 4 5
Loop completed
c) 0 1 2 3
Loop completed
d) 1 2 3 4
Loop completed

Correct answer is: a) 0 1 2 3 4
Loop completed
Explanation: The for loop iterates from 0 to 4, and after completing all iterations, the else block is executed and prints “Loop completed”.

Python Variable MCQ : Set 4

Python Variable MCQ

1). What is the output of the following code?
x = [1, 2, 3]
y = x.copy()
y[0] = 10
print(x)

a) [1, 2, 3]
b) [10, 2, 3]
c) [1, 2, 3, 10]
d) None of these

Correct answer is a)
Explanation: The copy() method creates a shallow copy of the list. Modifying the copy does not affect the original list.

2). What is the output of the following code?
x = “Hello”
print(len(x))

a) 5
b) 6
c) 10
d) None of these

Correct answer is a)
Explanation: The len() function in Python returns the length of a string. In this case, len(“Hello”) is equal to 5.

3). Which of the following is the correct way to declare a global variable “x” inside a function?
a) global x
b) x = global
c) x.global()
d) None of these

Correct answer is a)
Explanation: The “global” keyword is used to declare a variable as global inside a function.

4). What is the output of the following code?
x = “Python”
print(x[-2])

a) t
b) o
c) n
d) None of these

Correct answer is a)
Explanation: Negative indexing starts from the end of the string. x[-2] returns the second-to-last character, which is “t”.

5). What is the output of the following code?
x = “Hello”
print(x[::-1])

a) Hello
b) olleH
c) ello
d) None of these

Correct answer is b)
Explanation: The slicing [::-1] reverses the string. In this case, “Hello” reversed becomes “olleH”.

6). Which of the following is a valid way to check if a variable “x” is of type float?
a) type(x) == float
b) x.type() == float
c) typeof(x) == float
d) None of these

Correct answer is a)
Explanation: The type() function is used to check the type of a variable. The comparison “type(x) == float” checks if “x” is of type float.

7). What will be the value of the variable “x” after the execution of the following code?
x = [1, 2, 3]
y = x
y.append(4)

a) [1, 2, 3]
b) [1, 2, 3, 4]
c) [4, 3, 2, 1]
d) None of these

Correct answer is b)
Explanation: Both variables “x” and “y” refer to the same list object. Modifying “y” will also modify “x” since they point to the same memory location.

8). What is the output of the following code?
x = “Hello”
print(x[1])

a) H
b) e
c) l
d) None of these

Correct answer is b)
Explanation: Indexing starts from 0. x[1] returns the second character, which is “e”.

9). Which of the following is true about local variables in Python?
a) They can be accessed from any part of the program
b) Their scope is limited to the function or block where they are defined
c) They are declared using the local keyword
d) None of these

Correct answer is b)
Explanation: Local variables are only accessible within the function or block where they are defined.

10). What is the output of the following code?
x = 2
y = 3
print(x < y)

a) True
b) False
c) 2
d) 3

Correct answer is a)
Explanation: The < operator checks if the left operand is less than the right operand. In this case, 2 < 3 is True.

11). What is the output of the following code?
x = 5
y = 2
z = x % y
print(z)

a) 1
b) 2
c) 0
d) None of these

Correct answer is a)
Explanation: The % operator calculates the remainder of the division. In this case, 5 % 2 is equal to 1.

12). Which of the following is a valid variable name in Python?
a) 1_variable
b) variable_1
c) variable-1
d) variable 1

Correct answer is b)
Explanation: Variable names in Python can contain letters, numbers, and underscores, but they cannot start with a number or contain spaces or hyphens.

13). What is the output of the following code?
x = “Python”
print(x[1:4])

a) Pyt
b) yth
c) tho
d) None of these

Correct answer is b)
Explanation: Slicing extracts a portion of a string. In this case, x[1:4] returns the characters from index 1 to index 3, excluding the character at index 4.

14). Which of the following is the correct way to convert a floating-point number to an integer in Python?
a) int()
b) float_to_int()
c) str()
d) None of these

Correct answer is a)
Explanation: The int() function can be used to convert a floating-point number to an integer in Python.

15). What will be the value of the variable “x” after the execution of the following code?
x = 5
y = x
y = y + 2
print(x)

a) 5
b) 7
c) 2
d) None of these

Correct answer is a)
Explanation: Assigning the value of “x” to “y” creates a copy of the value. Modifying “y” does not affect the original value of “x”.

16). What is the output of the following code?
x = “Python”
print(x[1:])

a) Python
b) ython
c) P
d) None of these

Correct answer is b)
Explanation: Slicing with an omitted end index returns the substring from the start index to the end of the string. In this case, x[1:] returns “ython”.

17). Which of the following is the correct way to declare a constant variable in Python?
a) Use the const keyword
b) Prefix the variable name with an underscore (e.g., _PI)
c) Use all uppercase letters for the variable name (e.g., PI)
d) None of these

Correct answer is c)
Explanation: Although Python does not have built-in support for constant variables, using all uppercase letters for the variable name is a common convention to indicate that it should be treated as a constant.

18). What is the output of the following code?
x = [1, 2, 3]
y = x
y = [4, 5, 6]
print(x)

a) [1, 2, 3]
b) [4, 5, 6]
c) [1, 2, 3, 4, 5, 6]
d) None of these

Correct answer is a)
Explanation: Assigning a new list [4, 5, 6] to “y” does not modify the original list object referred to by “x”.

19). Which of the following is a valid way to concatenate two strings in Python?
a) str.add()
b) str.join()
c) str.append()
d) None of these

Correct answer is b)
Explanation: The str.join() method can be used to concatenate two strings in Python.

20). What will be the output of the following code?
x = 2
y = 3
print(x == y)

a) True
b) False
c) 2
d) 3

Correct answer is b)
Explanation: The == operator checks if the left operand is equal to the right operand. In this case, 2 is not equal to 3, so the expression evaluates to False.

21). What is the output of the following code?
x = 2
x = x * 3
x = x + 1
print(x)

a) 5
b) 7
c) 8
d) 9

Correct answer is d)
Explanation: The code multiplies the value of “x” by 3, adds 1 to it, and assigns the result back to “x”. Therefore, the value of “x” becomes 7, then 8.

22). What will be the value of the variable “y” after the execution of the following code?
x = [1, 2, 3]
y = x
x.append(4)
print(y)

a) [1, 2, 3]
b) [1, 2, 3, 4]
c) [4, 3, 2, 1]
d) None of these

Correct answer is b)
Explanation: When “y” is assigned the value of “x”, it refers to the same list object in memory. Therefore, any changes made to the list through either variable will be reflected in both. The code appends the value 4 to the list, so the value of “y” becomes [1, 2, 3, 4].

23). What will be the value of the variable “x” after the execution of the following code?
x = [1, 2, 3]
y = x
y[0] = 4
print(x)

a) [1, 2, 3]
b) [4, 2, 3]
c) [4, 2, 3, 4]
d) None of these

Correct answer is b)
Explanation: Since “x” and “y” refer to the same list object, modifying the list through one variable will affect the other. The code changes the value at index 0 to 4, so the value of “x” becomes [4, 2, 3].

24). What is the output of the following code?
x = “Hello”
y = “World”
z = x + y
print(z)

a) “Hello World”
b) “HelloWorld”
c) “WorldHello”
d) “HWeolrllod”

Correct answer is a)
Explanation: The + operator in Python can be used to concatenate two strings in Python. In this case, the variable “z” contains the concatenation of “Hello” and “World”, resulting in the string “Hello World”.

25). Which of the following statements is true regarding variable names in Python?
a) Variable names can contain spaces.
b) Variable names can start with a number.
c) Variable names are case-insensitive.
d) Variable names can contain special characters like @ or #.

Correct answer is b)
Explanation: Variable names in Python cannot start with a number. They can only start with a letter or an underscore.

Python Variable MCQ : Set 3

Python Variable MCQ

1). What will be the value of the following variable?
a = 10
a += 5
a -= 3

a) 5
b) 7.5
c) 10
d) 12

Correct answer is d)
Explanation: The code performs arithmetic operations on the variable “a”. The final value of “a” will be 12.

2). What is the scope of a local variable in Python?
a) Restricted to the function where it is defined
b) Accessible from any part of the program
c) Restricted to the class where it is defined
d) None of these

Correct answer is a)
Explanation: A local variable is accessible only within the function or block of code where it is defined.

3). Which of the following statements is true about global variables in Python?
a) They are accessible only within a specific function
b) They can be accessed from any part of the program
c) They can only store numeric values
d) None of these

Correct answer is b)
Explanation: Global variables can be accessed from any part of the program, including functions.

4). What will be the output of the given code?
a = 7
b = 3
print(x // y)

a) 2.5
b) 2
c) 3
d) 2.0

Correct answer is b)
Explanation: The double slash (//) is the floor division operator, which performs integer division and returns the quotient. In this case, 5 // 2 is equal to 2.

5). What is the data type of the following variable?
x = 5.0

a) int
b) float
c) double
d) None of these

Correct answer is b)
Explanation: The variable “x” is assigned a floating-point value, so its data type is float.

6). What will be the output of the given code?
x = “2”
y = 3
print(x * y)

a) 23
b) 6
c) 222
d) TypeError

Correct answer is c)
Explanation: When a string is multiplied by an integer, it repeats the string multiple times. In this case, “2” * 3 results in “222”.

7). What will be the output of the given code?
x = 10
y = “20”
print(x + int(y))

a) 30
b) 1020
c) 102010
d) TypeError

Correct answer is a)
Explanation: The code converts the string “20” to an integer using the int() function and performs addition. The result is 30.

8). Which of the following is an invalid variable name in Python?
a) my-var
b) my_var
c) 123var
d) _var123

Correct answer is a)
Explanation: Variable names cannot contain hyphens (-) in Python. Underscores (_) are allowed.

9). What will be the value of the variable “x” after the execution of the following code?
x = 5
x = x + “2”

a) 7
b) 52
c) TypeError
d) None of these

Correct answer is c)
Explanation: You cannot concatenate a string and an integer using the + operator. It raises a TypeError.

10). Which of the following is the correct way to check the type of a variable “x”?
a) typeof(x)
b) type(x)
c) x.type()
d) None of these

Correct answer is b)
Explanation: The type() function is used to check the type of a variable in Python.

11). What is the output of the following code?
x = 3.8
print(int(x))

a) 3
b) 4
c) 3.0
d) 4.0

Correct answer is a)
Explanation: The int() function converts a floating-point number to an integer by truncating the decimal part. In this case, int(3.8) is equal to 3.

12). What will be the output of the following code?
x = “Hello, World!”
print(x[7:12])

a) Hello
b) World
c) , Wor
d) None of these

Correct answer is b)
Explanation: The code uses slicing to extract the characters from index 7 to 11 (exclusive). This results in the string “World”.

13). Which of the following is true about constant variables in Python?
a) Their values cannot be changed after the assignment
b) They can only store integer values
c) They are declared using the const keyword
d) None of these

Correct answer is d)
Explanation: Python does not have a built-in concept of constant variables. Variables can be reassigned with different values.

14). What will be the output of the following code?
x = 2
y = 3
print(x ** y)

a) 6
b) 8
c) 9
d) 6.0

Correct answer is c)
Explanation: The double asterisk (**) is the exponentiation operator in Python. In this case, 2 ** 3 is equal to 8.

15). Which of the following is an immutable data type in Python?
a) list
b) tuple
c) dictionary
d) set

Correct answer is b)
Explanation: Tuples are immutable, meaning their elements cannot be changed once assigned. Lists, dictionaries, and sets are mutable.

16). What is the output of the following code?
x = “SQATOOLS”
print(x[-3:])

a) OLS
b) LS
c) SQA
d) OOLS

Correct answer is a)
Explanation: Negative indexing starts from the end of the string. x[-3:] extracts the last three characters, resulting in “OLS”.

17). What will be the value of the variable “x” in the given code?
x = 2
x = x * x

a) 2
b) 4
c) 8
d) None of these

Correct answer is b)
Explanation: The code squares the value of “x” and assigns the result back to “x”. So the value of “x” is 4.

18). Which of the following is a valid way to concatenate two strings in Python?
a) str1.add(str2)
b) str1 + str2
c) str1.concat(str2)
d) None of these

Correct answer is b)
Explanation: The + operator in Python is used to concatenate two strings in Python.

19). What is the output of the given code?
x = “Python”
print(x[1:4])

a) Pyt
b) yth
c) thon
d) None of these

Correct answer is b)
Explanation: The code uses slicing to extract the characters from index 1 to 3 (exclusive). This results in the string “yth”.

20). What will be the output of the given code?
x = 5
y = 2
print(x % y)

a) 2.5
b) 2
c) 1
d) 2.0

Correct answer is c)
Explanation: The % operator is the modulus operator, which returns the remainder of the division. In this case, 5 % 2 is equal to 1.

21). Which of the following is a valid way to convert an integer to a string in Python?
a) int_to_str()
b) str()
c) convert_str()
d) None of these

Correct answer is b)
Explanation: The str() function is used to convert an object to its string representation.

22). What is the output of the following code?
x = 2.7
print(round(x))

a) 2
b) 3
c) 2.0
d) 3.0

Correct answer is a)
Explanation: The round() function rounds the given number to the nearest integer. In this case, round(2.7) is equal to 2.

23). What will be the value of the variable “x” after the execution of the following code?
x = [1, 2, 3]
y = x
y[0] = 10

a) [1, 2, 3]
b) [10, 2, 3]
c) [10, 2, 3, 1]
d) None of these

Correct answer is b)
Explanation: Both variables “x” and “y” refer to the same list object. Modifying “y” will also modify “x” since they point to the same memory location.

24). Which of the following is a valid way to convert a string to an integer in Python?
a) int_to_str()
b) str()
c) int()
d) None of these

Correct answer is c)
Explanation: The int() function is used to convert a string to an integer in Python.

25). What is the output of the following code?
x = “Hello”
y = “World”
print(x + y)

a) HelloWorld
b) Hello World
c) Hello+World
d) None of these

Correct answer is a)
Explanation: The + operator concatenates two strings. In this case, “Hello” + “World” results in “HelloWorld”.

Python Variable MCQ : Set 2

Python Variable MCQ

1). What will be the output of the following Python code?
type(10.0)
  a) <class ‘float’>
  b) <class ‘int’>
  c) <class ‘list’>
  d) None of these

Correct answer is a).
Explanation: The value 10.0 is float, so the output of the given code will be <class ‘float’>.

2). What will be the output of the following Python code?
type(10/2)
  a) int
  b) <class ‘float’>
  c) 5
  d) None of these

Correct answer is b).
Explanation: Here, we are not finding the arithmetic value of 10/5, instead we need the data type of 10/5 (i.e. 2.0). So the output will be float.

3). What will be the output of the following Python code?
type(()) is <class ‘tuple’>
  a) True
  b) False

Correct answer is a).
Explanation: Tuples are stored inside round brackets () and the parameter inside type() is an empty tuple. So, the given code on execution will give the output as True.

4). What will be the output of the following Python code?
type([])
  a) <class ‘array’>
  b) <class ‘dict’>
  c) <class ‘list’>
  d) Code will generate an error

Correct answer is c).
Explanation: Lists are stored inside square brackets [] and the parameter inside type() is an empty list. So, the given code on execution will give the output as <class ‘list’>.

5). What will be the output of the following Python code?
type({}) is <class ‘set’>

  a) True
  b) False

Correct answer is b).
Explanation: type({}) produces a dictionary and not a set so the correct answer is b).

6). What will be the output of the following Python code?

bool(-5)
  a) True
  b) False

Correct answer is a).
Explanation: Bool is used to get a truth value of an expression.

7). A variable should be assigned a value before it is declared.
  a) True
  b) False

Correct answer is b).
Explanation: Python determines the type of a variable during runtime based on the value that is assigned to it. So, not necessary to assign a value during its declaration.

8). Which of the following function gives a unique number assigned to an object?
  a) ref()
  b) reference()
  c) id()
  d) type()

Correct answer is c).
Explanation: id() function returns a unique id for the object.

9). How do we define a block of code in Python?
  a) Using curly braces
  b) Indentation
  c) Using Brackets
  d) None of these

Correct answer is b).
Explanation: Identation is used to define a block of code in Python. Curly braces {} are used to define a block of code in other languages like C, C++,.

10). Variable names are case-sensitive in Python.
  a) True
  b) False

Correct answer is a).
Explanation: Variable names are case-sensitive in Python. So, variable1 is different than VARIABLE1 in Python.

11). How do we comment in a single line in Python?
  a) /
  b) \
  c) #
  d) ” “

Correct answer is c).
Explanation: Hash (#) is used to comment the entire line.

12). The following way is correct to assign multiple variables to a single value
      a = b = c = 5
  a) True
  b) False

Correct answer is a).
Explanation: This is a compact way to assign the same value to multiple variables. Here, a, b, and c will have a value of 5.

13). The following way is correct to assign multiple variables to multiple values
a, b, c = “Bikes”, “Cars”, “Trucks”
  a) True
  b) False

Correct answer is a).
Explanation: This is a compact way to assign values to multiple variables. Here, a, b, and c will have “Bikes”, “Cars”, and “Trucks” respectively.

14). What will be the output of the following Python code?
type(4j)
  a) alphanum
  b) long
  c) complex
  d) Error

Correct answer is c).
Explanation: j suffix to 4 (e.g., 4j) indicates the imaginary part. Type for such value returns complex.

15). What will be the output of the following Python code?
type(4l)
  a) alphanum
  b) long
  c) complex
  d) Error

Correct answer is d)
Explanation: Output will produce an error for this Python code. It varies on Python versions. This is valid in Python 2.7.5 and returns “long”.

16). Python supports the conversion of integer variables to complex.
  a) True
  b) False

Correct answer is a).
Explanation: Conversion of integer say x to complex is supported in Python using complex (x) function.

17). Python supports the conversion of complex variables to integers.
  a) True
  b) False

Correct answer is b).
Explanation: Conversion of complex numbers to integers is not supported in Python.

18). What will be the output of the following Python code?
var = “Hello”
int(var)
  a) Hello
  b) H,e,l,l,o
  c) Code will generate an error
  d) None of these

Correct answer is c).
Explanation: This is not supported in Python, and the code will generate an error: invalid literal for int() with base 10.

19). What will be the output of the following Python code?
var = “1234”
int(var)
  a) 1234
  b) 1,2,3,4
  c) Code will generate an error
  d) None of these

Correct answer is a).
Explanation: This will work fine in Python, and the code will produce output 1234 (correct option a).

20). What will be the output of the following Python code?
var = str(1234)
print(var)
  a) 1234
  b) 1,2,3,4
  c) ‘1234’
  d) Code will generate an error

Correct answer is a).
Explanation: This will work fine in Python, and the code will produce output 1234 (correct option a).

21). What will be the output of the following Python code?
str(1234)
  a) 1234
  b) 1,2,3,4
  c) ‘1234’
  d) Code will generate an error

The correct answer is c).
Explanation: This will work fine in Python, and the code will produce output ‘1234’ (correct option c).

22). What is a variable in Python Programming language?
a) A container to store data
b) A function to perform calculations
c) A loop control structure
d) None of these

Correct answer is a)
Explanation: A variable in Python is a name that refers to a value or data stored in the computer’s memory.

23). Which of the following is a valid variable name in Python?
a) 123var
b) var123
c) _var
d) None of these

Correct answer is b)
Explanation: Variable names in Python can start with a letter or an underscore (_), but not with a digit.

24). What will be the output of the following code?
x = 5
y = “Hello”
z = x + y
print(z)

a) 5Hello
b) Hello5
c) TypeError
d) None of these

Correct answer is c)
Explanation: You cannot perform arithmetic operations between different data types. Adding an integer and a string raises a TypeError.

25). Which of the following is not a valid variable type in Python?
a) int
b) float
c) string
d) char

Correct answer is d)
Explanation: Python does not have a separate data type for characters. Characters are represented as strings of length 1.

Python variable MCQ : Set 1

Python Variable MCQ

1). Which is the correct way to get the type of the variable, say for variable x that holds any kind of value?

  a) typedef (x)
  b) pytype (x)
  c) type (x)
  d) None of these

Correct answer is c).
Explanation: Type is a built-in function in Python that returns the class type of the object.
For example: If x is a number (integer), then type(x) will return “<class ‘int’>”.

2). Which is true for the variable names in Python?
  a) underscore is not allowed
  b) only names and special characters are allowed
  c) unlimited length
  d) none of these

Correct answer is c).
Explanation: There is no limit of the variable name length in the python.

3). What is __name__ in python?
  a) this is not a built-in variable
  b) this is a built-in variable
  c) None of these

Correct answer is b).
Explanation:  __name__ is a special or built-in variable that gives the name of the current module.

4). What is a ++ in Python?
  a) this is an increment operator like Java or C++
  b) this is not allowed in Python
  c) this is used as a global variable
  d) none of these

Correct answer is b).
Explanation: There is no ++ incremental operator in Python.

5). What are nonlocal variables in Python?
  a) Those are the same as the global variable
  b) Those are declared within nested functions
  c) There is no way to create nonlocal variables in Python
  d) None of these

Correct answer is b).
Explanation: Variables that are declared within a nested function are called nonlocal variables.

6). What are local variables in Python?
  a) Those are declared inside the function
  b) Those are defined within the local scope
  c) Not accessible outside of the function
  d) All of the these

Correct answer is d).
Explanation: Local variables are defined within a local scope, declared inside the function, and can not be accessed outside of the function.

7). Which is an invalid statement?
  a) testvar = 1000
  b) test var = 1000 2000
  c) test,var = 1000, 2000
  d) test_var = 1000

Correct answer is b).
Explanation: Whitespace is not allowed in the variable name.

8). What will be the value of variable b after the below code execution?
       a = “10”
       b = a + str (5)

  a) 15
  b) 5
  c) 105
  d) Syntax error

Correct answer is c).
Explanation: In this code, we are not adding 5 with 10 arithmetically but, we are adding two strings namely “10” and “5”.

9). Which is not a correct way to assign value to the variable?
  a) x=y=z=10
  b) x,y,z=10
  c) x,y,z=7.5,word,5
  d) None of these

Correct answer is b).
Explanation: Assigning a single value to multiple variables is not possible.

10). What will be the output of :
num = 2.789
print(round(num))
  a) 2.0
  b) 2.79
  c) 3.0
  d) 3

Correct answer is c)
Explanation: The round() function in Python rounds a number to the nearest whole number. In this case, num is 2.789, which is closer to 3 than to 2. Therefore, when you use round(num), it will round up to 3.0.

11). Python Variable must be declared before it is assigned a value:

  a) True
  b) False

Correct answer is b).
Explanation: No need to declare a variable before it is assigned a value

12). What are the things inside the list called?
  a) variables
  b) identifiers
  c) elements
  d) items

Correct answer is c).
Explanation: The things inside the list are called elements.

13). Identify the correct key value pair:
dict = {“Name”:”Rahul”, “Age”:24, “Occupation”:”Lawyer”}
  a) Key is Rahul, Value is Name
  b) Key is Name, Value is 24
  c) Key is Name, Value is Rahul
  d) Key is Name, Value is Age

Correct answer is c).
Explanation: Here, we are asked to identify the correct key value PAIR, so it will be option c).

14). Choose the correct option of the below code:

        def num():
             global a
             a = 20
             a = a+10
             print(a)

        a=10
        num()
        print(a)

  a) 30
       10

  b) 30
       30

  c) 20
       10

  d) 20
       20

Correct answer is b).
Explanation: Inside function num(), variable “a” is initially declared as global and assigned value as 20. Value of “a” will be printed when num() is called.
Variable inside the function will be given preference and hence the output of a will be a = a+10 = 20+10 = 30.
As we have declared “a” as global so when the function ends, outside print(a) will also output 30. So the correct answer is b).

15). What will be the output of the following code:
print(20//7)
  a) 2
  b) 2.0
  c) 2.857142857142857
  d) 3

Correct answer is a).
Explanation: The ‘//’ operator is called the floor division operator. This operator carries out the division and rounds off the value into the nearest whole number.

16). Which of the following is a core data type?
  a) boolean
  b) class
  c) def
  d) none of these

Correct answer is a).
Explanation: Boolean is a core data type.

17). Which of the following is an immutable data type?
  a) Sets
  b) Lists
  c) Strings
  d) Dictionary

Correct answer is c).
Explanation: Strings are an immutable data type as their values cannot be updated.

18). Which of the following is not a data type?
  a) String
  b) Character
  c) Integer
  d) None of these

Correct answer is b).
Explanation: Character is not a data type.

19). Which of the following function does not return any value?
  a) type
  b) int
  c) bool
  d) None

Correct answer is d).
Explanation: type, int, and bool return some value whereas the None function does not.

20). What will be the output of the following Python code?
type(“abcd”)
  a) string
  b) char
  c) str
  d) int

Correct answer is c).
Explanation: “abcd” is stored in a string format so it will return str.

21). What will be the output of the following code?
list1 = [1,2,3,4]
tup1 = tuple(list1)
print(tup1)
  a) [1,2,3,4]
  b) (1,2,3,4)
  c) 1 2 3 4
  d) The code will give an error while running

Correct answer is b).
Explanation: In this code, we are converting a list into a tuple and then printing it, so the output that we will get will be in tuple format.

22). In which of the following data type is stored in “Key – Value” pair format?
  a) Lists
  b) Dictionary
  c) Tuples
  d) None of these

Correct answer is b).
Explanation: In dictionaries, data is stored in key-value pair format.

23). Which of the following cannot be a variable?
  a) pass
  b) fail
  c) Both a and b
  d) None of these

Correct answer is a).
Explanation: pass is a keyword in Python. So, it can’t be a variable.

24). What will be the output of the following Python code?
type(range(10))
  a) <class ‘range’>
  b) int
  c) dict
  d) None of these

Correct answer is a).
Explanation: Range allows to generation a series of numbers within the mentioned range. If it’s used with type(), then it returns <class ‘range’>.

25). What will be the output of the following Python code?
type(‘5’)
  a) <class ‘str’>
  b) <class ‘int’>
  c) <class ‘float’>
  d) None of these

Correct answer is a).
Explanation: As ‘5’ is stored in a string format i.e. inside the colons (”), it will give the output as <class ‘str’>.

48. Problem to create an inheritance example in Python

In this Python oops program, we will create an inheritance example in Python. Python class called Dog that inherits from the Animal class.

Inheritance example in Python

Steps to solve the program
  1. The Dog class extends the Animal class, which means it inherits the properties and methods of the Animal class.
  2. The Dog class has its own constructor method __init__ that takes four parameters: name, color, breed, and weight. It calls the constructor of the Animal class using super() to initialize the name and color properties inherited from the Animal class. It also initializes two additional properties: self.breed to store the breed of the dog and self.weight to store the weight of the dog.
  3. The Dog class overrides the print_details method inherited from the Animal class. It calls the print_details method of the Animal class using super().print_details() to print the name and color of the dog. Then, it prints the additional details: breed and weight.
  4. The code creates an object dog of the Dog class by calling its constructor with the arguments “Jelly”, “Golden”, “Golden Retriever”, and 25.
  5. The print_details method is called on the dog object to print the details of the dog, including the inherited name and color, as well as the breed and weight specific to the Dog class.
  6. Thus, we have created an inheritance example in Python.
				
					class Animal:
    def __init__(self, name, color):
        self.name = name
        self.color = color
    
    def print_details(self):
        print("Name:", self.name)
        print("Color:", self.color)

class Dog(Animal):
    def __init__(self, name, color, breed, weight):
        super().__init__(name, color)
        self.breed = breed
        self.weight = weight
    
    def print_details(self):
        super().print_details()
        print("Breed:", self.breed)
        print("Weight:", self.weight)

# Create an object of the Dog class
dog = Dog("Jelly", "Golden", "Golden Retriever", 25)
dog.print_details()
				
			

Output:

				
					Name: Jelly
Color: Golden
Breed: Golden Retriever
Weight: 25
				
			

Related Articles

Create a Python class called Animal with attributes name and color.