2.3 How do we use variables

We use variables in several ways, mainly in:

  • Declaration and Initialization - Assigning a value to a variable creates the variable and reserves a memory location for it.

Example 2.3.1

age = 14
name = "Kim"

 

  • Storing Data - Variables hold data that can be used and manipulated throughout the program.

Example 2.3.2

score = 95

 

  • Retrieving Data - The stored value in a variable can be accessed and used in operations.

Example 2.3.3

print(score)
Example 2.3.3 - Output

95

 

  • Updating Data - Variables can be reassigned new values during the program's execution.

Example 2.3.4

score = 100

 


 

Exercise 2.3.1 - Write a Python program by first declaring a variable called city. Set (initialize) city to the name of your favorite city. Print the name of your favorite city by using the city variable.

You can refer to Output topic if you need help with the print() function.

Exercise 2.3.1 - Model Answer - Make sure to work out the exercise before checking the model answer.