Python Control Structures & Collections - Detailed Notes
1. Conditional Program Execution
a) Conditional Statements:
- Used to execute code based on a condition (True/False).
- Example:
if condition:
# code block
b) if Statement:
- Checks a condition and runs a block of code if it's True.
x = 10
if x > 5:
print("x is greater than 5")
c) if-else Statement:
- Runs one block if condition is True, another if False.
if x > 5:
print("Greater")
else:
print("Smaller or equal")
d) Nested if-else:
- if inside another if or else block.
if x > 0:
if x < 10:
print("Between 0 and 10")
else:
print("10 or more")
else:
print("0 or less")
2. Looping
a) for Loop:
- Used to iterate over a sequence (list, string, range).
for i in range(5):
print(i)
b) while Loop:
- Repeats while a condition is True.
x=0
while x < 5:
print(x)
x += 1
c) Nested Loops:
- Loop inside another loop.
for i in range(3):
for j in range(2):
print(i, j)
3. Control Statements
a) break:
- Exits the loop immediately.
for i in range(5):
if i == 3:
break
b) continue:
- Skips the current iteration and moves to the next.
for i in range(5):
if i == 2:
continue
print(i)
c) pass:
- Does nothing; placeholder.
for i in range(5):
pass
4. Lists
a) Introduction:
- Ordered, mutable collection of elements.
fruits = ["apple", "banana", "cherry"]
b) Properties:
- Mutable, can contain any data type, indexed, allows duplicates.
c) Accessing Elements:
fruits[0] # "apple"
fruits[-1] # "cherry"
d) Operations:
- Concatenation: [1, 2] + [3, 4]
- Repetition: [1] * 3
- Slicing: fruits[1:3]
e) Functions and Methods:
len(fruits)
[Link]("mango")
[Link]("banana")
[Link]()
5. Tuples
a) Introduction:
- Ordered, immutable collection of elements.
data = (1, 2, 3)
b) Properties:
- Immutable, can contain different data types, allows duplicates.
c) Accessing Elements:
data[0], data[-1]
d) Operations:
- Concatenation, repetition, slicing.
e) Functions and Methods:
len(data)
[Link](2)
[Link](3)
6. Dictionaries
a) Introduction:
- Collection of key-value pairs.
student = {"name": "Alice", "age": 20}
b) Properties:
- Unordered (before Python 3.7), keys must be unique and immutable.
c) Accessing Values:
student["name"]
[Link]("age")
d) Functions and Methods:
len(student)
[Link]()
[Link]()
[Link]()
student["grade"] = "A"
del student["age"]