Exercise: Variables

Questions for: Variables

Which of the following is a valid way to convert a string '10' to an integer?
A:
int('10')
B:
'10'.toint()
C:
integer('10', base=10)
D:
All of the above
Answer: A

int('10') is the correct way to convert a string to an integer in Python.

'10'.toint() is not a valid method for converting a string to an integer; instead, it will raise an AttributeError.

integer('10', base=10) is also not a valid way to convert a string to an integer, it will raise a NameError: name 'integer' is not defined.

What is the output of the following code:
my_dict = {'a': 1, 'b': 2, 'c': 3}
del my_dict['b']
print(my_dict)
A:
{'a': 1}
B:
{'a': 1, 'c': 3}
C:
{'a': 1, 'b': 2, 'c': 3}
D:
An error is raised
Answer: B

In this code, a dictionary my_dict is defined with three key-value pairs.

The second line uses the del statement to remove the key-value pair with the key 'b' from the dictionary.

When the dictionary is printed to the console, it shows the modified dictionary {'a': 1, 'c': 3}.

Which of the following statements about Python constants is true?
A:
They are variables whose values cannot be changed.
B:
They are defined using the const keyword.
C:
Python doesn't have a built-in constant type.
D:
None of the above
Answer: C
Python doesn't have a built-in constant type, unlike some other programming languages. Conventionally, constants in Python are defined using all uppercase letters to indicate that their values should not be changed, but this is only a convention and not enforced by the language.
Which of the following is true about global variables?
A:
They can only be accessed within a function.
B:
They can be accessed and modified anywhere in the code.
C:
They can be accessed but can't be modified anywhere in the code.
D:
They can be accessed anywhere in the code, but can only be modified within a function.
Answer: B

Global variables are defined outside of any function, and can be accessed and modified from anywhere in the code.

However, it's generally not recommended to use global variables extensively, as they can make the code harder to understand and debug.

What is the output of the following code:
x = 10
y = 5
x, y = y, x
print(x, y)
A:
5 10
B:
10 5
C:
An error is raised
D:
None of the above
Answer: A

In this code, two variables x and y are assigned the values 10 and 5 respectively.

The third line swaps the values of the variables using the tuple packing and unpacking technique.

When the variables are printed to the console, the output is 5 10.

Ad Slot (Above Pagination)
Quiz