Free Study Material

Data Types & Operators

Introduction

You've seen a variable's value can be a number, text, or a Boolean. This topic names each of those kinds formally, and introduces a distinction CBSE tests directly: whether a value can be changed after it's created.

Concept

Python's core built-in data types:

  • int — a whole number, like 25 or -3.
  • float — a number with a decimal point, like 3.14 or 98.6.
  • str — text, written inside quotes, like "hello".
  • bool — exactly True or False.
  • list, tuple, dict — collections that hold multiple values together (covered in their own chapters).

Every value in Python is also either mutable or immutable:

  • Mutable — can be changed in place after creation, without creating a new object. list, dict.
  • Immutable — cannot be changed in place at all; any "change" actually creates a brand-new value. int, float, str, bool, tuple.

Worked Example

name = "Aisha"
print(type(name))
print(type(25))
print(type(3.14))
print(type(True))

type() reports a value's data type. Running this prints <class 'str'>, <class 'int'>, <class 'float'>, and <class 'bool'>, in that order — one line for each print() call.

Note: A string looks like it can be "changed" with something like name = name + " Khan", but this doesn't modify the original string at all — it builds an entirely new string and points name at it. The original "Aisha" object is untouched, which is exactly what makes str immutable.

Explanation

Mutability matters beyond terminology: a mutable value can be modified by more than one variable name pointing at it, which is a common source of confusing bugs later (covered fully in the Lists chapter); an immutable value never has that risk, because no operation can ever change it after creation — only replace what a variable points to.

Summary

Python's core data types are int, float, str, and bool, plus the collection types list, tuple, and dict. Every type is either mutable (list, dict — can change in place) or immutable (int, float, str, bool, tuple — any "change" actually creates a new value).

What is a Data Type?

In Python, every value has a Data Type. This tells the computer how much memory to set aside and what kinds of operations can be performed on that data. For example, you can multiply two integers, but you cannot "multiply" two dictionaries.

Category Data Type Example
Numbers int, float, complex 10, 3.14, 2+3j
Sequence str, list, tuple "Hi", [1,2], (3,4)
Mapping dict {"age": 16}
Others bool, None True, None
Immutable (Unchangeable)

Values cannot be modified after they are created.

  • Integers, Floats
  • Strings
  • Tuples
Mutable (Changeable)

Values can be modified in-place without creating a new object.

  • Lists
  • Dictionaries
  • Sets

Introduction

Now that you know Python's basic data types, this topic covers the operators that actually work on them — starting with the two most common groups: arithmetic and relational.

Concept

Arithmetic Operators

OperatorMeaningExampleResult
+Addition7 + 29
-Subtraction7 - 25
*Multiplication7 * 214
/Division (always returns a float)7 / 23.5
//Floor Division (drops the decimal part)7 // 23
%Modulus (the remainder)7 % 21
**Exponent (power)7 ** 249

Relational Operators

Relational operators compare two values and always produce a bool result — True or False.

OperatorMeaning
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Worked Example

a = 17
b = 5

