Python Tutorial for Beginners
|

Python Master Class for Beginners 2026: The Roadmap to an IT Career

Master Python from scratch with Jithin. This RootSaid IT guide covers syntax, loops, dictionaries, and error handling to prepare you for IT jobs and interviews.

This comprehensive Python Master Class guide provides a structured roadmap for beginners transitioning into professional IT roles. I walk you through essential scripting foundations, including variable assignment, control flow logic, data collections, and error handling. This RootSaid IT tutorial ensures you understand real-world implementation, common coding failures, and the specific best practices neccessary to secure roles in DevOps, Networking, and Cybersecurity.

CategoryDetails
AuthorJithin (RootSaid IT)
Time2- 7 Hours
DifficultyAbsolute Beginner
EnvironmentVS Code / Python 3.10+
Primary GoalIT Career Foundation

Module 1 : Python Scripting Basics; How do I start outputting data in Python?

Every journey in programming begins with understanding how to communicate with the computer. The print function and proper syntax are the primary tools I use to verify that my logic is working correctly. Without these basics, you would have no way to see the output of your calculations or debug your script when something goes wrong.

Learning about syntax errors and comments teaches you the grammar of Python. Just as a misplaced comma can change the meaning of a sentence in English, a missing bracket in Python can stop an entire enterprise-level application from running. Comments ensure that your code remains readable for your future self and your teammates in a professional IT environment.

One practical example

We start by creating a Hello World script to confirm my environment was set up. I emphasized that the computer only understands exact instructions, and even a small typo can lead to a program failure.

Syntax

print("Your Message Here")
# This is a comment - it is ignored by Python

The print function requires parentheses, and text data must be enclosed in double quotes. The hash symbol is used to create comments, which are vital for documenting your code without affecting the program’s execution.

Real Code Example

print("Hello World from Rootsat IT")
print("*" * 25)

In our script, we printed a welcome message and then used string multiplication to print 25 stars in a single line. This demonstrated how to create visual separators in a console output efficiently.

Module 2 : Variables and f-strings; Why should I use f-strings for my variable output?

Variables are the heart of any dynamic program because they allow us to store and manipulate information. Instead of hard-coding values, variables act as containers or reserved spaces in the system memory. This allows a single script to handle different sets of data every time it is run, which is essential for processing user accounts or network traffic.

I also use f-strings to make my code more efficient and readable. Joining text and variables was previously prone to errors and looked messy. With f-strings, we can embed variables directly into our sentences, ensuring that the final output presented to the user is clean, accurate, and professional.

One practical example

I assigned a value to a variable and used it in a sentence. This is exactly how banking apps show your current balance where they store your balance in a variable and display it inside a pre-written sentence.

Syntax

variable_name = value
print(f"Text goes here {variable_name}")

To create a variable, you use the assignment operator. When printing with f-strings, you place the letter f before the opening quote and wrap your variable name in curly braces inside the string.

Real Code Example

fruit_count = 22
print(f"Total fruit count is {fruit_count}")

In the script, I assigned the number 22 to fruit_count. Instead of just printing the number, I used an f-string to provide context, outputting the sentence as expected.

Module 3 : Data Types and Strings; How do I transform and identify different data types?

Computers treat different types of information differently. Understanding numeric data types like Integers and Floats is vital for preventing logic errors. If you try to perform math on a piece of text instead of a number, your program will crash immediatley. Identifying the type of data is a core skill for any IT professional.

String methods allow us to clean and transform text data automatically. In IT jobs, you will often receive messy data. By using built-in methods, we can standardize this data instantly, saving hours of manual editing and ensuring data integrity across large systems.

One practical example

I used a Float to represent a decimal temperature and a string for a fruit name. I then showed how to automatically capitalize words to make them look professional in a report.

Syntax

my_string = "hello"
print(my_string.upper())
print(my_string.title())
print(len(my_string))

