Python Variables

Python Tutorial › Basics › Variables

Python Variables

BeginnerLesson 8 of 4710 min read10 runnable examples

A variable is a name that refers to a value, so you can use the value later, change it, and make your code readable. In Python you create a variable simply by assigning to it.

In this lesson
  • Create and update variables
  • Follow Python’s naming rules
  • Assign several variables at once
  • Understand that names point to objects

Create a variable

Write a name, an equals sign and a value. Python creates the variable the first time you assign to it. There is no var, let or type declaration.

Python
browser = "chromium"timeout = 30headless = True print(browser, timeout, headless)
Output
chromium 30 True
Note

= means assign, not “is equal to”. timeout = 30 stores 30 under the name timeout. To compare two values you use ==, covered in Operators.

Change a variable

Assigning again replaces the old value. The new value can even be a different type, because Python variables do not have a fixed type; the value does.

Python
count = 1count = count + 1      # read the old value, add 1, store the resultcount += 1             # the same thing, written shorterprint(count) count = "three"        # now it holds a stringprint(count, type(count))
Output
3
three <class 'str'>

Naming rules

RuleValidInvalid
Letters, digits and underscores onlyuser_2user-2, user 2
Cannot start with a digit_2nd, second2nd
Cannot be a keywordclass_nameclass, for
Case-sensitivetotal and Total are different
Python
user-name = "asha"
Output
  File "main.py", line 1
    user-name = "asha"
    ^^^^^^^^^
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?

Naming conventions

These are not enforced by Python but every Python developer follows them (they come from the PEP 8 style guide):

  • snake_case for variables and functions: max_retries, page_title.
  • UPPER_CASE for constants that should not change: BASE_URL, MAX_RETRIES.
  • PascalCase for classes: LoginPage.
  • Use names that say what the value means: retries beats r, price_in_rupees beats p.

Assign several variables at once

Python
x, y, z = 10, 20, 30           # one value per nameprint(x, y, z) a = b = c = 0                  # the same value to every nameprint(a, b, c) first, *rest = [1, 2, 3, 4]    # * collects the leftovers into a listprint(first, rest)
Output
10 20 30
0 0 0
1 [2, 3, 4]

The number of names on the left must match the number of values, unless one name has *:

Python
x, y = 1, 2, 3
Output
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    x, y = 1, 2, 3
    ^^^^
ValueError: too many values to unpack (expected 2, got 3)

Swap two variables

Many languages need a temporary variable to swap. Python swaps in one line:

Python
a = 10b = 20a, b = b, aprint("a =", a, "b =", b)
Output
a = 20 b = 10

Variables are names for objects

A variable does not contain the value; it refers to an object in memory. Two names can refer to the same object. id() shows an object’s identity and is checks whether two names refer to the same object.

Python
scores = [90, 85]backup = scores           # a second name for the same listbackup.append(70) print(scores)print(backup is scores)
Output
[90, 85, 70]
True

This is why changing a list through one name shows up through the other. Numbers and strings cannot be changed in place, so for them this never surprises you:

Python
a = 5b = ab = b + 1      # creates a new int object; a still refers to 5print(a, b)
Output
5 6
Tip

The Lists lesson shows how to make a real copy with .copy() when you need one.

Delete a variable

del removes a name. Using the name afterwards raises NameError.

Python
temp = 42del tempprint(temp)
Output
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(temp)
          ^^^^
NameError: name 'temp' is not defined

Constants

Python has no true constants. By convention a name in UPPER_CASE tells other developers “do not change this”:

Python
BASE_URL = "https://sqatools.in"MAX_RETRIES = 3 for attempt in range(1, MAX_RETRIES + 1):    print(f"Attempt {attempt} of {MAX_RETRIES} on {BASE_URL}")
Output
Attempt 1 of 3 on https://sqatools.in
Attempt 2 of 3 on https://sqatools.in
Attempt 3 of 3 on https://sqatools.in

Check your understanding

Predict the output

a = 3b = aa = a * 2print(a, b)

Quick quiz

1. Which is a valid Python variable name?

2. What does x, y = y, x do?

3. What is the convention for a value that should never change?

4. What does first, *rest = [5, 6, 7] put in rest?

Exercise: shopping cart total

Store the item price, quantity and discount percentage in well-named variables, then print the final amount.

