Exercise: Python

Questions for: Variables

What is the output of the following code:
x = "Hello"
y = "ExamAdept"
print(y + x)
A:
ExamAdeptHello
B:
ExamAdept Hello
C:
HelloExamAdept
D:
Hello ExamAdept
Answer: A

In Python, the + operator can be used to concatenate strings.

In this case, the variables x and y hold the strings "Hello" and "ExamAdept", respectively.

When they are concatenated with the + operator, the result y+x is "ExamAdeptHello".

What is the value of x after executing the following code:
x = 10
x += 5
x *= 2
print(x)
A:
15
B:
25
C:
30
D:
125
Answer: C

In Python, the += operator is used to add a value to a variable, and the *= operator is used to multiply a variable by a value.

In this case, x starts at 10, then 5 is added to it to make it 15, and then it is multiplied by 2 to make it 30.

The final value of x is 30.

Which of the following is a valid way to access the last item in a list called my_list?
A:
my_list.last
B:
my_list[-1]
C:
my_list[0]
D:
my_list[len(my_list)]
Answer: B
In Python, negative indices can be used to access elements from the end of a list. An index of -1 refers to the last item in the list, -2 refers to the second-to-last item, and so on. So my_list[-1] would access the last item in the list.
What is the difference between a global variable and a local variable?
A:
Global variables have a shorter lifespan than local variables.
B:
Global variables can only be accessed within a specific function, while local variables can be accessed anywhere in the code.
C:
Global variables can be accessed anywhere in the code, while local variables can only be accessed within a specific function.
D:
There is no difference between a global variable and a local variable.
Answer: C

In Python, a global variable is a variable that is defined outside of any function and can be accessed from anywhere in the code. A local variable, on the other hand, is a variable that is defined within a function and can only be accessed within that function.

Global variables exist throughout the entire program's execution, while local variables are created when a function is called and are destroyed when the function completes. Therefore, global variables have a longer lifespan than local variables.

Which of the following is a valid way to create an empty list?
A:
my_list = []
B:
my_list = lst()
C:
my_list = {}
D:
All of the above
Answer: A

In Python, you can create an empty list using the following ways:

# Using square brackets:
my_list = []

#Using the list() constructor:
my_list = list()

Both of these methods will create an empty list in Python.

Ad Slot (Above Pagination)
Quiz