Numeric types are defined by writing numbers with or without decimals. String methods are called by adding a period after the variable name followed by the method name and parentheses.

Real Code Example

storage_temperature = 30.8
fruit_name = "apple"
print(fruit_name.title())

In the script, I defined a Float for temperature. I then used the title method on the string apple to output Apple, demonstrating how to standardize user input for professional inventory systems.

Module 4 : Boolean Logic; Why is True or False the most basic decision unit?

Boolean logic is the foundation of all computer decision-making. A Boolean can only be one of two values: True or False. In the IT world, this represents on or off, success or failure, or yes or no. Without Booleans, a computer would have no way to verify if a condition has been met.

I also use Booleans to represent the presence of data. In Python, an empty string or a zero is considered False, while any actual data is considered True. Mastering this allows you to write scripts that check if a user has actually filled out a form or if a network port is open.

One practical example

I used a Boolean to track the status of a product. If a product was defective, the variable would be True, allowing the system to automatically flag it for removal from the assembly line.

Syntax

is_active = True
is_empty = False
print(type(is_active))

Booleans must always start with a capital letter. They do not use quotes because if you put quotes around them, Python will treat them as a String instead of a logical state.

Real Code Example

is_defective = True
if is_defective:
    print("This item is damaged.")

In our lesson, I showed that by setting the variable to True, we could create a logical trigger that tells the program exactly when to alert the user about a problem.

Module 5 : If Condition Logic; How can I make my script react to different sensor values?

Logic is what makes software smart. Without conditional statements, a program would simply follow a straight line from start to finish. In the real world, software must react to changing conditions, such as deciding whether a password is correct or if a systems temperature is too high.

Conditional chains allow for complex branching. An engineer might write a script that has several layers of checks. Mastering if, elif, and else allows you to build complex systems that operate without human intervention, responding to data in real-time.

One practical example

I built a script that monitored environmental conditions. Depending on the numerical data received from a sensor, the program chose between three different responses to manage the environment.

Syntax

if condition:
    # action 1
elif another_condition:
    # action 2
else:
    # default action

Note the colon at the end of each statement and the mandatory indentation. The elif statement is used to check multiple specific conditions in order.

Real Code Example

quality = 105
if quality > 100:
    print("Air quality is low. Turn on air purifier.")
elif quality < 50:
    print("Air quality is perfect.")
else:
    print("Air quality is good.")

In the script, since 105 is greater than 100, the program prints the instruction to turn on the purifier. This illustrates a simple automated decision-making process.

Module 6 : Switch Case Match Statement; When is match-case better than a long elif chain?

When you have a long list of specific values to check, using a chain of if-elif statements can make your code look cluttered. Python introduced the match-case statement to handle multiple specific conditions with much cleaner syntax. This is very similar to the switch case found in other languages.

This is highly useful for handling user commands or menu selections. If you are building a tool where a user types Start, Stop, or Restart, a Match-Case block allows you to map those specific strings to actions clearly. This makes the code easier to maintain and update in the future.

One practical example

Imagine a user interface with several different commands. Instead of writing five elif blocks, I use match-case to direct the programs flow based on exactly what the user typed.

Syntax

match variable:
    case "value1":
        # logic 1
    case "value2":
        # logic 2
    case _:
        # default logic

The match keyword looks at the variable, and each case block represents a possible match. The underscore acts as the default or wildcard case if none of the other values match.

Real Code Example

command = "Restart"
match command:
    case "Start":
        print("System starting...")
    case "Stop":
        print("System stopping...")
    case "Restart":
        print("System rebooting...")
    case _:
        print("Unknown command.")

In this example, Python immediately identifies the Restart case and skips the others. This is a much more elegant way to handle multiple-choice logic than standard if-statements.

Module 7 : Error Handling; How do I stop my program from crashing when a zero is entered?

In a professional environment, having a program crash abruptly is unacceptable. When a script hits an error, like dividing by zero, Python stops the program entirely. Try-Except blocks act as a safety net, allowing the developer to catch these errors and handle them gracefully.