Input
price = 250, quantity = 4, discount = 10%
Expected output
Subtotal: 1000
Final amount: 900.0
Hint 1

The discount amount is subtotal * discount_percent / 100.

Program Practice

Python variables FAQ

Do I need to declare a variable type in Python?

No. Python works out the type from the value you assign. n = 5 is an int and n = "5" is a str. You can add optional type hints, such as n: int = 5, for readability.

How do I swap two variables in Python?

Use tuple unpacking: a, b = b, a. No temporary variable is needed.

What is the difference between = and ==?

= assigns a value to a name. == compares two values and returns True or False.

Can a variable name start with an underscore?

Yes. A single leading underscore, as in _cache, is a convention meaning “internal, do not use from outside”.

Dog inherits from Animal

Python Practice › OOP Programs › Program 48

Dog inherits from Animal

EasyOOP Programs · 48 of 48

Create Dog (inherits Animal) with breed and weight, and a method to print all details.

Output
Bruno is brown, a Labrador weighing 28 kg

Approach

  1. Override show and reuse the parent’s message with super().

Solution

Python
class Animal:    def __init__(self, name, color):        self.name, self.color = name, color     def show(self):        return f"{self.name} is {self.color}" class Dog(Animal):    def __init__(self, name, color, breed, weight):        super().__init__(name, color)        self.breed, self.weight = breed, weight     def show(self):        return super().show() + f", a {self.breed} weighing {self.weight} kg" print(Dog("Bruno", "brown", "Labrador", 28).show())
Output
Bruno is brown, a Labrador weighing 28 kg

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Animal class

Python Practice › OOP Programs › Program 47

Animal class

EasyOOP Programs · 47 of 48

Create Animal with name and colour and a method to print them.

Output
Bruno is brown

Approach

  1. Store and print.

Solution

Python
class Animal:    def __init__(self, name, color):        self.name, self.color = name, color     def show(self):        print(f"{self.name} is {self.color}") Animal("Bruno", "brown").show()
Output
Bruno is brown

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

ShoppingCart class

Python Practice › OOP Programs › Program 46

ShoppingCart class

EasyOOP Programs · 46 of 48

Create ShoppingCart with items and total cost, and methods to add and remove items and calculate the total.

Output
{'pen': (10, 5)} 50

Approach

  1. Store items in a dict of name -> (price, quantity).

Solution

Python
class ShoppingCart:    def __init__(self):        self.items = {}     def add(self, name, price, qty=1):        old_qty = self.items.get(name, (price, 0))[1]        self.items[name] = (price, old_qty + qty)     def remove(self, name):        self.items.pop(name, None)     def total_cost(self):        return sum(price * qty for price, qty in self.items.values()) cart = ShoppingCart()cart.add("pen", 10, 3)cart.add("bag", 650)cart.add("pen", 10, 2)cart.remove("bag")print(cart.items, cart.total_cost())
Output
{'pen': (10, 5)} 50

Line by line

Lines 5-7

Adding an item again increases its quantity instead of replacing it.

Lines 12-13

The total is calculated when needed, so it is always up to date.

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

EBook with open and close

Python Practice › OOP Programs › Program 45

EBook with open and close

EasyOOP Programs · 45 of 48

Create EBook (inherits Book) with file_size and format, and methods to open and close the book.

Output
Opened Python Basics (PDF, 3.4 MB)
Closed Python Basics

Approach

  1. Track whether the e-book is open.

Solution

Python
class Book:    def __init__(self, title, author, pages):        self.title, self.author, self.pages = title, author, pages class EBook(Book):    def __init__(self, title, author, pages, file_size_mb, fmt):        super().__init__(title, author, pages)        self.file_size_mb, self.format = file_size_mb, fmt        self.is_open = False     def open(self):        self.is_open = True        return f"Opened {self.title} ({self.format}, {self.file_size_mb} MB)"     def close(self):        self.is_open = False        return f"Closed {self.title}" e = EBook("Python Basics", "SQA Tools", 220, 3.4, "PDF")print(e.open())print(e.close())
Output
Opened Python Basics (PDF, 3.4 MB)
Closed Python Basics

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Book class

Python Practice › OOP Programs › Program 44

Book class

EasyOOP Programs · 44 of 48

