Lesson 2 of 6 · Python

Storing things in variables

A useful program needs to remember information. Variables give values names so you can reuse, update and combine those values instead of typing them repeatedly.

What is a variable?

A variable is a name that refers to a value. The assignment operator = stores the value on its right under the name on its left. For example, name = "Sam" stores a string and age = 18 stores an integer.

You do not declare a variable type in advance. Python works out the type from the value you assign. You can also assign a new value to the same variable later in the program.

Naming variables clearly

Choose names that explain the information they hold. Names may contain letters, digits and underscores, but they cannot begin with a digit or contain spaces. Python treats student_name and Student_Name as two different names.

Avoid names that are too short to understand. total_marks is clearer than tm. Do not use Python keywords such as if, for or class as variable names.

Reuse and update values

Once a value is stored, use its variable name anywhere that value is needed. You can combine text with commas inside print(), or create a new value from existing variables. Python evaluates the expression on the right before assigning the result.

For example, age = age + 1 reads the current age, adds one and stores the result back in age. The shorter form age += 1 does the same job.

main.py
name = "Sam"
age = 18
course = "BCA"

print("Name:", name)
print("Age next year:", age + 1)
print("Course:", course)
marks.py
theory_marks = 72
practical_marks = 24
total_marks = theory_marks + practical_marks

print("Total:", total_marks)
total_marks += 2
print("Updated total:", total_marks)

Try it yourself

The code examples above are for reference. Copy the relevant example into the editor, press Run, then change it and run it again.

Code Campus
Your turn

Create variables for your name, city and age. Print a sentence using all three variables, then increase the age by one and print it again.

Show a hint
name = "Alex"
city = "Jalandhar"
age = 18
print(name, "lives in", city)
age += 1
print("Next year:", age)

#CodeCampus

Code Campus