This is particularly important for user-facing applications. If a user enters the wrong type of data, you want the program to ask them to try again. Learning error handling is the difference between a beginner script and a production-ready tool.

One practical example

I simulated a math error by trying to divide 100 by zero. Normally, this would crash the computer, but I wrote code that simply explained the error to the user and kept the program running.

Syntax

try:
    # code that might fail
except ZeroDivisionError:
    # what to do on failure

The try block contains code that might fail. If an error occured, Python jumps immediately to the except block, preventing a system crash and allowing for a custom error message.

Real Code Example

try:
    result = 100 / number
    print(result)
except ZeroDivisionError:
    print("Cannot divide a number by zero")

When the user entered 0 in our script, the ZeroDivisionError was caught. Instead of a red error screen, the user saw a clean message.

Module 8 : For Loops; How can I automate a repetitive greeting for ten users?

Automation is the primary reason many companies use Python. If you have to perform a task 1,000 times, writing 1,000 lines of code is impossible. For loops allow us to write a single block of logic and repeat it for every item in a specific range or collection.

This is essential for data processing. Whether you are iterating through a list of thousands of IP addresses to check their status or sending a welcome email to a new batch of users, the for loop is your primary tool. It makes RootSaid ITs troubleshooting method much faster when checking logs.

One practical example

I used a for loop to repeat a welcome message exactly 10 times. This demonstrated how a small amount of code can handle a repetitive task without any manual effort.

Syntax

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

The range function generates a sequence of numbers. The loop then assigns each number to the variable item and executes the code inside the block until the sequence is finished.

Real Code Example

for counter in range(10):
    print(f"Hello from RootSaid IT, count: {counter + 1}")

In our script, I used the counter variable to print a message 10 times. I added 1 to ensure the user saw a human-friendly count from 1 to 10.

Module 9 : While Loops; How do I keep a prompt active until the user enters the right password?

Sometimes you dont know exactly how many times you need to repeat a task. You might need to keep a program running until a user decides to quit. This is where the While loop becomes necessary. It functions based on a conditional state.

A While loop checks a condition before every single repetition. As long as that condition remains True, the loop continues. This is the logic behind infinite processes, like a server waiting for a request or an application waiting for user input.

One practical example

I created a security gate. The program would keep asking the user for a password over and over again, only stopping once the correct password was finally entered.

Syntax

while condition:
    # repeat logic here

Be careful because if the condition never becomes False, the loop will run forever. This could crash your computer and is known as an Infinite Loop.

Real Code Example

password = ""
while password != "secret123":
    password = input("Enter the secret password: ")
print("Access Granted!")

In the script, the loop continued to prompt the user as long as the input did not match the secret string. Once the correct password was entered, the loop ended.

Module 10 : The Break Statement; How do I perform an emergency stop on an assembly line loop?

In automation, you often need an emergency stop. Even if a loop is supposed to run 100 times, a specific event might make further repetition useless or dangerous. The break statement allows the program to exit a loop immediately.

This is crucial for resource management. If you are searching for a specific file in a folder of 10,000 documents, you should break the loop as soon as you find it. There is no point in checking the remaining files once your goal is achieved.

One practical example

I modeled a factory assembly line. I told the loop to check 10 items, but if it encountered a Broken item, it would break the loop and shut down the whole machine for safety.

Syntax

for item in range(10):
    if item == 5:
        break

The break keyword immediately terminates the current loop and moves the program to the next line of code outside the loop block.

Real Code Example

if product == 8:
    print("Item 8 broken - stopping machine")
    break

In our factory script, when the counter hit 8, the program printed a danger message and executed the break. Items 9 and 10 were never checked.

Module 11 : The Continue Statement; How do I skip an item without stopping the entire automation?

Sometimes you dont want to stop the whole process but you just want to skip one specific item. The continue statement tells Python to stop the current iteration and jump immediately back to the top of the loop for the next item.

