What is the output of this code?
def add(a, b): return a + b print(add(5, 10)) print(add('Hello, ', 'world!')) print(add([1, 2], [3, 4]))
Think about how the + operator works differently for numbers, strings, and lists.
The add function uses the + operator, which works for integers (adds), strings (concatenates), and lists (concatenates). So all three calls succeed and print the combined results.
What will be printed when running this code?
def describe(x): return f'Type: {type(x).__name__}, Value: {x}' print(describe(42)) print(describe([1, 2, 3])) print(describe({'a': 1}))
Look at how type(x).__name__ returns the type name as a string.
The function returns a string showing the type name and the value. The dictionary prints with quotes around the key because it's a string key.
What error does this code raise when executed?
def multiply(x, y): return x * y print(multiply(3, 4)) print(multiply('Hi', 3)) print(multiply([1, 2], '2'))
Check the types of arguments in the last call and how multiplication works for lists and strings.
The last call tries to multiply a list by a string, which is not allowed and raises a TypeError. Multiplying a list by an integer repeats the list, but multiplying by a string is invalid.
What is the output of this code?
class Dog: def speak(self): return 'Woof' class Cat: def speak(self): return 'Meow' def animal_sound(animal): return animal.speak() print(animal_sound(Dog())) print(animal_sound(Cat()))
Each class has its own speak method. The function calls the method on the passed object.
The function animal_sound calls the speak method on the object passed. Dog returns 'Woof', Cat returns 'Meow'.
Which option best explains why the following code works without errors?
def operate(x):
return x.action()
class A:
def action(self):
return 'A action'
class B:
def action(self):
return 'B action'
print(operate(A()))
print(operate(B()))Think about how Python decides if an object can do something, not what type it is.
This is duck typing: if an object has the method needed, Python allows calling it without checking the object's class explicitly.