LearnFrenzy
Sign in Take a free test

Python Programming · Topic 2 of 25

Variables and Data Types Questions and Concepts

  • 4 exercises
  • 50 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Variables and Data Types · Study material

In Python a variable is a name that refers to an object. You never declare a type: the object carries its own type, and the same name can point to an int now and a string later. That model explains most "tricky" Python questions – why changing one list changes another, why strings cannot be edited in place, why True + True is 2 and why 0.1 + 0.2 is not 0.3. This topic covers variables and assignment, the built-in data types (int, float, complex, bool, str, None), type conversion, truthiness and mutability, followed by 50 practice questions run on Python 3.

On this page

  • Variables are names bound to objects (id, is, aliasing)
  • Multiple, chained, starred and augmented assignment
  • Numbers: int, float, complex
  • bool, None and truthiness
  • Type conversion and rounding
  • Mutable vs immutable types

Variables are names, not boxes

An assignment such as marks = [78, 85] creates a list object and binds the name marks to it. backup = marks binds a second name to the same object – nothing is copied. id(x) gives an object's identity, and a is b asks whether two names refer to the same object (use == to compare values). Python is dynamically typed (names have no type) but strongly typed (it will not silently add a str to an int).

# A variable is a NAME that refers to an object; assignment never copies the object
marks = [78, 85]
backup = marks                 # a second name for the SAME list
backup.append(91)

print(marks)                   # the change is visible through both names
print(backup is marks)         # is: the same object?
print(id(marks) == id(backup))

score = 50
score = "fifty"                # dynamic typing: the name now refers to a str
print(type(score).__name__)

Output

[78, 85, 91]
True
True
str

Assignment forms