This is very helpful for filtering data. If you are processing a list of employee salaries but want to skip anyone who hasnt been paid yet, you use continue. It keeps the automation running while ignoring specific bad or irrelevant data points.

One practical example

In our factory assembly line, I found an item that was Out of Stock. I didnt want to shut down the factory so I just used the script to skip that empty slot and move to the next product.

Syntax

for item in range(10):
    if item == 5:
        continue

The continue keyword skips the remaining code in the current loop iteration and starts the next one immediatley.

Real Code Example

if product == 5:
    print("Item 5 out of stock - skipping")
    continue

In the script, when the loop hit item 5, it printed the skip message and jumped to item 6. The success message for item 5 was never printed.

Module 12 : Nested Loop Control; How do I combine skip and stop logic in one script?

Combining loops with conditional logic is how complex business rules are applied to data. Understanding how to nest these concepts allows you to build high-level scripts that can distinguish between minor errors and critical failures.

This Loop Control Logic is a core part of technical interviews. Employers want to see that you can not only repeat a task but also manage that repetition intelligently to save time and system resources.

One practical example

I combined all our loop knowledge to create a smart scanner that could successfully process good items, skip missing items, and emergency-stop for broken items.

Syntax

for item in sequence:
    if critical_error: break
    if minor_issue: continue

This structure represents the standard logical flow for most professional automation scripts used in DevOps and System Administration.

Real Code Example

for product in range(1, 11):
    if product == 5: continue
    if product == 8: break
    print(f"Successfully scanned product {product}")

The real-world script output showed products being processed in the correct order while respecting the skip and break rules defined in the logic.

Module 13 : Python Lists; Why are lists neccessary for storing ordered collections?

As programs grow, you need to manage groups of data rather than individual pieces. Lists allow you to store multiple items in a single variable in a specific order. This makes it easy to track things like a queue of customers or a set of IP addresses.

Without Lists, you would have to create a new variable name for every single piece of data which is impossible to manage. Lists are the primary way we organize and store ordered sequences of information in Python.

One practical example

I created an ordered list of fruits. By using a single variable, I was able to store an entire inventory and access any specific fruit using its position in the list.

Syntax

my_list = ["item1", "item2"]
print(my_list[0])

Lists use square brackets and items are separated by commas. Items are accessed via numerical indexes starting at 0.

Real Code Example

fruits = ["apple", "banana", "cherry"]
print(fruits[1])

In the script, I accessed the second item in our list. This demonstrated how professional software retrieves specific data points from a larger collection.

Module 14 : Python Dictionaries; How do key-value pairs make data retrieval faster?

While Lists are great for ordered items, Dictionaries are built for speed and searching. A Dictionary allows you to map a unique Key to a specific Value. This is the foundation of modern data structures.

Instead of searching through a long list, a Dictionary allows you to jump directly to the info you need using a name or ID. This is exactly how contact lists on your phone or database records in a cloud environment are structured.

One practical example

I created a phone book dictionary. Instead of looking through a list of numbers, I simply provided a name to the program, and it instantly gave us the correct phone number.

Syntax

my_dict = {"Key": "Value"}
print(my_dict["Key"])

Dictionaries use curly braces. Each entry consists of a Key followed by a colon and then its Value. You access the data by providing the Key name in square brackets.

Real Code Example

phone_book = {"Alice": "555-0101", "Bob": "555-0202"}
print(phone_book["Alice"])

The script showed how to retrieve Alice’s number instantly. I then used this logic to build a Quiz Game where questions were Keys and correct answers were Values.

Module 15 : Functions and Returns; How can I reuse my pricing logic across different products?

Functions are the ultimate tool for DRY programming which stands for Don’t Repeat Yourself. If you have a complex calculation that appears in ten different places, you should put it in a function. This way, if you need to change the logic later, you only change it once.

