livepython.net
CHAPTER 04Variables
4.1  VARIABLES

Python Variables: Store and Use Values

What Is a Variable?

A variable is a name that stores a value, so your program can use it later. You create one with the = sign:

PYTHONedit me
name = "Sunny"
age = 25
OUTPUT

Now name holds the text "Sunny", and age holds the number 25. Nothing is printed yet: creating a variable only stores the value.

Think of it like a labelled box. The label is the name (name), and inside the box is the value ("Sunny"). Whenever you say the label, Python opens the box and uses what's inside.

How = works in Python

  • The name goes on the left, the value on the right: name = "Sunny".
  • = means "store this value in this name". It does not mean "is equal to" like in maths.
  • Read it out loud as "name gets Sunny".

This step is called assignment: you assign a value to a variable.

The value can be anything you've met so far

PYTHONedit me
city = "Delhi"
score = 90
price = 19.99
OUTPUT

Text, whole numbers, decimal numbers: a variable can hold all of them. You'll learn about these kinds of values in the last topic of this chapter.

Common beginner doubt: "Can I write "Sunny" = name?" No. The name must always be on the left side of =.

A variable is a labelled box: name = value stores the value under that name.

your turnPick the right idea

What does name = "Sunny" do?

Think about it, then pick one.
your turnFill the gap

Make city hold Delhi

city ? "Delhi" print(city)

It should print: Delhi

Which piece makes this code work?

Printing Variables

To see what's inside a variable, give its name to print(), without quotes:

PYTHONedit me
name = "Sunny"
print(name)
OUTPUT
Sunny

Python looks up name, finds "Sunny" inside, and prints that.

Quotes or no quotes?

This is the most important thing in this lesson:

PYTHONedit me
name = "Sunny"
print(name)
print("name")
OUTPUT
Sunny
name
  • print(name), no quotes: Python uses the variable, and prints its value.
  • print("name"), with quotes: it's just text, so Python prints the word name.

Variables and text together

You already know commas from chapter 2. They work with variables too:

PYTHONedit me
name = "Sunny"
age = 25
print(name, "is", age, "years old.")
OUTPUT
Sunny is 25 years old.

print() puts a space between the items, as always. name and age are replaced by their values, and the text in quotes is shown as it is.

Common beginner doubt: "What if I print a variable that doesn't exist?" Python stops with a NameError, the same error you saw for text without quotes in chapter 2:

PYTHONedit me
print(nmae)
OUTPUT
NameError: name 'nmae' is not defined

A typo in a variable's name is a very common cause of this error.

No quotes: Python prints the value inside. With quotes: it prints the word itself.

your turnPredict the output

What will this print?

name = "Rocky" print("Hi", name)
Your turn! What will this code show on the screen?
your turnType the output

Type what this prints

pet = "Lucky" print("pet")
Read the code line by line, then type the output exactly.

Why Use Variables?

Imagine a program that greets a user:

PYTHONedit me
print("Hello, Sunny!")
print("Sunny, welcome to LivePython.")
OUTPUT
Hello, Sunny!
Sunny, welcome to LivePython.

It works, but only for Sunny. To greet Rocky, you'd have to find and change every Sunny by hand. In a big program, you'd surely miss one.

Now with a variable:

PYTHONedit me
name = "Sunny"
print("Hello,", name)
print(name, "is welcome here.")
OUTPUT
Hello, Sunny
Sunny is welcome here.

To greet Rocky, change one line: name = "Rocky". Try it in the editor above. Everything else updates by itself.

What variables give you

  • Change in one place. The value lives in one spot, and every line that uses it follows.
  • Clear code. price tells you what a number means. 19.99 alone doesn't.
  • Remember results. Store a calculation once, and use it again and again.
  • Programs that react. In the Input chapter, the user will type a name, and your variable will hold it. The same program then greets anyone!

Think of a form with blanks: "Hello, ____!". The variable is the blank. Fill it with a different value, and the same form works for everyone.

Variables let you write a program once, and use it for any value.

your turnPick the right idea

Why is name = "Sunny" better than typing Sunny on every line?

Think about it, then pick one.
your turnPredict the output

What will this print?

city = "Pune" print("I", "live", "in", city, sep="-")
Your turn! What will this code show on the screen?

Using Variables in Calculations

Variables that hold numbers can be used in maths, just like the numbers themselves:

PYTHONedit me
length = 5
width = 3
print(length * width)
OUTPUT
15

Python replaces length with 5 and width with 3, then calculates 5 * 3.

Store the result in a new variable

You can save a result too, and give it a name that says what it means:

PYTHONedit me
price = 20
quantity = 3
total = price * quantity
print("Total:", total)
OUTPUT
Total: 60

Read the third line as "total gets price times quantity". Python works out the right side first (20 * 3), then stores 60 in total.

Why this is powerful

Change quantity to 5 and run it again. total is worked out again from the new values, so the answer is always right. That's how real programs work: shopping carts, games, bills and reports all keep values in variables and calculate with them.

CodeWhat Python does
total = price * quantitymultiplies the two values, stores the result
average = total / 2divides, stores the result (a decimal)
left = 10 - usedsubtracts, stores the result

Common beginner doubt: "Does total change by itself if I change price later?" No. total keeps the value it got when its line ran. Run the calculation again to update it.

Variables in maths are replaced by their values, and the result can go into a new variable.

your turnType the output

Type what this prints

price = 20 qty = 3 print(price * qty)
Read the code line by line, then type the output exactly.
your turnOrder the lines

Put the lines in order to print the area

  1. print(area)
  2. width = 5
  3. length = 4
  4. area = length * width
These lines are mixed up. Put them back in order, then press Check.

Practice: Variables

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 16.Python Program to Create and Print a VariableEasySolve
  2. 21.Python Program to Add Two VariablesEasySolve
  3. 22.Python Program to Find the Area of a Rectangle Using VariablesMediumSolve