Variables and String Interpolation

Question Click to View Answer

What does the following code print to the console?

x = 32
print(x)

32 is printed to the console.

x = 32 is an example of variable assignment. The variable x is assigned to the value 32.

Assign the variable my_city to the string "New York". Print my_city to the console.

my_city = "New York"
print(my_city)

What does the following code print to the console?

num1 = 10
num2 = 20
print(num1 + num2)

30 is printed to the console.

The variable num1 is assigned to the value 10. The variable num2 is assigned to the value 20. The variables are added and the sum is printed to the console.

What does the following code print to the console?

s1 = "hot"
s2 = "dog"
print(s1 + s2)

"hotdog" is printed to the console.

The variable s1 is assigned to the value "hot" and the variable s2 is assigned to the value "dog". The strings are concatenated and the resulting value ("hotdog") is printed to the console.

What does the following code print to the console?

print(f"I like the number {6 + 2}")

"I like the number 8" is printed to the console.

This example uses string interpolation. When a string is preceded with a f it tells Python to use string interpolation and it will evaluate all values enclosed by brackets ({}) in the string.

What does the following code print to the console?

first_name = "television"
hobby = "homer"
tmp = first_name
first_name = hobby
hobby = tmp
print(f"{first_name} likes to watch {hobby}")

"homer likes to watch television" is printed to the console.

This exercise uses the tmp variable to switch the values of the first_name and hobby variables. String interpolation is used to print the resulting string to the console.

What does the following code print to the console?

first_name, last_name = "edward", "norton"
print(f"{first_name} {last_name} is an actor")

"edward norton is an actor" is printed to the console.

first_name, last_name = "edward", "norton" is an example of multiple assignment in Python. This syntactic sugar makes it easier to simultaneously assign multiple values. We could have also assigned the variables on separate lines.

first_name = "edward"
last_name = "norton"

String interpolation is used to embed the two variables in a string.

What does the following code print the console?

y = 34
y = "pablo"
print(y)

"pablo" is printed.

y is initially assigned to 34. y is then reassigned to "pablo". When a variable is reassigned, it loses all knowledge of other variables that it used to be assigned to.