Questions
Which of the following properly declares a variable?
"Michael Jordan" = namelarge_number = 2 ** 2025name: str = "Michael Jordan"int: large_number = 2 ** 2025
Which of the following properly updates or assigns a value to a variable (if it has already been declared)?
"Michael Jordan" = namelarge_number = 2 ** 2025name: str = "Michael Jordan"int: large_number = 2 ** 2025
Refer to the following code snippet to answer this question. Describe what will happen if we run this code. Feel free to create a memory diagram to assist you.
1 def foo(num: int) -> None:
2 """Fooey."""
3 x: int = num * -1
4 print(x)
5
6 def main() -> None:
7 """The main function."""
8 foo(4)
9 print(x)
10
11 main()SHOW SOLUTIONS
c:
name: str = "Michael Jordan"The important part to notice is that we are giving it a type, which we only do during declaration.large_number = 2 ** 2025Updating or assigning a value to a variable that has already been declared just uses the equal sign with the variable name on the left and the value on the right, and does not redeclare the type.
When this code is run, you will first enter the
mainfunction since it is called on line 11, then you will enter thefoofunction when it is called on line 8. Then thefoofunction will declare a local variablexand print it, outputting-4. Then we will return to line 8, then move on to line 9 where we attempt to printx. However,xwas a local variable only in thefooframe, not in themainframe, so we will get aNameError.