Python Essentials: Functions, Loops, Data Structures & More

Python Essentials


1. Functions

  • Defining a Function:

    python
    def function_name(parameters): # Code block
  • Calling a Function:

    python
    function_name(arguments)
  • Default Parameters:

    python
    def greet(name="User"): print(f"Hello, {name}!") greet() # "Hello, User!" greet("Alice") # "Hello, Alice!"
  • Return Statement:

    python
    def 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):

    python
    for i in range(len(my_list)): print(my_list[i])
  • For Loop (Range):

    python
    for i in range(0, 5): # Iterates from 0 to 4 print(i)
  • Nested Loops (For Matrices):

    python
    matrix = [[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
  • 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:

    python
    my_string = "Hello" print(my_string[0]) # 'H'
  • Slicing:

    python
    my_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.
      python
      my_string = "Hello World" print(my_string.split()) # ['Hello', 'World']

5. Conditionals

  • If Statements:

    python
    if condition: # Code block if condition is true
  • Logical Operators:

    • and: Returns true if both conditions are true.
    • or: Returns true if at least one condition is true.
    • not: Reverses the Boolean value.
  • Modifying Elements Based on Conditions:

    python
    nums = [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:

    python
    my_list = [1, 2] new_list = my_list * 3 # [1, 2, 1, 2, 1, 2]
  • List Comprehension:

    python
    nums = [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.

    python
    max([1, 2, 3]) # 3
  • sum(): Returns the sum of all elements in an iterable.

    python
    sum([1, 2, 3]) # 6
  • len(): Returns the length of an iterable.

    python
    len([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.