Functions also allow for modularity. In large IT projects, different engineers work on different functions. By defining clear inputs and outputs, developers can build separate pieces of an application that fit together perfectly.

One practical example

I created a price calculator. Instead of writing math for every single item in a store, I wrote one function and called it whenever I needed to find the final price for sneakers or phones.

Syntax

def function_name(parameter):
    # process logic
    return result

The def keyword stands for define. You provide parameters as inputs, and the return keyword sends the final answer back to the main program.

Real Code Example

def get_final_price(original, discount):
    amount = original * (discount / 100)
    return original - amount

sneakers = get_final_price(120, 20)
print(f"Final sneakers price: {sneakers}")

In the script, the function calculated the discount and returned the total. This value was then stored in a variable for later use.

Module 16 : External Libraries; How do I use pip to send web requests from my code?

The true strength of Python lies in its community. You dont have to reinvent the wheel for every project because you can use Libraries created by other experts. This allows you to perform complex tasks, like talking to web servers, in just a few lines of code.

Learning to use pip opens the door to thousands of professional tools. It allows you to transform a basic script into a powerful engine capable of interacting with the entire internet. This is how real-world IT solutions are built.

One practical example

I used the terminal to install the requests library. I then wrote a script that went out to the internet, talked to a public API, and brought back the current IP address.

Syntax

pip install requests
import requests
response = requests.get(url)

Libraries are installed via the terminal. Inside your script, you use the import keyword. To talk to a website, you use the get function from the requests library.

Real Code Example

import requests
response = requests.get("https://api.ipify.org")
print(f"Your IP Address is: {response.text}")

In the script, I imported requests and sent a request to ipify. The API returned our IP address, which I then printed.

Module 17 : Career Guidance; What are the most common questions in a Python technical interview?

Learning the syntax of a language is only half the battle. Knowing how to use that language to get a job is what truly matters. I focus on the practicalities of the hiring process, such as building a portfolio and handling technical interviews.

By understanding the common pitfalls and high-frequency questions that hiring managers ask, you can walk into an interview with confidence. I suggest reviewing how Python skills apply specifically to high-demand roles like Cybersecurity and DevOps.

One practical example

I reviewed how to explain the difference between a List and a Dictionary to an interviewer. This is a common question used to test your understanding of data structures and memory efficiency.

Step-by-Step Guide to IT Job Readiness

Step 1: Download the sample codes and projects.
I have linked all the RootSaid IT Python resources here. This ensures you aren’t just watching but actually coding along.

Step 2: Modify the logic in the sample projects.
Changing existing code is the best way to learn how things break. I suggest trying to add a new command to the match-case module.

Step 3: Join the RootSaid IT community.
We have active groups on WhatsApp and Telegram for troubleshooting. Networking with other makers is a huge advantage for your career.

Step 4: Build a small portfolio on GitHub.
Employers want to see what you have built. Even simple scripts like the Air Quality monitor show that you understand core logic.

Step 5: Practice technical communication.
Explain your code out loud. Being able to describe your troubleshooting process is vital during an interview.


Try These Exams to test your knowledge

Exam 1: How do I build a functional Network Health Monitor?

I have designed this task to push you beyond just copying code. In this project, you need to act like a DevOps engineer. Your script must store a list of servers and their current status using a dictionary. You will then create an interactive loop where you can scan ports, check health scores, and perform system restarts using the match-case logic.

Handling user input is where most scripts fail immediatley. You must ensure that if a user enters a string when the program expects a port number, your code does not crash. This requires the neccessary use of try-except blocks. By the end of this exam, you will have a portfolio-ready script that proves you understand the logical flow of a professional IT tool.

Hits – How do I define the project requirements?

Step 1: Create the data structure.
Start by defining a dictionary called server_status where keys are server names and values are Booleans representing if the server is online.

Step 2: Write the health calculation function.
Define a function that takes a list of numbers representing response times and returns an average health score.

Step 3: Build the interactive command loop.
Use a while loop to keep the program running until the user types the Exit command.

