Skip to content
CodeKruPro

Your language · Python

Basics: types, variables and operators

Data types, variables, operators, type conversion and how values are stored.

Learn: Python basics: types, variables and operators8 minute read

Basics questions check how Python stores values and how its operators behave. Python looks simple, so interviewers use these questions to see whether you know the details: what a variable really is, what is means and why round(2.5) gives 2. Each of these has caused real test failures, such as a price check that fails because of a float (a number with a decimal point) or a default value that hides a 0.

Step 1: everything is an object

Python has no primitive types (simple values that are not objects, as in Java). Numbers, strings, functions and even None are objects, and every object has a type. The core built-in types are:

  • numbers: int (no size limit, so it never overflows) and float (a 64-bit decimal; a bit is one 0 or 1 in memory). bool is a kind of int, so True + True is 2;
  • text and data: str for text and bytes for raw data such as a downloaded file;
  • collections: list (an ordered group you can change), tuple (an ordered group you cannot change), dict (key and value pairs) and set (unique values); see Collections;
  • None: the one object that means "no value".

Some types are immutable, which means an object can never change after it is made: int, float, bool, str, tuple, frozenset (a set that cannot change) and bytes. Others are mutable and change in place: list, dict and set. Many interview questions come back to this one fact.

Step 2: variables are names

A Python variable is a name bound to an object. b = a gives the same object a second name; it never copies. Assigning again, as in a = 5, moves the name to another object.

Python is dynamically typed: the type belongs to the object, so one name can point at an int now and a string later. It is also strongly typed: it does not convert types silently, so "1" + 1 raises TypeError (an error Python raises while running; see Exceptions). You convert on purpose with int(), float() and str(). Type hints such as def total(prices: list[float]) -> float help readers and tools like mypy (a program that checks types before you run the code), but Python itself does not check them when the code runs.

Step 3: is versus ==

== compares values. is checks whether two names point at the very same object (identity). Use is only for None and similar single objects. For numbers and strings, whether equal values share one object is a detail of CPython (the standard interpreter, the program that runs Python code), so is can give different answers for different values.

a = [1, 2]
b = [1, 2]
c = a
print(a == b, a is b, a is c)

c.append(3)
print(a)

x = int("1000")
y = int("1000")
print(x == y, x is y)

value = None
print(value is None)
True False True
[1, 2, 3]
True False
True

Changing the list through c changed a, because both names point at one list.

Step 4: numbers and operators

  • / always returns a float: 8 / 2 is 4.0.
  • // is floor division. It rounds down, toward minus infinity, so -7 // 2 is -4 (Java gives -3).
  • % gives the remainder and matches //, so the result takes the sign of the divisor (the number you divide by): -7 % 2 is 1.
  • ** is power. There is no ++; write i += 1.
  • round() sends a half to the even neighbour: round(2.5) is 2 and round(3.5) is 4. int(3.99) cuts toward zero: 3.
import math

print(7 / 2, 7 // 2, -7 // 2, -7 % 2)
print(round(2.5), round(3.5), int(-3.99))
print(0.1 + 0.2 == 0.3, math.isclose(0.1 + 0.2, 0.3))
print(2 ** 64)
print(True + True, isinstance(True, int))

price = float("1,299.50".replace(",", ""))
print(price * 2)
try:
    print("Total: " + 10)
except TypeError as e:
    print("TypeError:", e)
3.5 3 -4 1
2 4 -3
False True
18446744073709551616
2 True
2599.0
TypeError: can only concatenate str (not "int") to str

Floats are stored in binary (base 2), so 0.1 + 0.2 is not exactly 0.3. In tests compare them with math.isclose or pytest.approx (pytest is the usual Python test tool).

Step 5: truthiness and running a file

Any object can go in an if. This is called truthiness: every object counts as true or false. These count as false: False, None, zero, and empty containers ("", [], {}, set()). Everything else is true, even the string "False". So name = value or "guest" is a common default, but it also replaces a valid 0 or empty string. In that case test if value is None.

Python runs a file from top to bottom and needs no main method. A module is just a Python file, and importing it runs its top-level code. This check runs code only when the file is started directly, not when pytest or another module imports it:

def main():
    print("running smoke checks")

if __name__ == "__main__":
    main()

For fixed lists such as browsers or environments, use enum.Enum. To turn objects into text and back (serialisation), use the json module, which is what API tests (tests that call a web service and check its answers) rely on.

How to answer in an interview

State the rule, then show it with one short line. For "how are Python variables different from Java's?" say: "A Python variable is a name bound to an object. The type lives on the object, so the language is dynamically typed, but it is strongly typed because it never mixes types silently: "1" + 1 is a TypeError." For output questions, say the type of each result as you go: "/ always gives a float, so 8 / 2 is 4.0."

Common mistakes

  • Using is to compare numbers or strings. Use ==; keep is for None.
  • Expecting -7 // 2 to be -3, or round(2.5) to be 3.
  • Comparing floats with ==.
  • Thinking type hints are checked when the code runs.

Recap

Everything in Python is an object, and a variable is a name for one. Know which types are mutable. Use == for values and is None for missing values. Remember that / gives a float, // rounds down and round sends halves to even.

11 questions0/11 solved

StatusQuestionDifficultyAsked in
Not startedWhich built-in types are immutable?EasyAsked in: TCS
Not startedPython data types and how variables workEasyAsked in: Infosys, TCS, Tech Mahindra
Pro+/ versus // versus %Easy-Medium
Pro+is versus ==Easy-MediumAsked in: Capgemini, Infosys
Pro+Which values are falsy?Easy-Medium
Pro+Rounding, floats and big integersMedium
Pro+What does if __name__ == "__main__" do?Easy
Pro+Are type hints checked at run time?Easy-Medium
Pro+Enums in Python and when to use themEasy-MediumAsked in: Wipro
Pro+Serialisation in Python: json and pickleMediumAsked in: Capgemini, Wipro
Pro+Which language do you automate in, and why?Easy
Not startedNot startedIn progressIn progressSolvedSolvedPro+Pro+

The first 2 questions of each topic are free. Pro+ opens every question.

Back to the plan