Several names can be assigned at once by unpacking a tuple or list; a *name target collects the leftovers into a list. Chained assignment gives one object several names. Augmented operators (+=, -=, *=, //=, **= …) update a variable using its current value.

x, y, z = 1, 2.5, "three"        # multiple assignment (tuple unpacking)
a = b = c = 0                    # chained assignment: one object, three names
first, *rest = [10, 20, 30, 40]  # starred target collects the rest in a list

x, y = y, x                      # swap
print(x, y, z)
print(a, b, c)
print(first, rest)

count = 10
count += 5                       # augmented assignment: count = count + 5
count //= 4
print(count)

Output

2.5 1 three
0 0 0
10 [20, 30, 40]
3

Numbers: int, float and complex

TypeExamplesNotes
int42, -7, 0xFF, 0b101, 1_000arbitrary precision – never overflows
float3.14, 1e-3, float("inf")64-bit IEEE 754 double; binary fractions are approximate
complex3 + 4j, complex(1, -2).real, .imag, abs() gives the magnitude

/ always returns a float; // floors. Integers grow as large as memory allows, so 2 ** 1000 just works.

# int: no overflow – as many digits as memory allows
print(2 ** 64, len(str(2 ** 1000)))
print(0b1010, 0o17, 0xFF, 1_000_000)          # binary, octal, hex, underscores

# float: 64-bit IEEE 754, about 15–17 significant digits
print(0.1 + 0.2, 1e3, 2.5e-3)
print(float("inf") > 10 ** 300, 7 / 2, 7 // 2)

# complex: real + imaginary part, written with j
z = 3 + 4j
print(z.real, z.imag, abs(z))

Output

18446744073709551616 302
10 15 255 1000000
0.30000000000000004 1000.0 0.0025
True 3.5 3
3.0 4.0 5.0

bool, None and truthiness

bool has two values, True and False, and is a subclass of int (so True == 1). Every object has a truth value used by if and while: falsy values are False, None, numeric zero (0, 0.0, 0j) and empty containers ("", [], (), {}, set()); everything else is truthy – including " ", [0] and the string "False". None is the single object of type NoneType; test it with is None.

# bool is a subclass of int: True == 1, False == 0
print(True + True, True * 10, isinstance(True, int))

# Truthiness: zero, empty and None are False; everything else is True
for value in [0, 0.0, "", " ", [], [0], None, "False"]:
    print(repr(value), bool(value))

result = None                      # None means "no value yet"
print(result is None, type(result).__name__)

Output

2 10 True
0 False
0.0 False
'' False
' ' True
[] False
[0] True
None False
'False' True
True NoneType

Type conversion

Constructors convert between types: int(), float(), str(), bool(), list(), tuple(), set(). int() on a float truncates toward zero; on a string it needs a whole number (int("12.5") is a ValueError) and accepts a base. round() uses round half to even ("banker's rounding"), so round(2.5) is 2.

print(int("42") + 1, float("3.5") * 2, str(7) + "7")
print(int(9.99), int(-9.99))            # int() truncates toward zero
print(round(2.5), round(3.5), round(2.675, 2))   # round half to even; 2.675 is really 2.67499…
print(int("ff", 16), int("101", 2), hex(255), bin(10), oct(8))
print(float("1e-3"), int(True), bool(1), bool(-1))
print(list("abc"), tuple([1, 2]), set("aabb") == {"a", "b"})

Output

43 7.0 77
9 -9
2 4 2.67
255 5 0xff 0b1010 0o10
0.001 1 True True
['a', 'b', 'c'] (1, 2) True

Mutable vs immutable

Immutable objects (int, float, bool, str, tuple, frozenset, None) can never change; an operation that seems to change one builds a new object and rebinds the name. Mutable objects (list, dict, set, most user classes) change in place, and the change is seen through every name bound to them. Use .copy(), list(x) or slicing x[:] for an independent shallow copy.

# Immutable: int, float, bool, str, tuple, frozenset – "changing" makes a NEW object
s = "data"
t = s
t += "base"                     # builds a new string; s is untouched
print(s, t)

# Mutable: list, dict, set – changed in place, visible through every name
a = [1, 2]
b = a
b += [3]                        # += on a list extends it IN PLACE
print(a, b)

c = a.copy()                    # an independent (shallow) copy
c.append(4)
print(a, c)

Output

data database
[1, 2, 3] [1, 2, 3]
[1, 2, 3] [1, 2, 3, 4]

Common mistakes

  • "Copying" a list with = – both names share one list.
  • Comparing floats with == – use math.isclose(), or Decimal for money.
  • bool("False") is True – any non-empty string is truthy.
  • int("12.5") raises ValueError – use int(float(s)) if you really mean it.
  • Naming a variable str, list, sum or id – hides the built-in.
  • Using is to compare numbers or strings – it compares identity, not value.

Key points to remember

  • Variables are names bound to objects; = never copies.
  • Objects have types; names do not.
  • int is unlimited; float is an approximate binary double.
  • bool is a subclass of int; None is tested with is None.
  • Zero, empty and None are falsy; everything else is truthy.
  • round() rounds halves to the even neighbour.
  • str and tuple are immutable; list, dict and set are mutable.

Frequently asked questions

Does Python have constants?

No enforced constants. By convention an UPPER_CASE name (MAX_MARKS = 100) must not be reassigned; type checkers can enforce it with typing.Final.

Does Python have a char or a long type?

No. A character is a str of length 1, and int already has unlimited size (Python 2's long was merged into int).

What are type hints?

Optional annotations such as age: int = 21. Python ignores them at run time; tools like mypy and IDEs use them to find bugs.

Where can I learn more?

Read Python Variables and Python Data Types in the Python tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Python Programming

Why it matters

  • Python is the most popular first language and the default for data science, AI, automation and scripting
  • Campus coding rounds and technical interviews increasingly allow – or prefer – Python
  • "Predict the output" questions on lists, strings, dictionaries and mutable defaults are a favourite in written tests
  • Clean Python with comprehensions, generators and OOP is what product companies expect from freshers

Who it is for

  • School students (Class 11–12 computer science with Python) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, coding tests and Python interviews
  • Anyone moving into data science, AI or automation who needs strong Python fundamentals

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs: syntax errors, runtime exceptions and logical bugs
  • Coding problems with solutions and real output, every one run on Python 3 – open any example in the online Python compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture tests
  • Python interviews for freshers
  • Data science interviews
  • CBSE / university practicals
  • GATE CS

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, errors, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links