Step 4: Implement administrative logic.
Inside the loop, use match-case to handle commands like Status, Scan, and Restart.

Step 5: Add the safety net.
Wrap your port scanning logic in a try-except block to handle invalid numerical inputs without stopping the program.

One practical example

I want the output of your Status command to show a clean message for every server in your dictionary. It should look something like: Server Alpha is currently Online. This requires you to loop through the dictionary and use an if-else statement to convert the Boolean value into a readable string.

Hint

# Use this as a reference for your server dictionary
server_data = {
    "Web-Server": True,
    "Database": False,
    "Mail-Server": True
}

Remember that dictionaries use curly braces and keys must be unique. When you iterate through them, make sure you access both the key and the value to build your f-string output.

Final Code

# RootSaid IT - Python Master Class Exam 1
# Network Health Monitor Tool

# Module 13: Data Collection - Server inventory
server_status = {
    "Web-Portal": True,
    "Database-Primary": False,
    "Storage-Cloud": True,
    "Auth-Service": True
}

# Module 15: Functions - Calculate average health score
def calculate_health(response_times):
    if not response_times:
        return 0
    total = sum(response_times)
    # Returning the average
    return total / len(response_times)

# Module 08: While Loop - Main Program Loop
while True:
    print("\n--- RootSaid IT Network Monitor ---")
    print("1. Status - Check all servers")
    print("2. Scan - Test specific port")
    print("3. Health - Check average latency")
    print("4. Exit")
    
    # Module 01/02: Input and Variables
    command = input("\nEnter Command (Status/Scan/Health/Exit): ").title()

    # Module 06: Switch Case - Command Logic
    match command:
        case "Status":
            print("\nUpdating Server Status...")
            # Module 12: Nested Loop Logic
            for server, online in server_status.items():
                # Module 05: If-Else Logic
                status_text = "ONLINE" if online else "OFFLINE"
                print(f"[*] {server}: {status_text}")
        
        case "Scan":
            # Module 07: Error Handling - Preventing crash on non-integer input
            try:
                port = int(input("Enter Port Number: "))
                if port < 1 or port > 65535:
                    print("Error: Port must be between 1 and 65535.")
                else:
                    print(f"Scanning Port {port}... [RESULT: SECURE]")
            except ValueError:
                print("Invalid input! Please enter a numerical port number.")

        case "Health":
            # Module 03/13: Handling Lists and Floats
            times = [12, 15, 10, 22, 18]
            avg = calculate_health(times)
            print(f"Current Network Latency Average: {avg}ms")

        case "Exit":
            print("Shutting down monitor. Stay secure!")
            # Module 10: Break Statement
            break

        case _:
            print("Unknown command. Please try again.")

In this snippet, I have shown how to combine match-case with try-except. You must expand this logic to include the Status check and the Health calculation function mentioned in the steps above.


Exam 2: How do I build an Automated Security Log Analyzer?

In this second exam, I want you to step into the role of a Junior Security Analyst. Your objective is to take a list of raw log strings and extract the IP addresses that have more than three failed login attempts. This is a real-world task where you will be analysing text data to find patterns and store them in a way that is easy for a security team to read.

You will need to use your knowledge of string methods to clean the logs and dictionaries to count the occurrences of each IP. The logic requires a nested approach where you loop through the logs and update the threat configeration based on what you find. I have found that beginners often struggle with the logic of incrementing values in a dictionary, so pay close attention to that neccessary step.

Why is string parsing critical for security automation?

Step 1: Define the raw log data.
Create a list called raw_logs containing at least ten strings. Each string should follow a format like: Failed login from 192.168.1.10.

Step 2: Create a threat detection function.
Write a function that accepts an IP address and a count, then returns a string category: Low, Medium, or High threat.

Step 3: Process the logs with a loop.
Use a for loop to go through every log entry. Use the split string method to isolate the IP address from the rest of the text.

