PYT-101 Sprint Summary

Modified on Wed, 23 Jul at 1:55 PM

TABLE OF CONTENTS


PYT-101

Sprint summary

Getting Started

Topic 1: Python Intro


-   Introduction to Python

Python is a beginner-friendly, high-level programming language that’s widely used for data analysis due to its simplicity and powerful libraries.

What is it?
A versatile programming language popular in data science, automation, and application development.

Where is it used?
Used across analytics, machine learning, web development, and automation—especially with tools like Pandas, NumPy, and Jupyter Notebooks.

How is it used?




• Write your first line of code 


print("Hello, World!")



--- Takeaways / best practices
• Python is readable and intuitive—ideal for beginners
• Start with basic syntax before jumping to libraries
• Consistent indentation is critical in Python
• Practice small scripts to get familiar with flow

-   DataTypes

Every piece of data in Python has a type understanding these helps you choose the right operations and tools for analysis.

What is it?
Categories that define the kind of value a variable holds, such as integers, floats, strings, and booleans.


Numeric Data Types:

int i.e. integers. E.g.: -2, -153, 0, 12, 1

float: A decimal point number. E.g.: -1.5, 0.432, 1.44, 59.732, 1e3 (1 x 10^3)


Strings used for text. E.g.: "hello", "abracadabra", and others


Booleans: Used for logical operations. true, false


Where is it used?
Used in data cleaning, calculations, and ensuring the right format in analytics pipelines.

How is it used?
• Assign values to variables (e.g., x = 10, name = "Alice")
• Use type() to check the data type of any value
• Apply appropriate operations based on type (e.g., numeric ops on int/float)
• Convert types using casting (int(), str(), float(), etc.)

--- Takeaways / best practices
• Always verify data types before applying operations
• Type mismatches cause errors in code and logic
• Learn how to switch between types when needed (e.g., for input handling)
• Strong understanding of types helps when using libraries like Pandas

-   Variables, Printing

Variables store data, and printing helps you see it essential tools for debugging and data flow tracking.



What is it?
Variables are named containers for storing data, and print() is used to display values or results.

Where is it used?
Used in every Python program to manage and observe data through the analysis flow.

How is it used?
• Define variables with = 


age = 25


• Use print(variable) to view values in console
• Combine text and variables with f-strings 


print(f"Age is {age}")


• Print intermediate results for debugging or testing


--- Takeaways / best practices
• Use clear, descriptive variable names for readability
• Use print() often while learning to understand what your code is doing
• F-strings are a clean, modern way to format output
• Don’t overwrite Python’s built-in names as variable names (e.g., list, sum)


-   Arithmetic operations

Whether it’s calculating averages, totals, or differences - arithmetic is the base of numeric analysis.

What is it?
Operations like addition, subtraction, multiplication, and division used to process numerical data.


Output:


Addition: 17

Subtraction: 7

Multiplication: 60

Division: 2.4

Modulus (Remainder): 2



Unary Arithmetic Operators:




Where is it used?
Foundational in calculations, KPI generation, financial analysis, and data transformations.

How is it used?
• Use basic operators: +, -, *, /, %, **
• Combine with variables or values (total = price * quantity)
• Use in functions or conditional expressions
• Apply as part of data cleaning (e.g., normalizing values)

--- Takeaways / best practices
• Understand integer vs float division (use / vs //)
• Use parentheses to clarify or group operations
• Combine with functions for reusable logic
• Be mindful of data type when doing arithmetic (e.g., string + number will fail)

-   Keywords in python

Keywords are reserved words that form the foundation of the language they can’t be used as variable names.

What is it?
Built-in Python words that serve specific purposes in code syntax (e.g., if, for, return).



Where is it used?
Used throughout code structures - loops, conditionals, functions, and more.

How is it used?
• Recognize and use keywords in writing control flow and logic
• View list of all keywords using import keyword; print(keyword.kwlist)
• Avoid naming variables with reserved keywords
• Use them to define structure and flow (e.g., def, if, else, while)

--- Takeaways / best practices
• Learn core keywords early—they form the grammar of Python
• Don't use them as variable names (e.g., for = 10 will throw an error)
• Understanding keywords helps you read and write code faster
• Refer to the keyword list often during the learning phase

-   Operator precedence

When you mix multiple operations, Python follows a priority order knowing this helps avoid wrong calculations.





What is it?
The set of rules that determines the order in which operations are evaluated in an expression.

Where is it used?
Used in all expressions involving multiple operators - common in calculations, conditions, and formulas.

Example:

Predict the output of the following arithmetic expression:

1 + 2 ** 3 * 4 / 5
= 1 + (2 ** 3) * 4 / 5
= 1 + (8 * 4) / 5
= 1 + (32 / 5)
= 1 + 6.4
= 7.4


How is it used?
• Python follows standard precedence (e.g., * before +)
• Use parentheses to override default order
• Evaluate expressions step by step for clarity
• Practice with complex expressions to build intuition

--- Takeaways / best practices
• Misunderstanding precedence can lead to incorrect results
• Always use parentheses for clarity and control
• Review the precedence table or cheat sheet when in doubt
• Test expressions in small pieces if something feels off


Tip:


Topic 2: If-Else & Functions


- Relational Operators ( > , < , >= , <= , == , != )

Relational operators help you compare values essential for filtering, logic, and conditional checks in your code.

What is it?
Operators used to compare two values and return a Boolean result (True or False).




Where is it used?
Used in filtering datasets, condition checks, loops, and decision-making logic.

How is it used?
• Use > to check if one value is greater than another: x > y
• Use <, >=, <= for less than and equality-based comparisons
• Use == to check for equality and != for inequality
• Use inside if statements or while filtering data
• Example: 


if age >= 18: print("Eligible")


--- Takeaways / best practices
• Always use == for comparison—not =
• Combine with logical operators for complex conditions
• Watch for type mismatches (e.g., 5 == "5" is False)
• Great for writing readable, rule-based conditions in code

- If Else statements

Conditional logic lets your code make decisions like filtering values or checking thresholds.

What is it?
Control structure that runs different blocks of code based on whether a condition is True or False.


If Statement:




Else Statement:


Where is it used?
Used in data checks, filtering logic, alert systems, and decision trees in scripts.

How is it used?
• Start with an if block: if condition:
• Add else: to handle the alternate case
• Optionally use elif for multiple conditions
• Example:

if score >= 90:
 print("A grade")
else:
 print("Below A")


--- Takeaways / best practices
• Indentation is critical—use consistent spacing
• Keep conditions readable and meaningful
• Use elif instead of multiple nested if statements
• Combine with functions for clean, modular logic

Indentation:

  • Indentation is critical and defines blocks of code in Python.

  • Each block must be consistently indented.

  • Use spacebar or tab to indent

  • Mixing tab and spaces is not allowed 




- Comments

Comments make your code readable and explain the why behind your logic especially important in collaborative or long-term projects.

What is it?
Text in your code that’s ignored by Python and used to explain or document logic.

Where is it used?
Used throughout scripts, especially in data transformation, analysis logic, and functions.

How is it used?

  • Single-line comment: # This is a comment

  • Multi-line comment:

'''
This is a
multi-line comment
'''


• Add comments before complex logic or functions
• Comment out test code during debugging

--- Takeaways / best practices
• Comment clearly, but avoid stating the obvious
• Use comments to explain "why", not "what"
• Keep them updated—outdated comments mislead
• Essential for collaborative analytics work


- Functions (Definition, Invocation)

Functions let you package logic into reusable blocks perfect for repetitive tasks in data analysis.

What is it?
A named block of code that performs a specific task and can be called (invoked) when needed.




Where is it used?
Used to modularize code in data processing, transformations, cleaning, and report generation.

How is it used?
• Define with def:

def greet(): 

     print("Hello")


• Invoke with the function name: greet()
• Organize logic into functions for reuse and clarity
• Add docstrings to describe the purpose

--- Takeaways / best practices
• Keep functions small and task-specific
• Use clear, descriptive names
• Always call the function with ()
• Use functions to avoid repeating code in notebooks or scripts


- Passing parameters to a function

Parameters make functions dynamic they let you process different inputs using the same code block.

What is it?
Variables passed into a function to customize its behavior.

Where is it used?
Used in flexible data operations like filtering, computation, or file reading.

How is it used?
• Define parameters in the function:

def add(a, b):

    return a + b


• Pass arguments during function call: add(3, 5)
• Use default values: def greet(name="User")
• Handle multiple parameters for complex logic




--- Takeaways / best practices
• Use positional or keyword arguments for clarity
• Default values are helpful for optional parameters
• Match number and type of arguments to definition
• Parameterized functions are reusable and testable

- Returning values from a function

Returning a value lets your function produce output you can reuse in other operations or assign to variables.

What is it?
The mechanism to send a result back to the calling code from a function.

Where is it used?
Used in calculations, transformations, summaries, and data pipeline steps.

How is it used?
• Use return to send output from a function:

def square(x): 

    return x * x


• Capture the result in a variable: result = square(4)
• Can return single or multiple values (as tuple)
• Use returned values in further logic or output

--- Takeaways / best practices
• Always use return when a result is needed elsewhere
• A function without return returns None
• Functions can return complex types like lists, dicts
• Use return statements to isolate key results cleanly

- Introduction to Crio Python Platform

The Crio Python platform is a hands-on coding environment designed to help you practice Python with real-world guided exercises.

What is it?
A browser-based learning platform for practicing Python interactively through curated modules.

Where is it used?
Used in learning paths for data analytics, backend dev, and Python basics in Crio workshops or sprints.

How is it used?
• Log in using your Crio credentials
• Navigate to the assigned Python module
• Complete code challenges in the in-browser editor
• Submit and get instant feedback on your solutions
• Track progress through modules and checkpoints

--- Takeaways / best practices
• Use the platform for focused, hands-on Python practice
• Read problem statements and test cases carefully
• Test edge cases to ensure code is robust
• Make use of Crio’s real-time feedback to improve fast


Topic 3: Logic & Scope


-   If-else

The if-else structure lets your code decide what to do based on specific conditions critical for filtering data and applying logic.

What is it?
A control flow statement that executes one block of code if a condition is true, and another if it’s false.

Where is it used?
Used in data filtering, condition-based calculations, validation checks, and decision rules.

How is it used?
• Write an if block with a condition:

if score >= 60:
    print("Passed")
else:
    print("Failed")


• Use indentation to define code blocks
• Combine with input or variable values to guide logic
• Use elif for multiple condition paths

--- Takeaways / best practices
• Always use consistent indentation (typically 4 spaces)
• Don’t forget the colon (:) at the end of condition lines
• Keep conditions simple and readable
• Ideal for creating rule-based data checks and outputs

-   Nested If/Else

Nested if/else allows deeper decision-making when conditions depend on previous outcomes.

What is it?
An if/else block placed inside another if/else block to handle multiple levels of logic.


Syntax


if condition1:

    #  Block 1: block of code to be executed if condition1 is true

elif condition2:

     #  Block 2: block of code to be executed if the condition1 is false and condition2 is true

else:

    #  Block 3: block of code to be executed if the condition1 is false and condition2 is false



Where is it used?
Used when a condition needs to be checked only if a prior condition is true, like multi-level categorization or validations.

How is it used?
• Write inner if/else blocks inside outer ones:


if age >= 18:
    if has_id:
        print("Allowed entry")
    else:
        print("ID required")
else:
    print("Not eligible")


• Properly align each block with correct indentation
• Use this structure when decisions depend on other decisions

--- Takeaways / best practices
• Avoid over-nesting; it can make code harder to read
• Use elif when possible to flatten logic
• Use comments or blank lines to improve clarity
• Perfect for layered rule systems or multi-factor conditions


-   Logical operators

Logical operators let you combine multiple conditions making your logic flexible and powerful.

What is it?
Operators like and, or, and not used to evaluate multiple conditions together.



Where is it used?
Common in multi-condition filters, data validations, and complex if-statements.

How is it used?
• Use and to ensure both conditions are true:

if age > 18 and has_id:
    print("Entry granted")


• Use or to allow either condition to be true:

if day == "Saturday" or day == "Sunday":
    print("Weekend")



Example:


--- Takeaways / best practices
• Use parentheses for clarity when combining multiple conditions
• Evaluate order of logic carefully (Python short-circuits)
• Combine with if-else for effective decision logic
• Keep each condition logically separate and easy to test

-   Understanding errors

Errors are a part of programming understanding them helps you debug and fix issues faster.

What is it?
Problems in code that stop execution or cause incorrect behavior categorized into syntax, runtime, and logical errors.

Where is it used?
Everywhere in coding—especially when working with user input, file handling, calculations, and data transformations.

How is it used?
• Common syntax error:

print("Hello  # Missing quote → SyntaxError


• Common runtime error:


print(10 / 0)  # ZeroDivisionError


• Use try-except blocks to handle runtime errors:


try:
    value = int(input("Enter number: "))
except ValueError:
    print("Invalid input")


• Use error messages to identify and trace issues

--- Takeaways / best practices
• Read error messages carefully—they usually tell you the file, line, and problem
• Use print statements or breakpoints for debugging
• Handle exceptions where input or data may vary
• Learn to differentiate between syntax, runtime, and logic errors


-   local and global scoped variables

Variable scope controls where a variable can be used understanding this avoids confusion and bugs.

What is it?
Scope determines whether a variable is accessible within a specific block (local) or across the entire script (global).

Where is it used?
In functions, loops, and modules to control data visibility and avoid conflicts.

How is it used?
• Local variable (inside function):

def greet():
    name = "Alice"
    print(name)


• Global variable (outside function):

name = "Bob"
def greet():
    print(name)


• Modifying global inside function:

count = 0

def increment():
    global count
    count += 1


--- Takeaways / best practices
• Prefer local variables to avoid unintended side effects
• Use global only when necessary and with caution
• Always initialize global variables before using them in functions
• Helps maintain clean, modular, and bug-free code



Topic 4: Python Loops


- Loops in Python

What is it?
A loop is a programming construct that repeats a block of code multiple times based on a condition or sequence.

Where is it used?
Used in data processing, iterations over datasets, applying operations row-by-row, and automation tasks.

How is it used?
• Use while for condition-based loops
• Use for for sequence-based iteration (lists, ranges, dictionaries)
• Place the block of code inside the loop using indentation
• Apply break or continue to control the flow if needed

--- Takeaways / best practices
• Use loops to avoid repeating similar code
• Always ensure your loop condition has an exit path to prevent infinite loops
• Keep loops efficient, especially with large data
• Combine with functions for cleaner, modular code

- While Loop

What is it?
A while loop executes a block of code repeatedly as long as a given condition remains true.


Syntax:

while condition:

    # Code to execute while the condition is True

    print("Code executed successfully")



Where is it used?
Used when the number of iterations is not fixed in advance, such as reading input until a condition is met.

How is it used?
• Define a condition: while condition:
• Inside the loop, update something so the condition will eventually become false
• Example:

i = 0
while i < 5:
print(i)
i += 1



--- Takeaways / best practices
• Make sure the condition eventually becomes false
• Ideal for loops dependent on user input or dynamic conditions
• Avoid infinite loops—always have a stopping mechanism
• Use break carefully to exit mid-loop if needed

- For Loop

What is it?
A for loop iterates over a sequence like a list, string, tuple, or range.


Syntax:

for variable in sequence:

    # Code to execute

    print("Code executed successfully !")



Where is it used?
Used for fixed iteration over datasets, columns, or predefined values.

How is it used?
• Use for followed by variable and iterable:

for item in list:
print(item)


• Common with range:

# print numbers 1-4 with loops


for i in range(5):
print(i)


• Loop through lists, dictionaries, or files

--- Takeaways / best practices
• Best for known-length iterations
• Use enumerate() if you need the index
• Use zip() to loop over multiple sequences
• Clean and readable way to apply repetitive tasks

- While vs for : use case

What is it?
The choice between while and for depends on whether you're looping based on a condition or over a sequence.

Where is it used?
Used when deciding how best to structure loops in scripts, especially during data processing or user interactions.

How is it used?
• Use for when you know how many times to loop or have a sequence (like a list or range)
• Use while when you don’t know how many times, but want to loop until a condition is false
• Example use case for for: Iterating over rows in a dataset
• Example use case for while: Waiting for valid input or a signal

--- Takeaways / best practices
• Choose for for fixed iterations and cleaner syntax
• Use while for more flexible, condition-driven loops
• Avoid overcomplicating—select the loop type that keeps logic clear
• Both loops can be controlled using break/continue when needed

- break/continue/pass

What is it?
Control statements used inside loops to manage flow break exits the loop, continue skips to the next iteration, and pass does nothing.

Where is it used?
Used in data validation, skipping faulty rows, exiting loops early, or placeholder logic in loops/functions.

How is it used?
• break: Exit the loop entirely
Example:


for i in range(1, 6):

    if i == 3:

        break

    print(i)


Output:

1

2



• continue: Skip current iteration
Example:


for i in range(1, 6):

    if i == 3:

        continue

    print(i)


Output:


1

2

4

5



• pass: Placeholder for future logic


Example:

for i in range(1, 4):

    if i == 2:

        pass  # Do nothing here

    print(i)


Output:


1

2

3



--- Takeaways / best practices
• Use break when a condition requires early termination
• Use continue to skip undesired cases without exiting the loop
• Use pass as a placeholder during development
• Avoid overusing these for clarity—structure logic cleanly when possible


Topic 5: Lists & Sequences


-   Lists and Sequences

Lists are ordered collections used to store multiple values in a single variable—ideal for handling datasets, rows, and grouped data.

What is it?
A list is a mutable sequence used to store collections of items, like numbers, strings, or mixed data.

Where is it used?
Used in storing rows of data, filtering results, aggregating values, or processing collections in data analytics.

How is it used?
• Create a list:

fruits = ["apple", "banana", "cherry"]




• Access elements by index:

fruits[1] → "banana"


• Modify elements:

fruits[0] = "mango"


• Append new items:

fruits.append("orange") → ['mango', 'banana', 'cherry', 'orange']



--- Takeaways / best practices
• Lists are zero-indexed: the first element is at index 0
• Use lists to store dynamic sets of related data
• Lists are mutable—you can change them after creation
• Use with loops or functions to process collections easily

-   Slicing

Slicing helps you access a portion of a list—great for subsetting data, trimming input, or analyzing parts.

What is it?
A technique used to extract a portion of a list or string using a start, stop, and optional step.

Where is it used?
Used when you need only part of a dataset or want to manipulate a range of items.

How is it used?
• Basic syntax: 

list[start:stop:step]


  • The [start:stop:step] part is known as the slicing operator. Its syntax consists of a pair of square brackets and three index values - start, stop and step. 

  • The :step is optional. You typically use it only in those cases where you need a step value different from 1.

  • The resulting slice doesn’t include the item at the stop index.

  • Default values: start: 0, stop: len(list), step: 1


• Example:

numbers = [10, 20, 30, 40, 50]
numbers[1:4] → [20, 30, 40]


• Omit start/stop to default to beginning or end:

numbers[:3] → [10, 20, 30]
numbers[2:] → [30, 40, 50]


• Use steps:
numbers[::2] → [10, 30, 50]

--- Takeaways / best practices
• Slicing is non-destructive—it returns a new list
• Stop index is exclusive (i.e., not included in result)
• Use negative indices to slice from the end
• Useful for pagination, batching, or time-based slicing

-   max, min, len, sum, abs

These built-in functions help summarize and inspect lists quickly—ideal for numeric analysis.

What is it?
Functions that perform basic mathematical or structural operations on sequences or numbers.

Where is it used?
Used in data summaries, basic statistics, validations, and logic.

How is it used?

• max(): Returns the highest value
max([3, 7, 2]) → 7
• min(): Returns the smallest value
min([3, 7, 2]) → 2
• len(): Returns the number of elements
len([10, 20, 30]) → 3
• sum(): Adds all values
sum([1, 2, 3]) → 6
• abs(): Returns absolute value
abs(-10) → 10


--- Takeaways / best practices
• Use len() before accessing list elements to avoid index errors
• Use sum() with len() to compute averages:
avg = sum(nums)/len(nums)
• Always handle edge cases like empty lists to avoid errors
• abs() is great for calculating distances or handling negative values


Topic 6: 2D Lists & Control Flow


- 2D Lists - create, update, iterate, access

2D lists are like tables or spreadsheets—great for representing rows and columns of structured data.

What is it?
A 2D list is a list of lists, used to store data in rows and columns format.




Where is it used?
Used in representing tabular data, matrices, grids, and datasets where each row contains multiple values.

How is it used?


Example:

• Create a 2D list:
data = [[10, 20], [30, 40], [50, 60]]
• Access elements using two indices:
data[1][0] → 30
• Update a value:
data[2][1] = 65 → data becomes [[10, 20], [30, 40], [50, 65]]


• Iterate using nested loops:


--- Takeaways / best practices
• Think of each inner list as a row in a table
• Use clear loop variables to avoid confusion during iteration
• Useful for grid-based analysis or simulation data

- Nested Loops

Nested loops allow you to iterate through multidimensional data—such as each cell in a table or grid.

What is it?
A loop inside another loop; the inner loop completes all iterations for each iteration of the outer loop.

Where is it used?
Used in processing 2D lists, working with matrix data, or applying operations on every combination of values.

How is it used?
• Example with 2D list:

data = [[1, 2], [3, 4]]

for row in data:

    for val in row:

        print(val)


Output:

1

2

3

4



• Outer loop handles rows, inner loop handles columns
• Can be extended to 3D lists with more nesting


Updating Values in 2D Lists:




--- Takeaways / best practices
• Clearly distinguish outer and inner loop variables
• Avoid too many levels of nesting—it reduces readability
• Combine with if conditions to apply logic at each level
• Very effective for row-column based operations

- control/jump statements in 2D loops(break, continue)

Jump statements help you manage nested loops efficiently—skip, stop, or move within a dataset based on conditions.

What is it?
Special commands like break and continue used to control the flow of nested loops.

Where is it used?
Used in data filtering, skipping specific cells, stopping early when conditions are met, or avoiding unnecessary processing.

How is it used?
• break: Exit the inner loop entirely

# Example 2D list (matrix)

matrix = [[1, 2, 3],[4, 3, 6]]

# Iterate through rows and columns

for row in matrix:

    for x in row:

        if x == 3:

            break

        print(x)


Output:

1

2

4



• continue: Skip current iteration

# Example 2D list (matrix)

matrix = [[1, 2, 3],[4, 5, 6]]


# Iterate through rows and columns

for row in matrix:

    for x in row:

        if x == 3:

continue  # Skip the iteration if x equals 3

        print("The number is", x)


 Output:

The number is 1

The number is 2

The number is 4

The number is 5

The number is 6




--- Takeaways / best practices
• Use break to stop looping when further work is unnecessary
• Use continue to skip bad or unwanted data without breaking the loop
• Use flags or structured logic to avoid accidentally breaking outer loops
• Helpful for real-time validations, cleaning, or incomplete data handling


Topic 7: Tuples & Sets


-   Tuples

Tuples are fixed collections like lists, but you can't change them—ideal for storing constant data or as dictionary keys.

What is it?
An immutable sequence used to store multiple items, usually of related data.

Where is it used?
Used in situations where data shouldn’t change, like coordinates, records, or when returning multiple values from a function.

How is it used?

• Define a tuple:
point = (10, 20)
• Access elements:
point[0] → 10


• Use in function returns:
def stats(): return (avg, max_val)


• Iterate using loops:
for val in point: print(val)

--- Takeaways / best practices
• Tuples use parentheses, lists use square brackets
• Ideal for data that must remain unchanged
• Can be used as keys in dictionaries (unlike lists)
• Good for returning multiple values from functions

-   Immutability

Immutability means a data structure can’t be changed after creation this ensures consistency and safety in data handling.

What is it?
A property where a variable or structure cannot be modified after it's defined.

Where is it used?
Important in cases like using tuples as dictionary keys, or ensuring clean, consistent data across analysis steps.

How is it used?
• Tuples are immutable:

t = (1, 2, 3)
t[0] = 5 → Error: 'tuple' object does not support item assignment


• Strings are also immutable in Python
• Immutability helps prevent accidental changes to reference data

--- Takeaways / best practices
• Use immutable types for fixed reference data
• Prevents bugs caused by unexpected changes in large projects
• Immutable structures are safer when shared across functions or modules
• Helps ensure reproducibility in data pipelines

-   enumerate()

enumerate() makes it easy to loop over items with their index - great for tracking positions in your data.

What is it?
A built-in Python function that returns both index and value when looping through a sequence.

Where is it used?
Used in iteration when you need to track position or apply logic based on index.

How is it used?

• Without enumerate:
i = 0
for val in data:
print(i, val)
i += 1


• With enumerate:
for i, val in enumerate(data):
print(i, val)

Example:


code_status = [True, False, False, True, False, True, True]


for index, practiced in enumerate(code_status):

    if practiced:

        print("Day:", index + 1, "- Practiced")

    else:

        print("Day:", index + 1, "- Did not practice")


Output:

Day: 1 - Practiced

Day: 2 - Did not practice

Day: 3 - Did not practice

Day: 4 - Practiced

Day: 5 - Did not practice

Day: 6 - Practiced

Day: 7 - Practiced



--- Takeaways / best practices
• Clean and readable alternative to manual counters
• Useful when you need both index and value in loops
• Can start index at a custom value: enumerate(list, start=1)
• Enhances loop clarity and debugging

-   zip()

zip() lets you loop over multiple sequences in parallel ideal for combining columns or matching paired data.


Syntax:  

zip(*iterables) 


Parameters:

  • *iterables refers to one or more iterable objects (like lists, tuples, etc.) that we want to combine. The function pairs elements from these iterables into tuples based on their positions.

  • Return value:

  • Returns an iterator of tuples, where each tuple contains elements from the input iterables at the same index.



What is it?
A built-in function that pairs elements from multiple sequences into tuples.

Where is it used?
Used in combining lists (e.g., names and scores), iterating over datasets in parallel, or creating dictionaries.

How is it used?
• Example:

names = ["A", "B", "C"]
scores = [85, 90, 88]
for name, score in zip(names, scores):
print(name, score)



• Convert to list:

list(zip(names, scores)) → [('A', 85), ('B', 90), ('C', 88)]



--- Takeaways / best practices
• Useful when working with two or more aligned datasets
• Stops at the shortest sequence by default
• Use zip(*zipped_list) to unzip
• Enhances readability in paired iteration

-   Sets

Sets store unique values with no order perfect for removing duplicates or fast membership checks.

What is it?
An unordered, mutable collection of unique elements.

Where is it used?
Used in duplicate removal, comparison, and fast lookup in large datasets.

How is it used?

• Create a set:
s = {1, 2, 3, 3, 2} → s becomes {1, 2, 3}


• Add item:
s.add(4)


• Check existence:
2 in s → True


• Perform operations:
set1 & set2 (intersection), set1 | set2 (union)


--- Takeaways / best practices
• Use sets for fast membership testing
• Automatically removes duplicates
• Cannot store mutable items like lists
• Great for data deduplication and filtering tasks


Topic 8: Dictionaries


- Introduction to Dictionaries

Dictionaries store data as key-value pairs ideal for labeled data like records, JSON responses, or configurations.

What is it?
A dictionary is an unordered collection where each item is stored as a pair of key and value.

Where is it used?
Used in JSON parsing, structured data representation, column-wise storage, and lookups based on labels.

How is it used?

• Create a dictionary:
student = {"name": "Alice", "score": 85}


• Access value by key:
student["name"] → "Alice"


• Add a new key-value pair:
student["age"] = 20


• Update value:
student["score"] = 90



--- Takeaways / best practices
• Keys must be unique and immutable (strings, numbers, tuples)
• Values can be any data type
• Ideal for storing structured records where position doesn’t matter
• Avoid using large strings or mutable types as keys


- Dictionary Operations and Iteration

Dictionaries offer flexible operations like access, update, deletion, and looping—great for working with labeled datasets.

What is it?
Operations that allow reading, updating, and processing dictionary data.

Where is it used?
Used in data manipulation, metadata handling, aggregating results, and mapping values.

How is it used?

• Get all keys:
student.keys() → dict_keys(['name', 'score', 'age'])


• Get all values:
student.values() → dict_values(['Alice', 90, 20])


• Iterate through items:
for key, value in student.items():
print(key, value)


• Delete a key:
del student["age"]



--- Takeaways / best practices
• Use .get(key, default) to avoid key errors
• Iterate with .items() to access both key and value
• Keys are case-sensitive
• Check for key existence before access using if key in dict

- Dictionary Keys vs List Indexes

While lists use numeric positions, dictionaries use keys allowing you to label and access data semantically.

What is it?
A comparison between how data is accessed in dictionaries (by key) and lists (by index).

Where is it used?
Helps choose the right data structure based on whether data is label-driven or position-based.

How is it used?
• List example:



names = ["Alice", "Bob"]
names[0] → "Alice"


• Dictionary example:

scores = {"Alice": 90, "Bob": 85}
scores["Alice"] → 90


• Lists are ordered; dictionaries (in Python 3.7+) preserve insertion order
• Lists use numeric indices; dictionaries use descriptive keys

--- Takeaways / best practices
• Use lists when order and position matter
• Use dictionaries when you want to access data by name or label
• Lists are better for ordered data processing; dictionaries are best for key-value lookups
• Choose based on how you'll retrieve and use the data


Topic 9: Strings & Input

-   String manipulation(split, strip, slice, f-strings)

What is it?
String manipulation involves modifying, extracting, or formatting string data using built-in functions.

Where is it used?
Used in data cleaning, parsing files, formatting outputs, and preparing text data for analysis.

How is it used?

• split() breaks a string into a list:
"apple,banana".split(",") → ['apple', 'banana']


• strip() removes whitespace:
" hello ".strip() → "hello"


• Slicing extracts parts:
name = "Python"
name[1:4] → "yth"


• f-strings format values into strings:
name = "Alice"
print(f"Hello, {name}!") → "Hello, Alice!"


f-strings:



--- Takeaways / best practices
• Use strip() to clean input and remove noise
• Use split() for CSV-style parsing or breaking inputs
• f-strings are the most efficient and readable way to format output
• Combine these methods for robust data cleaning and transformation


-   Typecasting

Typecasting helps convert data between types for example, strings to numbers.

What is it?
The process of converting one data type to another using built-in functions.

Where is it used?
Used when working with inputs, correcting data types, or preparing variables for operations (e.g., int to float, str to int).

How is it used?

• Convert string to integer:
int("5") → 5


• Convert integer to string:
str(100) → "100"


• Convert string to float:
float("3.14") → 3.14


• Useful in input processing:
age = int(input("Enter your age: "))


--- Takeaways / best practices
• Always validate data before casting to avoid errors
• Use int(), float(), str() carefully on user input or file data
• Combine with try-except to handle invalid conversions
• Proper type conversion is essential for accurate calculations


-   Working with standard input via terminal

Reading input from the user allows dynamic data collection and interaction with scripts during runtime.

What is it?
Using input() to collect data from the terminal during program execution.

Where is it used?
Used in scripts where user-defined values are required for analysis, such as thresholds, file names, or parameters.

How is it used?
• Get input as a string:

name = input("Enter your name: ")


• Convert input if needed:

age = int(input("Enter your age: "))


• Combine with conditions:

if age >= 18:
print("Adult")



--- Takeaways / best practices
• Input is always received as a string—typecast when needed
• Prompt clearly so the user knows what to enter
• Handle invalid input using validation or try-except
• Keep terminal interaction minimal and clean in analytics scripts

-   SFP

SFP (Structure, Flow, Purpose) is a coding guideline that ensures your code is organized, logical, and focused on solving the right problem.

What is it?
A concept to write code with proper structure (organization), flow (logical order), and purpose (goal alignment).

Where is it used?
Used in writing clean, maintainable scripts in projects, especially in analytics pipelines and collaborative codebases.

How is it used?
• Structure: Use functions, variables, and comments to organize code
• Flow: Keep logic sequential and clear (input → process → output)
• Purpose: Focus each section on solving a specific part of the problem
• Example:

Input: Get data
Processing: Clean and analyze
Output: Print or store results

--- Takeaways / best practices
• Write code as if someone else will read it tomorrow
• Avoid mixing unrelated logic in one place
• Follow consistent naming and formatting practices
• SFP improves code readability, collaboration, and reusability

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article