Python Essentials: Functions, Loops, Data Structures & More
Python Essentials
1. Functions
Defining a Function:
pythondef function_name(parameters): # Code block
Calling a Function:
pythonfunction_name(arguments)
Default Parameters:
pythondef greet(name="User"): print(f"Hello, {name}!") greet() # "Hello, User!" greet("Alice") # "Hello, Alice!"
Return Statement:
pythondef add(a, b): return a + b result = add(3, 5) # result is 8
Function Scope (Local vs Global):
- Local variables are accessible only within the function.
- Global variables are accessible throughout the program.
2. Loops
For Loop (List Iteration):
pythonfor i in range(len(my_list)): print(my_list[i])
For Loop (Range):
pythonfor i in range(0, 5): # Iterates from 0 to 4 print(i)
Nested Loops (For Matrices):
pythonmatrix = [[1, 2], [3, 4]] for row in matrix: for element in row: print(element)
List Iteration & Modification During Loop:
- Be careful when modifying a list while iterating, as it may skip elements.
- Consider iterating over a copy or using list comprehensions to avoid issues.
3. Data Structures
Lists:
- Mutable: You can modify lists after creation.
- Example:python
my_list = [1, 2, 3] my_list[0] = 10 # my_list becomes [10, 2, 3]
Tuples:
- Immutable: Once created, elements cannot be changed.
- Example:python
my_tuple = (1, 2, 3) # my_tuple[0] = 10 # ERROR
Sets:
- Unordered collection of unique elements.
- Set operations:
- Combines:
s1 | s2
- Returns what is common to both sides:
s1 & s2
- Returns elements in the 1st set that aren’t common:
s1 - s2
- Returns elements that are not common in both:
s1 ^ s2
- Combines:
Dictionaries:
- Access elements by keys.
- Example:python
d = {"apple": 3, "banana": 5} print(d["apple"]) # 3
Common Methods for Dictionaries:
.items()
: Returns a list of (key, value) pairs..keys()
: Returns a list of keys..values()
: Returns a list of values.
4. Strings
String Indexing:
pythonmy_string = "Hello" print(my_string[0]) # 'H'
Slicing:
pythonmy_string = "Hello" print(my_string[:3]) # 'Hel'
String Methods:
.upper()
: Converts to uppercase..lower()
: Converts to lowercase..split()
: Splits a string into a list based on a delimiter.pythonmy_string = "Hello World" print(my_string.split()) # ['Hello', 'World']
5. Conditionals
If Statements:
pythonif condition: # Code block if condition is true
Logical Operators:
and
: Returnstrue
if both conditions are true.or
: Returnstrue
if at least one condition is true.not
: Reverses the Boolean value.
Modifying Elements Based on Conditions:
pythonnums = [1, 2, 3, 4, 5] for i in range(len(nums)): if nums[i] % 2 == 0: nums[i] = 0 print(nums) # [1, 0, 3, 0, 5]
6. File Handling
- Reading Files:
.read()
: Reads the entire file content..readline()
: Reads one line at a time..readlines()
: Reads all lines into a list.- Example:python
with open("file.txt", "r") as infile: for line in infile: print(line.strip())
7. List Operations
List Repetition:
pythonmy_list = [1, 2] new_list = my_list * 3 # [1, 2, 1, 2, 1, 2]
List Comprehension:
pythonnums = [1, 2, 3, 4] squares = [x**2 for x in nums if x % 2 == 0] # [4, 16]
Modifying Lists During Iteration:
- Avoid modifying a list while iterating over it. This can lead to unexpected behavior.
- Use list comprehensions or iterate over a copy.
8. Common Functions
max()
: Returns the maximum value from an iterable.pythonmax([1, 2, 3]) # 3
sum()
: Returns the sum of all elements in an iterable.pythonsum([1, 2, 3]) # 6
len()
: Returns the length of an iterable.pythonlen([1, 2, 3]) # 3
9. Debugging Tips
- Variable Assignment & References:
- Assigning a variable to another creates a reference to the same object (in case of mutable types).
- Modifying a mutable object through one reference will affect all references to that object.
- Avoid Modifying Lists During Iteration:
- This can cause some elements to be skipped, leading to unexpected results. Instead, use a copy of the list or list comprehensions.