Create Book with title, author and pages, with getter methods.

Output
Wings of Fire | A. P. J. Abdul Kalam | 180

Approach

  1. One method per attribute.

Solution

Python
class Book:    def __init__(self, title, author, pages):        self.title, self.author, self.pages = title, author, pages     def get_title(self):        return self.title     def get_author(self):        return self.author     def get_pages(self):        return self.pages b = Book("Wings of Fire", "A. P. J. Abdul Kalam", 180)print(b.get_title(), "|", b.get_author(), "|", b.get_pages())
Output
Wings of Fire | A. P. J. Abdul Kalam | 180
Tip

In idiomatic Python you would usually read b.title directly and add @property only when extra logic is needed.

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Laptop class

Python Practice › OOP Programs › Program 43

Laptop class

EasyOOP Programs · 43 of 48

Create Laptop with brand, model and storage, with methods to start up, shut down and check storage.

Output
Inspiron 15 started True
512 GB
Inspiron 15 shut down False

Approach

  1. Keep an is_on flag.

Solution

Python
class Laptop:    def __init__(self, brand, model, storage_gb):        self.brand, self.model, self.storage_gb = brand, model, storage_gb        self.is_on = False     def start(self):        self.is_on = True        return f"{self.model} started"     def shutdown(self):        self.is_on = False        return f"{self.model} shut down"     def storage(self):        return f"{self.storage_gb} GB" lp = Laptop("Dell", "Inspiron 15", 512)print(lp.start(), lp.is_on)print(lp.storage())print(lp.shutdown(), lp.is_on)
Output
Inspiron 15 started True
512 GB
Inspiron 15 shut down False

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Phone class

Python Practice › OOP Programs › Program 42

Phone class

EasyOOP Programs · 42 of 48

Create Phone with brand, model and storage, with methods to call, text and check storage.

Output
Calling 98765 43210 from Galaxy A55
Text to 98765 43210: Running late
81 GB free

Approach

  1. Track used storage and report what is free.

Solution

Python
class Phone:    def __init__(self, brand, model, storage_gb):        self.brand, self.model, self.storage_gb = brand, model, storage_gb        self.used_gb = 0     def call(self, number):        return f"Calling {number} from {self.model}"     def text(self, number, message):        return f"Text to {number}: {message}"     def free_storage(self):        return self.storage_gb - self.used_gb p = Phone("Samsung", "Galaxy A55", 128)p.used_gb = 47print(p.call("98765 43210"))print(p.text("98765 43210", "Running late"))print(p.free_storage(), "GB free")
Output
Calling 98765 43210 from Galaxy A55
Text to 98765 43210: Running late
81 GB free

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

VIPCustomer with credit

Python Practice › OOP Programs › Program 41

VIPCustomer with credit

EasyOOP Programs · 41 of 48

Create VIPCustomer (inherits Customer) with credit_limit and discount_rate, and a method for available credit.

Output
12000 850.0

Approach

  1. Available credit = credit limit + balance.

Solution

Python
class Customer:    def __init__(self, name, balance=0):        self.name, self.balance = name, balance class VIPCustomer(Customer):    def __init__(self, name, balance, credit_limit, discount_rate):        super().__init__(name, balance)        self.credit_limit, self.discount_rate = credit_limit, discount_rate     def available_credit(self):        return self.balance + self.credit_limit     def price_after_discount(self, price):        return price * (1 - self.discount_rate / 100) v = VIPCustomer("Meena", 2000, 10000, 15)print(v.available_credit(), v.price_after_discount(1000))
Output
12000 850.0

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Customer with deposit and withdraw

Python Practice › OOP Programs › Program 40

Customer with deposit and withdraw

EasyOOP Programs · 40 of 48

Create Customer with name and balance and methods to deposit and withdraw.

Output
750 Insufficient balance 650

Approach

  1. Return a message from each method.

Solution

Python
class Customer:    def __init__(self, name, balance=0):        self.name, self.balance = name, balance     def deposit(self, amount):        self.balance += amount        return self.balance     def withdraw(self, amount):        if amount > self.balance:            return "Insufficient balance"        self.balance -= amount        return self.balance c = Customer("Asha", 500)print(c.deposit(250), c.withdraw(1000), c.withdraw(100))
Output
750 Insufficient balance 650

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs