0% found this document useful (0 votes)
2 views

python essentials for MLops

This lesson focuses on Python programming concepts including variables, types, conditionals, and error handling. Key points highlight the dynamic nature of variables, the use of f-strings for string formatting, and the importance of try/except blocks for managing exceptions. Additionally, it covers data structures such as lists, dictionaries, tuples, and sets, emphasizing their unique properties and use cases.

Uploaded by

21javeriasaleem
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

python essentials for MLops

This lesson focuses on Python programming concepts including variables, types, conditionals, and error handling. Key points highlight the dynamic nature of variables, the use of f-strings for string formatting, and the importance of try/except blocks for managing exceptions. Additionally, it covers data structures such as lists, dictionaries, tuples, and sets, emphasizing their unique properties and use cases.

Uploaded by

21javeriasaleem
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Module 1:

Lesson Reflection
Summary of Lesson:

This lesson covers working with variables, types, conditionals (if, else), exceptions, and
handling errors in Python. Key concepts include variable assignment, reassigning
variables, string formatting, type conversions, comparison operators, try/except blocks,
and catching multiple exception types.

Top 3 Key Points:

 Variables don't need explicit types, values can be dynamically reassigned


 F-strings provide readable string formatting using variables
 Try/except blocks catch and handle exceptions gracefully

5 Reflection Questions:

1. When might you want to reassign variables versus creating new variables?

2. How could you use f-strings to create a customized print output?

3. What is a scenario where try/except would lead to cleaner code than checking
return codes?

4. What might cause a TypeError during string concatenation?

5. Why catch specific exception types instead of generic Exception blocks?

Answers:

When to Reassign Variables vs. Create New Variables

 Reassign when you want to update a value while keeping the same reference (e.g.,
updating a loop counter or modifying a configuration setting).
 Create a New Variable when preserving the original value is important for
debugging, immutability, or readability (e.g., when transforming data without
losing the original state).
2: Using f-strings for Customized Print Output

 f-strings allow you to embed expressions directly in strings using {}.

This makes the code more readable and efficient compared to


concatenation or .format()

3: Using try/except for Cleaner Code

 Instead of checking return codes, which can clutter the code with
conditionals, try/except simplifies error handling.

Key Terms
 List - An ordered collection of values enclosed in square brackets []. Useful for
storing sequences of items.
 Index - The numeric position of an item in a list. Starts at 0 for first item. Used to
access items by position.
 Iteration - Repeated execution of code on successive list items. Done in Python
with a for-in loop.
 Dictionary - Unordered collection of key-value pairs denoted with curly braces
{}. Keys map to associated values.
 Key - Unique identifier that is used to look up values in a dictionary. Looks up are
very fast.
 Value - Data associated with a given key in a dictionary. Values can be any
Python data type.
 Tuple - Fixed-size, immutable ordered collection similar to a list. Denoted with ().
Useful when data shouldn't change.
 Set - Unordered collection of unique objects. Helpful for removing duplicates and
set operations.
 Membership - Ability to check if a value is contained in a collection like lists,
dictionaries, tuples, or sets.
 Methods - Built-in functions that allow manipulating and interacting with data
structures.
 Iteration - The process of repeatedly executing code on each item in a collection
one by one.
Reflection Questions

1. When would you want to use a tuple over a list?


2. What real-world examples can be modeled with dictionaries?
3. How could sets help improve the efficiency of a program?
4. What issues can arise from nested data structures?
5. Why is proper data structure selection important when coding?

Challenge Exercises

1. Implement a phone book as a dictionary.


2. Find the most frequent words in a text file using sets.
3. Filter user-submitted comments stored in a list for profanity.
4. Build a histogram from word counts using dictionaries.
5. Convert a deeply nested list to a flat list.

When would you want to use a tuple over a list?

• Tuples are immutable, meaning they can’t be changed after creation.

• Use a tuple when you need to ensure data integrity (e.g., coordinates, database keys).

• Tuples are slightly faster than lists due to immutability.

2. What real-world examples can be modeled with dictionaries?

• A phone book (name → phone number).

• Student grades (student ID → grade).

• API responses (JSON-like key-value data).


