Check that the following code snippet will execute properly or not. Justify your answer.
a=10
b=25
if a<b:
print("a is less than b")
else:
print("b is less than a")Answer
Output: No output
Justification: The given code snippet will not execute properly because of incorrect indentation. In Python, it is mandatory to indent the statements inside the if and else blocks. If the statements under the if condition are not indented, Python will display an IndentationError and the program will not run. Since the print() statements are not indented under if and else, the code is syntactically incorrect.
What would be the output of following code snippet:
a = [1, 2, 3, 4, 5]
b = [2, 2, 2, 2, 2]
for i in a:
for j in b:
k=i+j
print(k)Answer
Output:
3
4
5
6
7
- The outer
forloop iterates through each element of lista. - For each value of
i, the innerforloop iterates through all elements of listb. - Inside the inner loop, the value of
kis updated ask = i + j. Since all elements of listbare 2, andkis overwritten in every inner iteration, after the inner loop finishes,kholds the valuei + 2. - The
print(k)statement is outside the inner loop but inside the outer loop, so it prints the final value ofkfor eachi.
Iterations:
Outer Loop (i) | Inner Loop (j) values | Calculation (k = i + j) | Value Printed |
|---|---|---|---|
| 1 | 2, 2, 2, 2, 2 | 3, 3, 3, 3, 3 | 3 |
| 2 | 2, 2, 2, 2, 2 | 4, 4, 4, 4, 4 | 4 |
| 3 | 2, 2, 2, 2, 2 | 5, 5, 5, 5, 5 | 5 |
| 4 | 2, 2, 2, 2, 2 | 6, 6, 6, 6, 6 | 6 |
| 5 | 2, 2, 2, 2, 2 | 7, 7, 7, 7, 7 | 7 |
In Python, an 'if-elif-else' can be used to implement the 'switch-case' paradigm.
Answer
True
Reason — In Python, the if-elif-else statement allows checking multiple conditions one after another, which performs the same role as a switch-case statement by executing different blocks of code based on different conditions.
In Python, 'elif' and 'else' can be used interchangeably.
Answer
False
Reason — elif is used to check an additional condition, whereas else does not check any condition and is executed only when all the preceding if and elif conditions evaluate to false. Therefore, elif and else cannot be used interchangeably.
The 'while' loop is suitable to iterate sequence data type.
Answer
False
Reason — The while loop is used when the number of iterations is not known beforehand and it works based on a condition, whereas sequence data types are iterated using the for loop.
In Python, 'continue' and 'pass' keywords are interchangeable.
Answer
False
Reason — The continue statement is used to skip the current iteration of a loop and transfer the control to the beginning of the loop for the next iteration, whereas the pass statement is a null statement that does nothing and is used only as a placeholder to make the code syntactically correct. Therefore, the continue and pass keywords are not interchangeable.
The 'for' loop uses membership operator 'in'.
Answer
True
Reason — The for loop in Python uses the membership operator in to check the presence of a value in a sequence and to iterate over each element of that sequence one by one.
The function of the 'continue' and 'break' statements is the same.
Answer
False
Reason — The break statement terminates the loop immediately and transfers the control outside the loop, whereas the continue statement skips the current iteration and transfers the control to the next iteration of the loop. Therefore, their functions are not the same.
In Python, you cannot create an empty 'for' loop.
Answer
False
Reason — In Python, an empty for loop can be created by using the pass statement. The pass statement acts as a null statement and allows the loop body to remain empty while keeping the syntax correct. Therefore, it is possible to create an empty for loop in Python.
The 'while' loop can be used to create an infinite loop.
Answer
True
Reason — The while loop executes as long as the given condition evaluates to True. If the condition never becomes False, the loop will continue to execute indefinitely, thereby creating an infinite loop.
A loop inside a loop is called nested loop.
Answer
True
Reason — A loop that is written inside the body of another loop is called a nested loop, where one loop (inner loop) executes completely for each iteration of the outer loop.
In Python, 'elif' can be used without 'if'.
Answer
False
Reason — The elif statement cannot be used independently. It must always be used after an if statement to check an additional condition.
Which of the following keywords is not used in conditional statements?
- if
- else
- elif
- go
Answer
go
Reason — The keywords used in Python conditional statements are if, else, and elif. The keyword go is not a conditional keyword in Python.
What will be the output of the following statement for any two values of a & b entered by the user?
print(a) if a>b else print(b)
- It will give an error
- It will print the largest number
- It will print the smallest number
- None of these
Answer
It will print the largest number
Reason — This is a shorthand if-else statement. If the condition a > b is true, the value of a is printed, otherwise, the value of b is printed. Therefore, the larger of the two numbers is printed.
Which of the following is the correct sequence to create multiple conditional statements?
- if else else
- if elif else
- if else elif
- if else if
Answer
if elif else
Reason — In Python, when we need to check more than one condition, we use the if-elif-else statement. The if statement checks the first condition, the elif statement checks the next condition, and the else statement is executed when none of the conditions are true. Therefore, the correct sequence to create multiple conditional statements is if elif else.
Which logical operator(s) is/are used to combine multiple conditions in 'if' statement?
- and
- or
- not
- both a and b
Answer
both a and b
Reason — In Python, the logical operators and and or are used to combine multiple conditions in an if statement. The and operator checks if all conditions are true, while the or operator checks if any one of the conditions is true.
The function of 'else' in 'if-else' statement is:
- to execute the block of statements when the condition is True
- to execute the block of statements when the condition is False
- to specify an alternative condition
- None of these
Answer
to execute the block of statements when the condition is False
Reason — In an if-else statement, when the condition written in the if statement evaluates to False, the else block is executed. Thus, the function of else is to execute the block of statements when the condition is False.
How many conditions can be checked using the if-elif-elif-else statement?
- One
- Two
- Three
- Four
Answer
Three
Reason — The if-elif-elif-else statement consists of one if condition and two elif conditions, allowing three conditions to be checked. The else part does not check any condition, it executes when all the conditions are false. Therefore, the correct answer is Three.
In Python, what would be the condition to check if a value is not equal to 5?
- x =! 5
- x != 5
- x not= 5
- x == 5
Answer
x != 5
Reason — In Python, the != operator is the not equal to comparison operator. It is used to check whether two values are not equal. Therefore, the correct condition to check if a value is not equal to 5 is x != 5.
In Python, which keyword is used to terminate a loop immediately?
- exit
- return
- break
- continue
Answer
break
Reason — The break keyword is used to terminate a loop immediately and transfer the control outside the loop.
From the following, which is not a comparison operator in Python?
- ==
- !=
- >=
- <>
Answer
<>
Reason — In Python, the valid comparison operators include ==, !=, and >=. The symbol <> is not a comparison operator in Python.
What would be the result of the following expression?
15 > 12 and 2 < 1
- True
- False
- Error
- None of these
Answer
False
Reason — The expression contains the logical operator and, which returns True only if both conditions are true.
= 15 > 12 and 2 < 1
= True and False
= False
Fill in the blanks:
- ................ is used to repeat a block of code until a certain condition is met.
- ................ statement in a loop is used to break the execution of the loop.
- ................ keyword is used to create an empty loop.
- ................ statement is used to skip the current iteration of the loop and move to the next.
- ................ loop is used to iterate over a sequence of items.
Answer
- while loop is used to repeat a block of code until a certain condition is met.
- break statement in a loop is used to break the execution of the loop.
- pass keyword is used to create an empty loop.
- continue statement is used to skip the current iteration of the loop and move to the next.
- for loop is used to iterate over a sequence of items.
Explain the use of break statement in Python with the help of an example.
Answer
The break statement in Python is used to terminate a loop immediately and transfer the control outside the loop, even if the loop condition is still true.
Example:
numbers = [1, 2, 3, 4, 5]
for n in numbers:
if n == 4:
break
print(n)
print("The end")Output:
1
2
3
The end
In this example, the loop iterates through the list numbers. When the value 4 is encountered, the break statement is executed, which stops the loop immediately and the control comes out of the loop. After the loop ends, the statement print("The end") is executed.
Write a program to find the smallest number among three numbers by using the nested 'if-else' statements.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
if a < b:
if a < c:
print("Smallest number is:", a)
else:
print("Smallest number is:", c)
else:
if b < c:
print("Smallest number is:", b)
else:
print("Smallest number is:", c)Enter first number: 5
Enter second number: 8
Enter third number: 3
Smallest number is: 3
Write a Python program to check that if a given number is even or odd.
num = int(input("Enter a number: "))
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")Enter a number: 82
The number is even.
Enter a number: 51
The number is odd.
Write a Python program to add all the elements of a tuple.
t = (10, 20, 30, 40)
s = 0
for i in t:
s = s + i
print("Sum of elements of the tuple is:", s)Sum of elements of the tuple is: 100
Write a program to delete/remove all the numbers less than 10 from the list.
numbers = [5, 12, 3, 20, 8, 15, 2, 30]
new_list = []
for i in numbers:
if i >= 10:
new_list.append(i)
print("List after removing numbers less than 10:", new_list)List after removing numbers less than 10: [12, 20, 15, 30]
Write a Python program to find the largest element in a tuple.
t = (12, 45, 7, 89, 34)
largest = t[0]
for i in t:
if i > largest:
largest = i
print("The largest element in the tuple is:", largest)The largest element in the tuple is: 89
Write a Python program to find the square of all elements between 1 to 20.
for i in range(1, 21):
print(i * i)1
4
9
16
25
36
49
64
81
100
121
144
169
196
225
256
289
324
361
400
Write a Python program to demonstrate the use of the if-elif-else statements.
num = 4
if num == 1:
print("Red")
elif num == 2:
print("Blue")
elif num == 3:
print("Green")
elif num == 4:
print("Yellow")
elif num == 5:
print("Orange")
else:
print("Invalid input")Yellow
Write a python program to print a pyramid using 'for' loop.
rows = 5
for i in range(1, rows + 1):
for j in range(rows - i):
print(" ", end="")
for k in range(1, 2 * i):
print("*", end="")
print() *
***
*****
*******
*********
Write a program to store marks of your class students and show their percentage.
n = int(input("Enter number of students: "))
max_marks = int(input("Enter maximum marks: "))
names = []
percentages = []
for i in range(n):
name = input("Enter student name: ")
marks = int(input("Enter total marks: "))
percentage = (marks / max_marks) * 100
names.append(name)
percentages.append(percentage)
print("\nStudent Name and Percentage")
for i in range(n):
print(names[i], "-", percentages[i], "%")Enter number of students: 3
Enter maximum marks: 300
Enter student name: Asha
Enter total marks: 250
Enter student name: Ravi
Enter total marks: 208
Enter student name: Neha
Enter total marks: 290
Student Name and Percentage
Asha - 83.33333333333334 %
Ravi - 69.33333333333334 %
Neha - 96.66666666666667 %
Write a program to implement a simple shopping cart system. In it user can add items, remove items, view the cart, and calculate the total cost.
cart = []
price = []
choice = 0
while choice != 5:
print("1. Add item")
print("2. Remove item")
print("3. View cart")
print("4. Calculate total cost")
print("5. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
item = input("Enter item name: ")
cost = int(input("Enter item price: "))
cart.append(item)
price.append(cost)
print("Item added to cart")
elif choice == 2:
item = input("Enter item name to remove: ")
if item in cart:
index = cart.index(item)
cart.pop(index)
price.pop(index)
print("Item removed from cart")
else:
print("Item not found")
elif choice == 3:
print("Items in cart:")
for i in range(len(cart)):
print(cart[i], "-", price[i])
elif choice == 4:
total = 0
for p in price:
total = total + p
print("Total cost:", total)
elif choice == 5:
print("Thank you for shopping")
else:
print("Invalid choice")1. Add item
2. Remove item
3. View cart
4. Calculate total cost
5. Exit
Enter your choice: 1
Enter item name: Pen
Enter item price: 50
Item added to cart
1. Add item
2. Remove item
3. View cart
4. Calculate total cost
5. Exit
Enter your choice: 1
Enter item name: Book
Enter item price: 100
Item added to cart
1. Add item
2. Remove item
3. View cart
4. Calculate total cost
5. Exit
Enter your choice: 1
Enter item name: Pencil
Enter item price: 15
Item added to cart
1. Add item
2. Remove item
3. View cart
4. Calculate total cost
5. Exit
Enter your choice: 2
Enter item name to remove: Pen
Item removed from cart
1. Add item
2. Remove item
3. View cart
4. Calculate total cost
5. Exit
Enter your choice: 3
Items in cart:
Book - 100
Pencil - 15
1. Add item
2. Remove item
3. View cart
4. Calculate total cost
5. Exit
Enter your choice: 4
Total cost: 115
1. Add item
2. Remove item
3. View cart
4. Calculate total cost
5. Exit
Enter your choice: 5
Thank you for shopping
Write a program that inputs two tuples and creates a third one that contains all the elements of the first tuple followed by all the elements of the second tuple.
tuple1 = eval(input("Enter first tuple: "))
tuple2 = eval(input("Enter second tuple: "))
tuple3 = tuple1 + tuple2
print("First tuple:", tuple1)
print("Second tuple:", tuple2)
print("Combined tuple:", tuple3)Enter first tuple: (1, 2, 3)
Enter second tuple: (4, 5, 6)
First tuple: (1, 2, 3)
Second tuple: (4, 5, 6)
Combined tuple: (1, 2, 3, 4, 5, 6)
Write a program to print the longest word in the given list of words.
words = ["apple", "banana", "grapes", "watermelon", "kiwi"]
longest = words[0]
for w in words:
if len(w) > len(longest):
longest = w
print("The longest word is:", longest)The longest word is: watermelon