Python Practice Notes
Revision notes covering Python basics, loops, functions, and collection data types.
1. Indexing
Positive indexing starts at 0. Negative indexing starts at -1 from the end of a sequence.
classroom = [
"sagar", "jathib", "jathias", "ranyad", "tata"
]
# Positive indexing: 0, 1, 2, 3, 4
# Negative indexing: -5, -4, -3, -2, -1
print(classroom[0])
print(classroom[-1])
print(type(classroom))
print(len(classroom[0]))
2. String Slicing and Step Functions
Syntax: string[start:stop:step]
name = "sasdas"
print(name[0:]) # From index 0 to the end
print(name[:2]) # From the beginning to index 1
print(name[::3]) # Every third character
print(name[::-2]) # Reverse with a step of 2
3. String Split Method
The split() method divides a string into
a list using a specified separator.
name = "S A G A R"
print(type(name))
name = name.split(" ")
print(name)
print(type(name))
4. Escape Characters and User Input
Common escape characters:
\\— Backslash\n— New line\"— Double quotation mark
a = input("Enter user name: ")
b = input("Enter another user name: ")
print(f"User has entered \\{a}\nand \"{b}\"")
5. Assignment Operators
a += b # Equivalent to a = a + b
a -= b # Equivalent to a = a - b
a *= b # Equivalent to a = a * b
6. Loops
While Loop
A while loop repeats as long as its condition is true.
i = 0
while i <= 10:
print(f"{i} is less than or equal to 10")
i += 1
For Loop
A for loop iterates over a sequence or range of values.
# range(start, stop, step)
for i in range(1, 10):
print(f"{i} is less than 10")
Break Statement
The break statement terminates a loop.
for i in range(1, 10):
print(f"{i} is less than 10")
if i == 5:
break
Continue Statement
The continue statement skips the current
iteration and moves to the next one.
for i in range(1, 10):
if i == 5:
continue
print(f"{i} is less than 10")
Nested Loops
A nested loop is a loop inside another loop.
for i in range(1, 10):
for j in range(10, 20):
print(f"{i} * {j} = {i * j}")
7. Functions
Functions are reusable blocks of code defined using
the def keyword.
def addition(a, b):
for i in range(a, b):
print(f"i value is {i} and b value is {b}")
addition(5, 7)
Return Values
def addition(a, b):
return a + b
result = addition(1, 10)
print(result)
8. Lambda Functions
A lambda function is a small anonymous function.
multiply = lambda a, b: a * b
add = lambda x, y: x + y
print(add(3, 5))
print(multiply(3, 5))
9. Lists
Lists are ordered and mutable collections. They allow duplicate values and different data types.
l = [1, "asa", "sagar"]
z = [20, 30, 90, 10, 34, 67]
# Add an element at the end
l.append("python")
# Remove and return the last element
l.pop()
# Insert a value at a particular index
l.insert(1, "hello")
# Remove a particular value
l.remove("asa")
# Find the index of a value
print(l.index("sagar"))
# Sort a list
z.sort()
# Count occurrences of a value
print(z.count(10))
# Get the number of elements
print(len(z))
# Concatenate two lists
l1 = [20, 30, 40]
l2 = [60, 80, 90]
l3 = l1 + l2
print(l3)
List Comprehension
z = [i ** 2 for i in range(1, 10)]
print(z)
10. Tuples
Tuples are ordered and immutable collections. They allow duplicate values.
numbers = (10, 20, 30, 20)
print(numbers)
print(numbers[0])
print(len(numbers))
11. Sets
Sets store unique elements. They do not support indexing, and their iteration order should not be relied upon.
a = {1, 2, 3, 4, 5, 5, 5, 8}
print(a)
# Convert a list into a set
a = [10, 10, 10, 10, 20]
b = set(a)
c = list(b)
print(c)
Set Operations
a = {2, 4, 5, 7}
b = {7, 10, 2, 4}
# All unique elements from both sets
print(a.union(b))
# Common elements
print(a.intersection(b))
# Elements in a but not in b
print(a.difference(b))
# Elements in either set, but not both
print(a.symmetric_difference(b))
Set Comprehension
z = {i ** 2 for i in range(1, 10)}
print(z)
Frozenset
A frozenset is an immutable version of a set.
frozen = frozenset(z)
print(frozen)
12. Dictionaries
Dictionaries store data as key-value pairs. Keys must be unique and hashable.
a = {
"name": "Death Note",
"Episode": 1,
"seen": 2
}
a["name"] = input("Enter anime name: ")
# Display key-value pairs
print(a.items())
# Display keys
print(a.keys())
# Display values
print(a.values())
# Access a value using its key
print(a["name"])
Dictionary Comprehension
z = {i: i ** 2 for i in range(1, 10)}
print(z)
13. Quick Revision
- List: Ordered and mutable.
- Tuple: Ordered and immutable.
- Set: Unique elements, no indexing.
- Frozenset: Immutable set.
- Dictionary: Key-value pairs.
- While loop: Repeats while a condition is true.
- For loop: Iterates over a sequence or iterable.
- Break: Exits the loop.
- Continue: Skips to the next iteration.
- Lambda: Creates a small anonymous function.
Comments
Post a Comment