3. How could sets help improve the efficiency of a program?

• Sets store only unique values, preventing duplicates automatically.

• Membership checks (x in set) are faster than lists due to hashing.

• Useful for operations like intersection, union, and difference.

4. What issues can arise from nested data structures?

• Increased complexity and harder debugging.

• More memory usage and potential performance bottlenecks.

• Difficult traversal and access if deeply nested.

5. Why is proper data structure selection important when coding?

• Optimizes speed, memory, and readability.

• Prevents unnecessary complexity.

• Ensures code scalability and maintainability.

When would you want to use a tuple over a list?

• Tuples are immutable, meaning they can’t be changed after creation.

• Use a tuple when you need to ensure data integrity (e.g., coordinates, database keys).

• Tuples are slightly faster than lists due to immutability.

2. What real-world examples can be modeled with dictionaries?

• A phone book (name → phone number).

• Student grades (student ID → grade).

• API responses (JSON-like key-value data).

3. How could sets help improve the efficiency of a program?

• Sets store only unique values, preventing duplicates automatically.


• Membership checks (x in set) are faster than lists due to hashing.

• Useful for operations like intersection, union, and difference.

4. What issues can arise from nested data structures?

• Increased complexity and harder debugging.

• More memory usage and potential performance bottlenecks.

• Difficult traversal and access if deeply nested.

5. Why is proper data structure selection important when coding?

• Optimizes speed, memory, and readability.

• Prevents unnecessary complexity.

• Ensures code scalability and maintainability.

Lesson Reflection
Top 4 Key Points

 Lists index starting at 0 and preserve order when appending items

 Dictionaries map keys to values for efficient lookup time

 Tuples act like immutable lists useful when data shouldn't change

 Sets only allow unique elements, automatically removing duplicates

When would using a dictionary for lookups be more efficient than searching a list?

• Dictionaries provide O(1) average-time complexity for lookups using hashing, while lists
require O(n) time in worst cases.

• If frequent lookups are needed (e.g., user authentication, config settings), a dictionary is
significantly faster.

2. How could tuples ensure code doesn’t unintentionally alter data?

• Since tuples are immutable, they prevent accidental modifications.


• Useful for fixed data like GPS coordinates ((latitude, longitude)) or database keys.

3. What real-world data would best fit sets that required uniqueness?

• Email addresses in a mailing list.

• Unique product IDs in an inventory.

• Hashtags used in a social media post.

4. Why is order important for some use cases but irrelevant for others?

• Important when dealing with sequential operations (e.g., processing a queue, maintaining
historical data).

• Irrelevant when checking membership or uniqueness (e.g., user permissions, category


tags).

5. What built-in methods did you find most useful for data structures?

• dict.get(key, default): Avoids KeyErrors when fetching dictionary values.

• set.add(value): Ensures unique values without duplicates.

• list.sort() / sorted(iterable): Helps maintain ordered lists efficiently.

• tuple.count(value): Useful for checking frequency in immutable collections.

KEY ITEMS:
loop: A keyword used for an indefinite loop that runs forever until it is broken out
of using a break statement or another control flow mechanism.

 if let: A construct allowing assignment and conditional execution based on the


result of an expression, such as checking if an optional value contains a specific
type (e.g., an integer).
 shadowing: The practice of redefining a variable with the same name in the
same scope to take on new characteristics or values.

 type annotations: Explicitly specifying the data type for variables,


expressions, and other elements within Rust code to ensure proper compilation
and execution.

 option: A wrapper over an optional value that can contain either a concrete value
(e.g., integer) or None.

 sum: An enum used as a wrapper over an option in the context of this lesson; it
provides a convenient way to work with options, especially when combined with
pattern matching and if let statements.

 while loop: A control flow mechanism that continues executing while a specific
condition is met.

 for loop: A control flow mechanism used for iterating over sequences (e.g.,
ranges or vectors) in Rust.

 continue: A keyword allowing skipping to the next iteration of a loop when


certain conditions are met, such as an odd number in this lesson's example.

 break: A keyword that allows breaking out of loops and other control flow
mechanisms once specific criteria have been satisfied (e.g., finding a seven).

You might also like