ЁЯТ╗
тМия╕П
ЁЯЦ▒я╕П
ЁЯЦея╕П
ЁЯТ╛
тЖР Back to Dashboard
Font Size:

1. Introduction

Every program works on data. To work on data effectively, a programmer must understand the types of data that Python can store, how they can be converted from one form to another, and which functions are available to operate on them. Data handling in Python is built around the concept of data types, which define the kind of value a variable holds and the operations that can be performed on it.

Python treats everything as an object, and every object has a type. This chapter explores the built-in data types in detail, starting with the fundamental types: integers, floats, complex numbers, strings, and booleans. We will learn how to check the type of a value using the type() function, how to convert between types using functions like int(), float(), str(), and bool(), and how to write expressions using these values.

We will also look at operators in depth, including arithmetic, relational, logical, assignment, identity, and membership operators, along with the precedence rules that decide the order in which operators are evaluated. Understanding precedence and associativity is essential because it determines the result of complex expressions. By the end of this chapter, you will be able to write correct expressions, convert data safely between types, and predict the output of expression-based questions.

2. Understanding Data Types

Python's built-in data types can be grouped as:

Every value in Python belongs to one of these types, and the type determines its behaviour. We can verify the type with the built-in function type().

print(type(10))
print(type(2.5))
print(type("hello"))
print(type(True))

Output:

<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>

3. Number Types

3.1 Integer (int)

Integers are positive or negative whole numbers without a fractional part. There is no upper limit on the size of an integer in Python 3, which makes it very convenient for large calculations.

a = 100
b = -25
print(type(a))

3.2 Float (float)

Floats represent numbers with a decimal point and can also be written in scientific notation using e.

x = 3.14
y = 1.5e3
print(y)

Output: 1500.0. The value 1.5e3 means 1.5 multiplied by 10 to the power 3.

3.3 Complex (complex)

Complex numbers are written in the form a + bj, where a is the real part, b is the imaginary part, and j represents the square root of -1.

z = 3 + 4j
print(z.real)
print(z.imag)

Output:

3.0
4.0

4. Strings

A string is a sequence of characters enclosed in single quotes, double quotes, or triple quotes. Triple quotes allow multi-line strings. Strings are immutable, which means their content cannot be changed after creation.

name = "Aarav"
greeting = 'Hello'
multi = """This is
a multi-line string"""

Important string properties: - Indexing: Characters are accessed using indices starting from 0. name[0] gives 'A'. - Slicing: A substring is extracted using [start:end]. name[1:4] gives 'ara'. - Concatenation: Strings are joined with +. - Repetition: * repeats a string. "ab" * 3 gives "ababab". - len(): Returns the number of characters in the string.

word = "Python"
print(word[0])
print(word[1:4])
print(len(word))
print(word + " Rocks")
print(word * 2)

Output:

P
yth
6
Python Rocks
PythonPython

5. Boolean Data Type

The boolean type bool has only two values: True and False. Booleans are the result of relational and logical operations and are used heavily in decision making.

print(10 > 5)
print(10 == 5)
print(bool(0))
print(bool("Hello"))

Output:

True
False
False
True

Notice that bool(0) is False but bool("Hello") is True, because an empty or zero value is considered falsy while non-empty values are truthy.

6. Type Conversion (Typecasting)

Sometimes we need to change the type of a value. Python provides built-in functions for this:

print(int(3.99))
print(int("25"))
print(float("3.5"))
print(str(100))
print(bool(1))

Output:

3
25
3.5
100
True

A point to remember: int("3.5") will raise a ValueError because an integer cannot be created directly from a string containing a decimal point; you must convert to float first.

7. Operators in Detail

7.1 Arithmetic Operators

+, -, *, /, //, %, **. While / always returns a float, // floors the result and % returns the remainder.

7.2 Relational Operators

<, >, <=, >=, ==, != compare two values and return True or False.

7.3 Logical Operators

and, or, not combine boolean values. and returns the first falsy operand or the last operand if all are truthy.

7.4 Assignment Operators

=, +=, -=, *=, /=, %=, //=, **=. The expression x += 5 is equivalent to x = x + 5.

7.5 Identity Operators

is and is not check whether two variables refer to the same object in memory, not whether their values are equal.

7.6 Membership Operators

in and not in check whether a value exists inside a sequence such as a string, list, or tuple.

8. Precedence and Associativity

