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”.

Python MCQ Questions and Answers: Free Interview Mock Tests

Prepare for your Python interview with free, timed Python MCQ tests written for QA engineers and developers. Pick a topic and answer 20 random questions in 20 minutes from a 200-question bank. You get your score, every correct answer with an explanation, a score split into QA and developer questions, and an interview readiness score that grows as you practise.

How the Python MCQ tests work

  • 15 interview topics from Python basics to pytest, OOP and pandas. New topics open as their question banks are published.
  • 20 questions per test, 200 per topic: questions you have not seen come first, so about 10 attempts cover a whole topic.
  • 20-minute timer and live progress bar: see how many questions you have answered; the test submits itself when time runs out.
  • Real interview questions: predict-the-output code, common bugs, best practice and test-automation scenarios. Every code question was run on Python 3 to confirm the answer.
  • Instant review: pass mark 70%, the correct answer and a short explanation for every question, and a link to the lesson to revise.
  • Your Python learning progress: topics mastered, topics still to practise and what to study next, saved in your browser.

How interview readiness is calculated

Readiness combines how much you have practised with how well you score: readiness = (tests completed out of 20) × (accuracy). Accuracy is the average of your last three scores in each available topic; a topic you have not tried counts as 0%.

  • 0 to 39%: Getting started
  • 40 to 69%: Developing
  • 70 to 84%: Almost ready
  • 85 to 100%: Interview ready

Python MCQ topics

Learn first, then test yourself

Each test links to the matching lesson in the free Python tutorial. Practise coding with 1,100+ Python practice programs, and if you work in test automation, continue with the Playwright with Python & pytest course and its mock interview.

Frequently asked questions

Are these Python MCQ tests free?

Yes. Every test is free and needs no sign-up. Your results and progress are stored only in your own browser.

Who are these Python MCQs for?

For QA and test automation engineers and for developers preparing for Python interviews. Each question is tagged as a QA or developer question, and your result shows your score in both.

How many questions are in each Python MCQ test?

Each test has 20 multiple-choice questions drawn at random from a 200-question bank for that topic, with a 20-minute time limit and a 70% pass mark.

Are the answers correct?

Every predict-the-output question was executed on Python 3 and its answer is the real output. Each question also has an explanation, so you learn why the answer is right.

Where can I learn the topics before testing?

Every topic links to its lesson in the free sqatools Python tutorial, and the result page shows a “Revise the lesson” button when you do not pass.

Will my progress be saved?

Progress is saved in your browser’s local storage on this device. Clearing site data or switching browsers starts a fresh history.

1. Python Variable Tutorial: A Comprehensive Guide

Python Variable:

Introduction:
Variables are an important concept in any programming language, including Python. In simple language, a variable is a named location in memory that stores a value. In Python, you can use variables to store any type of data, including numbers, strings, and even complex data structures like lists and dictionaries.

Creating Variables in Python:

To create a variable in Python, you need to give it a name and assign a value to it. Here’s an example:
Name = “ Omkar “
Age = 25
Profession = “Software Engineer “
In the example above, we created three variables: Name, Age, and Profession.
The name variable is a string.
The age variable is an integer.
The Profession variable is also a string.

 

Python Variable Naming Rules:

When creating variables in Python, there are a few rules that you need to follow:
1. Variable names must start with a letter or underscore (_), followed by any combination of letters, digits, and underscores.
2. Variable names are case-sensitive, which means name and Name are two different variables.
3. A variable name cannot start with a number.
4. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).

Python Variable Types:

Python Variable types:
1. Numbers – Consists of integers, floating-point numbers, and complex numbers.
2. Strings – Consists of characters in quotes.
3. Booleans – Consists of True or False values.
4. Lists – Consists of ordered sequences of elements.
5. Tuples – Consists of ordered, immutable sequences of elements.
6. Sets – Consists of unordered collections of unique elements.
7. Dictionaries – Consists of unordered collections of key-value pairs.

Checking types of the variable:
First, we will create some Python variable.
Name = “ Omkar “
Age = 25
Height = 5.8 ft

To check the type of the variable use the type() function.
print(type(Name)) #Output: <class ‘str’>
print(type(Age)) #Output: <class ‘int’>
print(type(Height)) #Output: <class ‘float’>

Python variable assignment types:

Value Assignment:

To assign the value to a Python variable use equal sign ( = ).
Example:
A = 10
We can also assign the same value to multiple Python variables.
A = B = C = 10

Multiple value assignment:

We can assign different values to different Python variables at the same time. We separate the variables and their values by ‘ , ‘.
Example:
a, b, c = 40, 50, 60
Here,
Value of variable a is 40 , b is 50 and c is 60.

Python Variable scope:

Scope of Variable:

In Python, the scope of a variable determines where in the code the variable can be accessed and used. The scope of a variable is defined by where the variable is created and assigned a value.
There are two types of Python variable scopes: global scope and local scope.

1. Global Scope: Variables created outside of any function or class have a global scope. This means that they can be accessed and modified from anywhere in the code, including within functions and classes.
Example:
number = 100 # global Python variable

def print_number():
print(number) # accessing global variable

def modify_number():
global number # declaring number as global variable
number = 200 # modifying global variable

print_number() # Output: 100
modify_number()
print_number() # Output: 200
In the example above, the variable number is declared outside of any function, so it has a global scope. The function print_number() can access and print the value of the number, and the function modify_number() can modify the value of the number by declaring it as a global variable using the global keyword.

2. Local Scope: Variables created inside a function or class have a local scope. This means that they can only be accessed and modified within that function or class.
Example:
def my_function():
number = 100 # local Python variable
print(number) # accessing local variable

my_function() # Output: 100
print(number) # NameError: name ‘number’ is not defined

Basic Mathematical operations using variables:

Creating variables and assigning value to them:
a, b = 10 , 20

Performing operations and printing output:
print(a+b) #Output: 30
print(a-b) #Output: -10
print(a*b) #Output: 200
print(a/b) #Output: 0.5

Variables are an important concept in Python programming language. They allow you to store and manipulate data in your code and are important for writing effective programs. By understanding how to create, name, and use variables, you can write Python code that is easy to read and maintain.

Python Loop Programs with Solutions

Python Practice › Loop Programs

Python Loop Programs with Solutions

90 programs75 easy14 medium1 hard

90 loop programs from counting and digit tricks to star and letter patterns. They practise for, while, range(), break, continue and nested loops; every solution is explained and shows its real output.

Before you start

Read the Loops: for & while lesson first if the topic is new to you.

All programs

Python List Programs with Solutions

Python Practice › List Programs

Python List Programs with Solutions

100 programs93 easy7 medium0 hard

100 list programs, from sums and reversing to sublists, de-duplication and run-length decoding. Lists are Python’s most used data structure, and these exercises appear in most Python interviews. Every solution is explained and shows its real output.

Before you start

Read the Lists and List Comprehension lesson first if the topic is new to you.

All programs