Advanced Python Concepts

Jun 21, 2024

Lecture Notes: Advanced Python Concepts

1. Virtual Environments

  • Purpose: Isolate dependencies for different Python projects to avoid conflicts.
  • Commands:
    • Create: virtualenv env_name
    • Activate (Windows): env_name\Scripts\activate.ps1
    • Deactivate: deactivate
  • Example: Create multiple environments (env1, env2) and install different packages (pandas, pyjokes), then freeze dependencies to requirements.txt with pip freeze > requirements.txt and install with pip install -r requirements.txt.

2. Lambda Functions

  • Syntax: lambda arguments: expression
  • Example: square = lambda n: n * n for squaring a number.
  • Usage: Quick function definitions for simple operations.

3. The Join Method

  • Purpose: Concatenate elements in a list with a specified separator.
  • Syntax: separator.join(iterable)
  • Example: '-'.join(['Harry', 'Rohan', 'Shubham'])Harry-Rohan-Shubham.

4. The Format Method

  • Purpose: Insert variables into strings at specified places.
  • Syntax: {} for position-based formatting.
  • Example: ",".format(name, marks, phone)

5. Map, Filter, and Reduce

Map

  • Usage: Apply a function to all items in an input list.
  • Syntax: map(function, iterable)
  • Example: Squaring numbers in a list map(lambda x: x*x, [1, 2, 3, 4])

Filter

  • Usage: Filter items out of a list.
  • Syntax: filter(function, iterable)
  • Example: Filter even numbers filter(lambda x: x % 2 == 0, [1, 2, 3, 4])

Reduce

  • Usage: Apply a rolling computation to sequential pairs of values in a list.
  • Syntax: reduce(function, iterable) from functools
  • Example: Calculate sum reduce(lambda x, y: x + y, [1, 2, 3, 4])

6. Error Handling with Try, Except, Else, and Finally

  • Purpose: Manage errors gracefully and perform clean-up operations.
  • Syntax:
    try:
        # code that might raise an exception
    except SomeException as e:
        # code that runs if an exception occurs
    else:
        # code that runs if no exception occurs
    finally:
        # code that always runs (clean-up code)
    
  • Example: Handle division by zero and other errors efficiently.

7. Name Equals Main

  • Purpose: Ensure that certain code runs only when a module is executed directly, not when imported.
  • Syntax: if __name__ == "__main__":
  • Example:
    if __name__ == "__main__":
        main()
    
  • Usage: Helps in debugging and code reusability.

8. Global Keyword

  • Purpose: Modify a global variable inside a function.
  • Syntax: global var_name
  • Example:
    a = 10
    def update():
        global a
        a = 20
    update()
    print(a)  # 20
    
  • Usage: Change global variables within functions.

9. List Comprehension

  • Purpose: Compact and readable way of creating lists.
  • Syntax: [expression for item in iterable]
  • Example: Squaring numbers [x*x for x in range(10)]
  • Usage: Efficient and readable list generation.

10. Advanced Python Functions (Merging Dictionaries, Multiple Context Managers, etc.)

  • Merging Dictionaries: Use ** unpacking to merge.
  • Context Management: Efficiently handle multiple resources with with
  • Example: Merging dictionaries
    dict1 = {'a': 1}
    dict2 = {'b': 2}
    merged_dict = {**dict1, **dict2}
    
  • Multiple Context Managers: Unpack and manage multiple resources
    with open('file1.txt') as f1, open('file2.txt') as f2:
        ...
    

I hope these notes help you in effectively understanding and using advanced Python concepts!

Practice Set Solutions

Problem 1

Objective: Create virtual environments, install packages, and utilize requirements.txt

Commands:

pip install virtualenv
virtualenv env1
source env1/bin/activate  # For Unix-based systems
.env1\Scripts\activate.ps1  # For Windows
pip install pandas pyjokes
pip freeze > requirements.txt
pip install -r requirements.txt

Problem 2

Objective: Format a string using the format method

name = input('Enter name: ')
marks = int(input('Enter marks: '))
phone = input('Enter phone number: ')
formatted_string = "Name: {}, Marks: {}, Phone: {}".format(name, marks, phone)
print(formatted_string)

Problem 3

Objective: Use the join method to concatenate elements of a list with a separator

table = [7 * i for i in range(1, 11)]
sequence = '\n'.join(map(str, table))
print(sequence)

Problem 4

Objective: Filter list of numbers that are divisible by 5

def divisible_by_5(x):
    return x % 5 == 0

l = [1, 2, 10, 3, 15, 25]
filtered_list = list(filter(divisible_by_5, l))
print(filtered_list)

Problem 5

Objective: Use reduce to find the maximum number in a list

from functools import reduce

def max_reduce(a, b):
    return a if a > b else b

numbers = [1, 2, 5, 6, 3]
max_number = reduce(max_reduce, numbers)
print(f'The maximum number is: {max_number}')

Problem 6

Objective: Use pip freeze to export and recreate environment

Commands:

pip freeze > requirements.txt
pip install -r requirements.txt

Problem 7

Objective: Create a simple web server using Flask

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, World!"

if __name__ == "__main__":
    app.run()

I hope these practice sets help you in applying advanced Python concepts efficiently! 😊

😎 Have a great time coding!

Emoji representing the notes: 📚

Happy Learning!

Source: Lecture/Presentation on Advanced Python Concepts.