1. Python — Key Characteristics
- Interpreted: Python code is executed line by line by the Python interpreter — no separate compilation step is needed.
- High-level: Python abstracts hardware details, allowing the programmer to focus on logic rather than memory management.
- Dynamically typed: Variable types are determined at runtime — you do not need to declare a variable's type before using it.
- Case-sensitive:
Name,name, andNAMEare three different identifiers. - Indentation-based: Python uses indentation (whitespace) to define blocks of code instead of curly braces
{}. - Object-oriented: Everything in Python is an object — including numbers, strings, and functions.
- Open source and cross-platform: Runs on Windows, macOS, and Linux.
Modes of Running Python
| Mode | Description | When to Use |
|---|---|---|
| Interactive Mode | Type and execute one statement at a time at the >>> prompt |
Quick testing, exploring results |
| Script Mode | Write a complete program in a .py file and run it |
Writing full programs |
2. Tokens — The Building Blocks of Python
A token is the smallest individual unit in a Python program. Python has five types of tokens:
(i) Keywords
Reserved words with special meaning in Python. They cannot be used as variable names. Python 3 has 35 keywords.
| Python Keywords (selected) | ||||||
|---|---|---|---|---|---|---|
False |
True |
None |
and |
or |
not |
if |
elif |
else |
for |
while |
break |
continue |
return |
def |
class |
import |
from |
in |
is |
pass |
global |
lambda |
try |
except |
finally |
raise |
del |
(ii) Identifiers
Names given to variables, functions, classes, and other objects.
Rules for valid identifiers:
- Can contain letters (A–Z, a–z), digits (0–9), and underscore (
_). - Must begin with a letter or underscore — NOT a digit.
- Cannot be a keyword.
- No spaces or special characters (
@,#,$, etc.) allowed. - Case-sensitive:
ageandAgeare different identifiers.
| Valid Identifiers | Invalid Identifiers | Reason Invalid |
|---|---|---|
name, _age, roll_no |
2name |
Starts with digit |
marks1, MyClass |
my name |
Contains space |
__init__, PI |
for |
Keyword |
total_marks |
my@var |
Special character |
(iii) Literals
Fixed values used directly in the code. Python supports: numeric literals (42, 3.14), string literals ('hello'), boolean literals (True, False), and None.
(iv) Operators
Symbols that perform operations on values. Covered in detail in Section 5.
(v) Punctuators
Symbols used to organise code structure: ( ), [ ], { }, :, ,, ., ;, =, #.
3. Variables and Assignment
A variable is a named location in memory that stores a value. In Python, a variable is created when a value is first assigned to it.
Assignment Statement
variable_name = value
# Examples
name = "Alice" # str
age = 17 # int
height = 5.6 # float
is_student = True # bool
Multiple Assignment
# Assign same value to multiple variables
x = y = z = 0
# Assign different values in one line (tuple unpacking)
a, b, c = 10, 20, 30
# Swap two variables (Pythonic way — no temp variable needed)
a, b = b, a
Dynamic Typing
In Python, the same variable can hold different types of data at different times:
x = 10 # x is int
x = "hello" # now x is str — perfectly valid in Python
Use type(variable) to check the current type of a variable.
Comments
- Single-line comment: Start with
#— Python ignores everything after#on that line. - Multi-line comment: Use triple quotes
"""..."""or'''...'''(technically a string literal, but used as a comment).
# This is a single-line comment
"""
This is a
multi-line comment
"""
4. Data Types in Python
A data type defines the kind of value a variable can hold and the operations that can be performed on it. Python's built-in data types are:
| Data Type | Category | Example | Mutable? |
|---|---|---|---|
int |
Numeric | 42, -7, 0 |
No |
float |
Numeric | 3.14, -0.5, 2.0 |
No |
complex |
Numeric | 3+4j, 2j |
No |
bool |
Numeric (subclass of int) | True, False |
No |
str |
Sequence | "hello", 'Python' |
No |
list |
Sequence | [1, 2, 3] |
Yes |
tuple |
Sequence | (1, 2, 3) |
No |
dict |
Mapping | {"name": "Ali"} |
Yes |
set |
Set | {1, 2, 3} |
Yes |
NoneType |
Special | None |
No |
(i) Integers (int)
Whole numbers without a decimal point. Python integers have unlimited precision — there is no overflow.
a = 100
b = -45
c = 0
# Number systems — Python supports multiple bases
decimal = 255 # base 10 (default)
binary = 0b11111111 # base 2 → value 255
octal = 0o377 # base 8 → value 255
hexadecimal = 0xFF # base 16 → value 255
(ii) Floating Point Numbers (float)
Numbers with a decimal point. Stored as double-precision (64-bit) IEEE 754 floating point.
pi = 3.14159
temp = -98.6
sci = 1.5e3 # scientific notation: 1.5 × 10³ = 1500.0
small = 2.5e-4 # 2.5 × 10⁻⁴ = 0.00025
(iii) Boolean (bool)
A subtype of int. Only two values: True (= 1) and False (= 0).
flag = True
print(True + True) # Output: 2 (True is treated as 1)
print(False * 10) # Output: 0 (False is treated as 0)
print(type(True)) # Output: <class 'bool'>
Falsy values in Python (evaluate to False in boolean context): 0, 0.0, "" (empty string), [], (), {}, None. Everything else is truthy.
(iv) Strings (str)
An ordered, immutable sequence of characters enclosed in single '', double "", or triple quotes """ """.
s1 = 'Hello'
s2 = "World"
s3 = """This is a
multi-line string"""
# Indexing — starts at 0; negative index counts from end
name = "Python"
print(name[0]) # 'P'
print(name[-1]) # 'n'
print(name[1:4]) # 'yth' (slicing: start:stop, stop excluded)
print(name[::-1]) # 'nohtyP' (reversal using step -1)
String Operations
| Operation | Operator / Method | Example | Result |
|---|---|---|---|
| Concatenation | + |
"Hi" + " " + "there" |
"Hi there" |
| Repetition | * |
"Ha" * 3 |
"HaHaHa" |
| Membership | in, not in |
"Py" in "Python" |
True |
| Length | len() |
len("Python") |
6 |
| Upper / Lower | .upper(), .lower() |
"hello".upper() |
"HELLO" |
| Strip whitespace | .strip() |
" hi ".strip() |
"hi" |
| Replace | .replace(old, new) |
"cat".replace("c","b") |
"bat" |
| Find index | .find(sub) |
"Python".find("th") |
2 |
| Split | .split(sep) |
"a,b,c".split(",") |
['a','b','c'] |
| Check digit | .isdigit() |
"123".isdigit() |
True |
String Slicing — s[start : stop : step]
s = "COMPUTER"
# 0123456 7 ← positive index
# -8 -1 ← negative index
print(s[2:6]) # 'MPUT' (characters at index 2, 3, 4, 5)
print(s[::2]) # 'CMUE' (every 2nd character)
print(s[::-1]) # 'RETUPMOC' (reverse)
print(s[-4:-1]) # 'UTE'
5. Operators in Python
(i) Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 10 + 3 |
13 |
- |
Subtraction | 10 - 3 |
7 |
* |
Multiplication | 10 * 3 |
30 |
/ |
Division (always float) | 10 / 3 |
3.3333... |
// |
Floor Division (integer) | 10 // 3 |
3 |
% |
Modulus (remainder) | 10 % 3 |
1 |
** |
Exponentiation | 2 ** 8 |
256 |
(ii) Comparison (Relational) Operators
Always return True or False.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
Equal to | 5 == 5 |
True |
!= |
Not equal to | 5 != 3 |
True |
> |
Greater than | 7 > 3 |
True |
< |
Less than | 3 < 7 |
True |
>= |
Greater than or equal | 5 >= 5 |
True |
<= |
Less than or equal | 4 <= 3 |
False |
(iii) Logical Operators
| Operator | Description | Example | Result |
|---|---|---|---|
and |
True if BOTH operands are True | True and False |
False |
or |
True if AT LEAST ONE operand is True | True or False |
True |
not |
Inverts the boolean value | not True |
False |
(iv) Assignment Operators
| Operator | Equivalent To | Example (x=10) |
|---|---|---|
+= |
x = x + val |
x += 5 → x=15 |
-= |
x = x - val |
x -= 3 → x=7 |
*= |
x = x * val |
x *= 2 → x=20 |
/= |
x = x / val |
x /= 4 → x=2.5 |
//= |
x = x // val |
x //= 3 → x=3 |
%= |
x = x % val |
x %= 3 → x=1 |
**= |
x = x ** val |
x **= 2 → x=100 |
(v) Identity and Membership Operators
| Operator | Type | Description | Example |
|---|---|---|---|
is |
Identity | True if same object in memory | a is b |
is not |
Identity | True if different objects in memory | a is not b |
in |
Membership | True if value found in sequence | 3 in [1,2,3] |
not in |
Membership | True if value NOT found in sequence | 5 not in [1,2,3] |
Operator Precedence (High to Low)
| Priority | Operators |
|---|---|
| 1 (Highest) | () — Parentheses |
| 2 | ** — Exponentiation |
| 3 | +x, -x — Unary plus/minus |
| 4 | *, /, //, % |
| 5 | +, - |
| 6 | ==, !=, >, <, >=, <=, in, not in, is, is not |
| 7 | not |
| 8 | and |
| 9 (Lowest) | or |
6. Type Conversion
Implicit Type Conversion (Coercion)
Python automatically converts one data type to another when required — always converting to the "wider" type to avoid data loss:
x = 5 # int
y = 2.0 # float
z = x + y # Python automatically converts x to float
print(z) # 7.0
print(type(z)) # <class 'float'>
Conversion hierarchy: bool → int → float → complex
Explicit Type Conversion (Type Casting)
Manually converting from one type to another using built-in functions:
| Function | Converts to | Example | Output |
|---|---|---|---|
int(x) |
Integer | int("42"), int(3.9) |
42, 3 (truncates) |
float(x) |
Float | float("3.14"), float(5) |
3.14, 5.0 |
str(x) |
String | str(100), str(3.14) |
'100', '3.14' |
bool(x) |
Boolean | bool(0), bool(42) |
False, True |
chr(x) |
Character | chr(65) |
'A' |
ord(x) |
ASCII / Unicode integer | ord('A') |
65 |
# Common use case: reading numeric input from user
age = int(input("Enter your age: ")) # input() always returns str
salary = float(input("Enter salary: "))
# Note: int("3.14") causes ValueError — must convert to float first
# Correct: int(float("3.14")) → 3

