Chapter 3: Variables and Data Types
In Python, variables are names bound to objects; they do not have fixed types. You assign a value to a
variable simply by = (e.g. x = 10 ). The data type is determined by the object it refers to at runtime
1 . For example:
x = 42 # x refers to an integer object
print(type(x)) # <class 'int'>
x = "hello" # now x refers to a string object
print(type(x)) # <class 'str'>
Python’s built-in numeric types include: - int – integer numbers of unlimited precision 2 . E.g. x =
123 . - float – floating-point numbers (double precision) 2 . E.g. y = 3.14 . - complex – complex
numbers with real and imaginary parts (written a + bj ) 2 .
Booleans ( True / False ) are a subtype of integers 2 ( True acts like 1 , False like 0 ).
Python also provides text and other types: - str – immutable sequences of Unicode characters. Strings
are created with quotes, e.g. "hello" or 'world' . They support slicing/indexing like lists.
- NoneType – the type of the special value None , used to denote “no value.”
Because Python is dynamically typed, you can freely convert between types or mix them in expressions.
For example, Python will automatically promote int to float when needed 3 . You can also use
constructors to convert explicitly: int("123") → 123 , float("3.14") → 3.14 , etc. Python’s
garbage collector reclaims memory for objects with no references, so you generally need not manage
memory manually 1 4 .
Key Points:
- Variables are labels for objects. Reassigning a variable (e.g. x = 5; x = "foo" ) simply binds it to a
new object 1 .
- Python types (int, float, str, list, etc.) are built-in classes; the type() function shows an object’s type.
- Objects (especially complex ones like lists or dicts) reside in the heap; Python manages memory and
garbage collection automatically 4 .
Chapter 4: Operators and Expressions
Python provides a rich set of operators for arithmetic, comparisons, logic, and more. Most operators
work much like in other languages, but some nuances apply:
• Arithmetic Operators: + - * / // % ** 5
• / performs floating-point division (even if operands are ints).
• // is floor division (e.g. 7//3 == 2 ).
• % is the remainder (modulo).
• ** is exponentiation (e.g. 2**3 == 8 ).
• All arithmetic operators follow standard precedence (see documentation for details).
1
• Comparison Operators: <, >, <=, >=, ==, !=, is, is not 6 .
• Use these in conditions. For example, x == y tests equality, x < y tests less-than.
• The is operator checks object identity (whether two references point to the same object).
• Logical Operators: and , or , not (Boolean logic) 7 8 .
• These use short-circuit logic: x and y returns x if it’s false, else y ; x or y returns x if
it’s true, else y 7 .
• not x inverts the truth value of x .
• Example: (x < 10) and (y > 0) .
• Bitwise Operators: Work on integers only: & (AND), | (OR), ^ (XOR), ~ (NOT), <<
(left shift), >> (right shift) 9 . These operate on the binary representations of
integers. For example, 5 & 3 == 1 because 0b101 & 0b011 == 0b001 .
• Assignment Operators: = , += , -= , etc. combine assignment with operations.
• Other: The ternary expression a if condition else b for inline if-else.
Operator Examples:
a = 10; b = 3
print(a + b) # 13
print(a / b) # 3.333... (float division)
print(a // b) # 3 (integer division)
print(a ** b) # 1000 (10^3)
print(a % b) # 1 (remainder)
print(a == 10) # True
print(a != b) # True
print((a > 5) and (b < 5)) # True (logical and)
print(~a) # bitwise NOT; in two's complement, ~10 == -11
Chapter 5: Control Flow Statements
Python controls program flow with conditionals and loops:
• if / elif / else : Executes code based on conditions 10 11 . For example:
x = int(input("Enter a number: "))
if x < 0:
print("Negative")
elif x == 0:
print("Zero")
2
else:
print("Positive")
Here, only the first true branch runs. Python allows any number of elif clauses; the final else is
optional 11 .
• for loops: Iterate over items in a sequence 12 . Unlike C’s for-loop, Python’s for directly
loops over collection elements. Example:
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
This prints each word and its length. To loop over numeric ranges, use the built-in range() function
13 :
for i in range(3):
print(i) # prints 0, 1, 2
• while loops: Repeat as long as a condition is true. Example:
n = 5
while n > 0:
print(n)
n -= 1
• break and continue : Inside loops, break exits the loop immediately 14 ; continue
skips to the next iteration 15 . For example, to find factors:
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(f"{n} equals {x} * {n//x}")
break # exit inner loop when a factor is found 14
• else clause on loops: A loop can have an else block that runs if the loop finishes normally
(no break ) 16 . For example:
for n in range(2, 6):
for x in range(2, n):
if n % x == 0:
print(n, "equals", x, "*", n//x)
break
3
else:
print(n, "is prime") # runs if no break occurred 16
• pass : A no-op statement, useful as a placeholder (it does nothing) 17 .
Key Points:
- Use indentation to define block scopes (the body of if , loops, functions, etc.) 18 .
- Conditional tests ( if ) must evaluate to a Boolean ( True / False ). Non-Boolean values (like non-
zero numbers or non-empty strings) are treated as True by default.
- Loops allow powerful constructs. Remember that modifying a sequence while iterating can lead to
subtle bugs; often iterating over a copy or using comprehensions is safer.
Chapter 6: String Handling
Python’s string type str is an immutable sequence of characters. Strings support all standard
sequence operations (indexing, slicing, concatenation, repetition) 19 . You can define strings with single
quotes ( 'abc' ), double quotes ( "abc" ), or triple quotes ( '''multiline''' ). Raw strings
( r"..." ) treat backslashes literally. Since strings are immutable, concatenation ( + ) or join
produces new strings.
s = "Hello"
t = s + " World" # concatenation
print(t[0], t[1:5]) # H ello
Strings have many built-in methods for manipulation (see Python’s string module 20 or str
methods). For example: - [Link]() , [Link]() , [Link]() - [Link]('sub') returns
index of substring or -1. - [Link]('old', 'new') , [Link]() , [Link]() . - len(s) gives
string length.
Python supports formatted strings:
- F-strings: Prefixed with f , allow inline expressions: f"Value: {x}" .
- [Link]() : Use placeholders "Name: {}".format(name) .
Example:
name = "Alice"; age = 30
print(f"{name} is {age} years old.") # f-string
print("{} is {} years old.".format(name, age))
Because strings are immutable, operations that modify strings (like upper/lower) return new strings.
Many formatting and encoding features exist (byte strings, unicode, etc.) but the basics above cover
most text processing needs.
4
Chapter 7: Lists, Tuples, Sets, and Dictionaries
Python provides several built-in container types:
• List ( list ): Ordered, mutable sequences of items. Defined with square brackets: lst = [1,
2, 3] . Lists allow duplicates and can hold mixed types. You can append ( [Link](x) ),
remove, or change elements (e.g. lst[0] = 10 ).
• Tuple ( tuple ): Ordered, immutable sequences. Defined with parentheses or comma:
t = (1, 2, 3) or t = 1, 2, 3 . You cannot modify a tuple’s contents after creation.
Tuples allow duplicates.
• Set ( set ): Unordered collections of unique items. Defined with curly braces: s = {1, 2, 3}
or via set() constructor. Sets do not allow duplicates, and iteration order is arbitrary. Sets
support membership tests ( x in s ) efficiently, and set operations ( & , | , etc.).
• Dictionary ( dict ): Unordered (in Python 3.7+, ordered by insertion) mappings from keys to
values. Defined with curly braces and colons: d = {'a': 1, 'b': 2} . Keys must be
immutable (e.g. strings, numbers, tuples), and are unique. Values can be any type and can
duplicate. Access with d['a'] , add with d['c'] = 3 .
The table below summarizes key differences:
Dictionary ( {key:
Feature List ( [] ) Tuple ( () ) Set ( {} )
value} )
lst = t = d = {'a':1, 'b':
Syntax s = {1,2,3}
[1,2,3] (1,2,3) 2}
Mutability Mutable Immutable Mutable Mutable (values)
Ordered (Python 3.7+)
Order Ordered Ordered Unordered
21
Keys: Not allowed 22 ;
Duplicates Allowed Allowed Not allowed
Values: allowed
No numeric index;
Indexing Yes Yes No (no indexing)
access by key
General Fixed Membership tests,
Use-case Key-value lookup
sequences collections unique elements
22 23 21
Examples:
lst = [1, 2, 2, 3]
tup = (1, 2, 3)
st = {2, 3, 4}
d = {'x': 100, 'y': 200}
print(lst[1], tup[1]) # 2 2
lst[0] = 10 # modify list
5
# tup[0] = 10 # Error: tuples are immutable
print(2 in st, 'x' in d) # True True (membership in set, key in dict)
• Lists support many methods: append() , pop() , insert() , sort() , etc.
• Tuples support only non-modifying methods (like count, index). Use when you need a fixed
sequence (e.g. as a dictionary key or return multiple values).
• Sets support set algebra: union , intersection , difference .
• Dictionaries allow fast lookup by key: use [Link]() , [Link]() , [Link]() to iterate.
List Comprehensions: A concise way to create lists from other iterables. Example: squares = [x**2
for x in range(5)] yields [0,1,4,9,16] . Similar comprehensions exist for dicts ( {k:v
for ...} ) and sets.
In summary, choose the container based on needs: use list for general ordered collections, tuple for
fixed records, set for unique items and membership checks, and dict for associative mappings. Python’s
rich built-ins and methods on these types make them very powerful data structures in practice 22 21 .
1 4python - Does dynamic typing mean change of memory place or change of value? - Stack
Overflow
[Link]
2 3 5 6 7 8 9 19 Built-in Types — Python 3.14.3 documentation
[Link]
10 11 12 13 14 15 16 17 4. More Control Flow Tools — Python 3.14.3 documentation
[Link]
18 2. Lexical analysis — Python 3.14.3 documentation
[Link]
20 string — Common string operations — Python 3.14.3 documentation
[Link]
21 22 23 Differences and Applications of List, Tuple, Set and Dictionary in Python - GeeksforGeeks
[Link]