Step 4: Store counts in a dictionary.
Create a dictionary called login_attempts. If an IP is already in the dictionary, increment its value by 1; otherwise, add it with a starting value of 1.

Step 5: Interactive reporting.
Use a while loop and match-case to let the user choose between viewing the full report, checking a specific IP, or exiting the tool.

How do I structure the threat detection logic?

I want your report to use f-strings to display the final threat level for each suspicious IP. For example, your code should output: IP 192.168.1.50 has 5 failed attempts and is a High threat. This ensures you are combining your knowledge of collections, functions, and formatting in a single, cohesive script.

Hint – Syntax

# Use this as a reference for incrementing dictionary values
log_counts = {}
ip = "10.0.0.1"

if ip in log_counts:
    log_counts[ip] += 1
else:
    log_counts[ip] = 1

This is a standard RootSaid IT method for building counters. It prevents the script from crashing when it encounters a new key that has not been defined yet.

Real Code Answer

# RootSaid IT - Python Master Class Exam 2
# Automated Security Log Analyzer

# Module 13: List of raw logs
raw_logs = [
    "Failed login from 192.168.1.50",
    "Successful login from 10.0.0.5",
    "Failed login from 192.168.1.50",
    "Failed login from 172.16.0.20",
    "Failed login from 192.168.1.50",
    "Failed login from 172.16.0.20",
    "Failed login from 192.168.1.50",
    "Failed login from 192.168.1.100",
    "Failed login from 10.0.0.5",
    "Failed login from 192.168.1.50"
]

# Module 15: Threat Category Function
def get_threat_level(count):
    # Module 05: Decision Logic
    if count >= 5:
        return "HIGH THREAT"
    elif count >= 3:
        return "MEDIUM THREAT"
    else:
        return "LOW THREAT"

# Module 14: Dictionary to store IP counts
login_attempts = {}

# Module 12: Processing the data
print("[!] Starting RootSaid IT Log Analysis...")

for log in raw_logs:
    # Only process failed attempts
    if "Failed" in log:
        # Module 03: String Parsing
        # Splitting the string and taking the last part (the IP)
        ip = log.split()[-1]
        
        # Module 14: Dictionary incrementing logic
        if ip in login_attempts:
            login_attempts[ip] += 1
        else:
            login_attempts[ip] = 1

# Module 09: Interactive Reporting
while True:
    print("\n--- Security Analyzer Menu ---")
    print("1. Report - Full Threat Assessment")
    print("2. Search - Check specific IP")
    print("3. Exit")
    
    choice = input("\nSelect Option: ")
    
    match choice:
        case "1":
            print("\n--- SUSPICIOUS ACTIVITY REPORT ---")
            for ip, count in login_attempts.items():
                level = get_threat_level(count)
                # Module 02: f-string output
                print(f"IP: {ip} | Attempts: {count} | Status: {level}")
        
        case "2":
            target = input("Enter IP Address to search: ")
            # Module 14: Dictionary lookup
            if target in login_attempts:
                count = login_attempts[target]
                print(f"Result: {target} found with {count} failed attempts.")
            else:
                print("Result: No suspicious activity found for this IP.")
                
        case "3":
            print("Exiting Security Analyzer.")
            break
            
        case _:
            print("Invalid selection. Use 1, 2, or 3.")

In this example, I used the split method to turn a sentence into a list of words. You must now apply this to your full list of logs and use your function to calculate the threat levels based on the counts stored in your dictionary.


Follow RootSaid IT for Free Career Guidance

Similar Posts

2 Comments

  1. I’m often to blogging and i really appreciate your python chapters. The article has actually peaks my interest. I’m going to bookmark your web site and maintain checking for brand spanking new information.

  2. I am truly thankful to the owner of this web site who has shared this fantastic piece of writing at at this place. I am learning python now and this tutorials are really useful for me. Please try to make less gramatical errors.

Leave a Reply

Your email address will not be published. Required fields are marked *