print(a / b)
print(a // b)
print(a % b)
print(a == b)
print(a > b)

Running this prints, in order: 3.4 (true division), 3 (floor division drops the .4), 2 (the remainder after 17 // 5 = 3), False (17 does not equal 5), and True (17 is greater than 5).

Note: == (double equals) checks equality and produces a bool. = (single equals) assigns a value and produces nothing at all. Mixing these up is one of the most common beginner errors in Python.

Explanation

// and % are worth tracing by hand until they're automatic: for a // b, the result is how many whole times b fits into a; for a % b, the result is whatever is left over after that. For 17 // 5, 5 fits into 17 three whole times (15), leaving a remainder of 2 — exactly what 17 % 5 returns. This pair shows up constantly in later chapters, from checking even/odd numbers to extracting individual digits.

Summary

Arithmetic operators (+ - / // % *) compute a value; relational operators (== != > < >= <=) compare two values and always return True or False. / always returns a float, while // returns the whole-number quotient and % returns the remainder.

The Engines of Logic

In Python, Operators are special symbols that carry out arithmetic or logical computation. The values that the operator operates on are called Operands. For example, in 10 + 5, + is the operator and 10 and 5 are the operands.

Operator Meaning Example (A=10, B=3)
** Exponentiation (Power) 10 ** 3 = 1000
/ Division (Always returns Float) 10 / 3 = 3.333...
// Floor Division (Integer result) 10 // 3 = 3
% Modulus (Remainder) 10 % 3 = 1

Common Comparisons

  • == : Equal to
  • != : Not Equal to
  • >= : Greater than or Equal to
  • <= : Less than or Equal to
# Try running these in your editor!
print(17 // 5)  # Expected: 3
print(17 % 5)   # Expected: 2 (The remainder)
print(5 == 5.0) # Expected: True

Introduction

Arithmetic and relational operators work with numbers and comparisons. This topic covers four more operator groups — for combining conditions, updating variables, comparing objects, and searching collections.

Concept

Logical Operators

Combine or invert bool values:

  • and — True only if both sides are True.
  • or — True if at least one side is True.
  • not — flips True to False, and False to True.

Assignment Operators

= assigns a value. Python also has shorthand compound assignment operators that update a variable using its own current value:

OperatorSame as
x += 5x = x + 5
x -= 5x = x - 5
x *= 5x = x * 5
x /= 5x = x / 5

Identity Operators

is and is not check whether two names refer to the exact same object in memory — not just whether their values look equal.

Membership Operators

in and not in check whether a value exists inside a collection (a string, list, or similar).

Worked Example

marks = 85
attendance = 92

print(marks > 80 and attendance > 90)
print(marks > 90 or attendance > 90)

score = 10
score += 5
print(score)

subjects = ["Physics", "Chemistry", "Maths"]
print("Chemistry" in subjects)
print("Biology" not in subjects)

marks > 80 and attendance > 90 is True and True, so it prints True. marks > 90 or attendance > 90 is False or True, so it also prints True — only one side needs to be True for or. score += 5 updates score from 10 to 15. "Chemistry" in subjects is True (it's in the list); "Biology" not in subjects is also True (it genuinely isn't there).

Note: == compares values ("do these look the same?"), while is compares identity ("are these literally the same object in memory?"). Two separate lists with identical contents are == but not is — a real, exam-tested distinction covered fully once objects like lists are introduced.

Explanation

and/or don't just produce True/False in the abstract — they're how a program combines multiple real-world conditions into one decision, like checking that both marks and attendance clear a threshold before deciding a student passes. That combined-condition pattern is exactly what the next chapter's if statements are built to act on.

Summary

Logical operators (and, or, not) combine or invert conditions; compound assignment operators (+=, -=, *=, /=) update a variable using its own value in one step; is/is not compare object identity rather than value; in/not in check membership inside a collection like a string or list.

Beyond Simple Math

While arithmetic operators handle numbers, these operators handle logic and relationships. They allow us to combine conditions, update variables quickly, and check if one piece of data exists inside another.

and

Returns True only if both statements are true.

or

Returns True if at least one statement is true.

not

Reverses the result (True becomes False).

Operator Equivalent To Action
x += 5 x = x + 5 Add and assign
x -= 2 x = x - 2 Subtract and assign
x *= 3 x = x * 3 Multiply and assign
Identity (is, is not)

Checks if both variables point to the same object in memory.

x is y
Membership (in, not in)

Checks if a value exists inside a sequence (String, List, etc.).

"P" in "Python"

Introduction

You now know most of Python's operators individually. This topic covers what happens when several of them appear together in the same line, and the two basic terms used to describe any line of code.

Concept

Expressions and Statements

  • An expression is anything that evaluates to a value: 5 + 3, marks > 80, "Hi " + name.
  • A statement is a complete instruction Python executes: marks = 85 is a statement (an assignment statement) built out of the expression 85.

Operator Precedence

When an expression mixes several operators, Python evaluates them in a fixed order, not strictly left to right:

  1. () — parentheses (evaluated first, always)
  2. ** — exponent
  3. *, /, //, % — multiplication, division, floor division, modulus
  4. +, - — addition, subtraction
  5. ==, !=, >, <, >=, <= — relational operators
  6. not
  7. and
  8. or

Operators on the same level (like * and /) are then evaluated left to right.

Worked Example

result = 2 + 3 * 4
print(result)

result2 = (2 + 3) * 4
print(result2)

check = 5 > 3 and 2 < 1
print(check)

2 + 3 4 evaluates 3 4 first (multiplication outranks addition), giving 12, then 2 + 12 = 14. Wrapping 2 + 3 in parentheses forces it to happen first instead, giving 5 * 4 = 20. 5 > 3 and 2 < 1 evaluates both relational comparisons first (True and False), then combines them with and, giving False.

Tip: When an expression's order of evaluation isn't immediately obvious, add parentheses — even ones that aren't strictly required. (2 + 3) * 4 is exactly as correct as a precedence table lookup, and far easier to read at a glance.

Explanation

Precedence explains a mistake every beginner makes at least once: writing average = a + b + c / 3 expecting to divide the total by 3, when Python actually divides only c by 3 first (/ outranks +), then adds the result to a + b. The fix is always the same: (a + b + c) / 3.

Summary

An expression evaluates to a value; a statement is a complete instruction. When several operators appear in one expression, Python follows a fixed precedence order — parentheses first, then *, then / // %, then + -, then relational operators, then not, and, or — with parentheses always the safest way to make the intended order explicit.

Calculations in Order

A single line of code can contain multiple operators. Python follows a strict set of rules called Operator Precedence to decide which operation happens first. Without these rules, a simple math problem could give different answers on different computers!

Expression

A combination of values and operators that evaluates to a single value.

10 + 5 * 2
Statement

A complete line of code that performs an action (like assignment or printing).

x = 10 + 5 * 2
Priority Operator Type Symbols
1 (Highest) Parentheses ( )
2 Exponentiation **
3 Multiplication/Division * , / , // , %
4 (Lowest) Addition/Subtraction + , -

Note: If operators have the same priority (like + and -), Python calculates from Left to Right.

# What will be the output?
result = 10 + 2 * 3 ** 2
print(result)

# Breakdown:
# 1. Power first: 3 ** 2 = 9
# 2. Multiplication next: 2 * 9 = 18
# 3. Addition last: 10 + 18 = 28
1
Parentheses
Everything inside brackets happens first.
( )
2
Exponentiation
Powers and indices.
**
3
Multiplication & Division
Includes Floor Division and Modulus.
* , / , // , %
4
Addition & Subtraction
The final steps of the calculation.
+ , -

Introduction

Every program you've traced so far used fixed values written directly in the code. Real programs usually need to take in data from the user and convert it to the right type before working with it — this topic covers exactly that.

Concept

Input

input("prompt") displays the prompt, waits for the user to type something, and returns whatever they typed — always as a string, even if they type digits.

Output

print() displays values. Two optional arguments control its formatting:

  • sep — what to place between multiple printed items (default is a single space).
  • end — what to print after everything else (default is a newline, so each print() normally starts on a fresh line).

Type Conversion

Because input() always returns a string, converting it to a number is a routine step:

  • int(value) — converts to a whole number.
  • float(value) — converts to a decimal number.
  • str(value) — converts to a string.

Worked Example

age_text = input("Enter your age: ")
print(type(age_text))

age = int(age_text)
print(type(age))
print(age + 1)

print("A", "B", "C", sep="-")
print("No newline here", end=" ")
print("— same line.")

age_text holds whatever the user typed, as a str — even if they type 15, type(age_text) prints <class 'str'>. int(age_text) converts it to a real integer, so age + 1 works as arithmetic instead of raising an error. print("A", "B", "C", sep="-") prints A-B-C using the custom separator. The next print() uses end=" " instead of a newline, so "— same line." from the following print() call appears right after it, on the same line.

Warning: age_text + 1 (skipping the conversion) raises TypeError: can only concatenate str (not "int") to str — input()'s result is always text, and Python never silently converts it to a number for you.

Explanation

This str-to-number conversion step is not optional boilerplate — it's the direct, practical consequence of input()'s one fixed rule (always returns a string). Forgetting it is one of the most common early runtime errors, precisely because the code looks like it should work with plain numbers.

Summary

input() always returns a string, so a value the user types must be explicitly converted with int() or float() before it can be used in arithmetic. print() accepts sep (the separator between items) and end (what to print after the last item, replacing the default newline) to control exactly how output is formatted.

Talking to Your Program

A program is only useful if it can interact with a human. We use input() to listen to the user and print() to speak back. However, there is a catch: input() always treats everything as a String. To do math, we must learn to convert types.

The input() function

Used to take data from the keyboard. Crucial: It always returns data as a String.

name = input("Enter name: ")
The print() function

Used to display results on the screen. You can print multiple items separated by commas.

print("Hello", name)
Implicit (Automatic)

Python promotes a "smaller" type to a "larger" type to avoid data loss.

x = 5 + 2.0 # x becomes 7.0 (float)
Explicit (Manual)

The programmer uses functions like int(), float(), or str().

age = int(input("Enter age: "))
# The WRONG way:
val1 = input("Enter 10: ") # returns "10"
val2 = input("Enter 5: ")  # returns "5"
print(val1 + val2)         # Result: "105" (String joining)

# The RIGHT way:
val1 = int(input("Enter 10: ")) # converts to 10
val2 = int(input("Enter 5: "))  # converts to 5
print(val1 + val2)              # Result: 15 (Math addition)

Want the full course?

Unlock all chapters, video lectures, and SQL practice exercises.

Get Full Access