What is the output of the following Python code?
string = 'Hello, world!'
print(string[7:12])
Explanation:
In Python, string slicing uses a zero-based index. string[7:12]
extracts characters from index 7 (inclusive) to 12 (exclusive), resulting in the substring 'world'.
What is the value of 'x' after this code executes?
x = 5 if x == 5: x += 1 else: x -= 1
Explanation:
Since 'x' is initially 5, the condition 'x == 5' is true. Therefore, 'x' is incremented by 1, resulting in 6.
What will the following Python code snippet print?
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Explanation:
The code defines a function greet
that takes a name
as input and prints a greeting. When called with "Alice", it substitutes "Alice" for name
in the print statement.
What will the following Python code snippet print?
x = 5
if x > 10:
print('A')
elif x > 3:
print('B')
else:
print('C')
Explanation:
The code checks if x
is greater than 10. Since it's not, it moves to the elif
condition. As x
is greater than 3, 'B' is printed.
What will the following code print?
my_set = {1, 2, 3}
my_set.add(3)
print(my_set)
Explanation:
Sets in Python are unordered collections of unique elements. Adding an element that already exists in the set has no effect. Therefore, the output will remain {1, 2, 3}
.
What will be the data type of the result of the following expression: 10 / 2
?
Explanation:
In Python, dividing two integers using the /
operator always results in a float, even if the division is whole.
Can a Python function return multiple values?
Explanation:
Python allows returning multiple values by implicitly packaging them into a tuple. This tuple can then be unpacked into individual variables.