When an expression contains many operators, Python evaluates them according to precedence. From highest to lowest (simplified):

  1. Parentheses ( )
  2. Exponentiation **
  3. Unary operators +x, -x, not
  4. *, /, //, %
  5. +, -
  6. Relational operators <, >, ==, etc.
  7. not
  8. and
  9. or
print(2 + 3 * 4)
print((2 + 3) * 4)
print(10 - 4 + 2)

Output:

14
20
8

Because * has higher precedence than +, 2 + 3 * 4 is evaluated as 2 + 12 = 14. Parentheses override precedence. Addition and subtraction have the same precedence and are evaluated left to right, so 10 - 4 + 2 gives 8.

Quick Revision Tables

Table 1: Built-in Data Types and Examples

Data Type Category Example Mutable
int Number 42 No
float Number 3.14 No
complex Number 2 + 3j No
str Sequence "Hello" No
bool Boolean True No
list Sequence [1, 2, 3] Yes
tuple Sequence (1, 2, 3) No
dict Mapping {"a": 1} Yes
set Set {1, 2, 3} Yes

Table 2: Type Conversion Functions

Function Purpose Example Result
int(x) Convert to integer int(3.9) 3
float(x) Convert to float float("2.5") 2.5
str(x) Convert to string str(100) "100"
bool(x) Convert to boolean bool(0) False
complex(r,i) Create complex number complex(2,3) (2+3j)

Mind Map

graph TD A["Python Data Handling"] --> B["Data Types"] A --> C["Operators"] A --> D["Type Conversion"] A --> E["Precedence"] B --> B1["Numbers: int, float, complex"] B --> B2["Strings: str"] B --> B3["Boolean: bool"] B --> B4["Collections: list, tuple, dict, set"] C --> C1["Arithmetic"] C --> C2["Relational"] C --> C3["Logical"] C --> C4["Assignment"] C --> C5["Identity, Membership"] D --> D1["int(), float(), str(), bool()"] E --> E1["Parentheses highest"] E --> E2["** before * / before + -"]

Important Diagrams (SVG)

Diagram 1: Hierarchy of Python Data Types

Python Built-in Data Types Python Data Types Everything is an object Numbers int: 42 float: 3.14 complex: 2+3j Sequences str: "Hello" list: [1, 2, 3] tuple: (1, 2, 3) Mapping dict: {"a": 1} Key-value pairs Unordered Sets set: {1, 2, 3} Unique items Unordered Others bool: True/False bytes, bytearray Golden Rule The data type of a value decides what operations are allowed on it

Diagram 2: Operator Precedence Ladder

Operator Precedence in Python Highest: ( ) parentheses * exponentiation / // % (multiply, divide, floor, modulo) + - (addition, subtraction) < > <= >= == != (relational) not and or (Lowest) Golden Rule When in doubt, use parentheses to force the evaluation order you want

Common Mistakes

  1. Trying int("3.5") directly, which raises a ValueError; the string must be converted to float first.
  2. Using a single = for comparison, causing a SyntaxError instead of checking equality.
  3. Forgetting that strings are immutable and trying to change a character, e.g., name[0] = 'X', which raises a TypeError.
  4. Assuming / returns an integer; it always returns a float in Python.
  5. Mixing string and integer concatenation with +, e.g., "age: " + 17, which raises a TypeError.
  6. Misinterpreting boolean truthiness: bool("False") is True because the non-empty string is truthy.
  7. Ignoring precedence and getting 2 + 3 * 4 wrong by evaluating left to right.
  8. Using is to compare values instead of identities, which can give unexpected results for some objects.

Exam Tips

  1. Memorise the output format of type(), for example <class 'float'>.
  2. Practise expression-evaluation questions: they appear very frequently in exams.
  3. Learn the rules of truthiness: 0, empty string, empty list are falsy; everything else is truthy.
  4. Remember that // and % are connected: a = (a // b) * b + (a % b).
  5. For conversion questions, always ask what type the source is before converting.
  6. Learn string slicing carefully, since word[start:end] excludes the character at the end index.

Conclusion

Data handling is the heart of programming in Python. By understanding data types, the programmer knows what operations are valid, and by understanding conversion functions, values can be reshaped safely. Operators and precedence rules determine how expressions are evaluated, and mastering them removes most of the ambiguity and errors in program output. These concepts form the vocabulary of every program, and the chapters on control structures, lists, and dictionaries build directly on this foundation to create truly useful programs.