Blog 5: Control Flow in Python – If Statements, Loops, and Logical Operators

Control flow is one of the most important concepts in Python programming, especially for hackers. It allows you to determine how your code executes based on conditions, iterate through data, and make logical decisions. In this blog, we will cover the basics of if statements, loops, and logical operators in Python.

1. If Statements

If statements enable you to execute a block of code only if a specific condition is true. This is particularly useful for scenarios where decision-making is required.

Basic Syntax:

if condition:
    # Code to execute if the condition is True

Example:

password = "admin123"
input_password = input("Enter your password: ")

if input_password == password:
    print("Access Granted")
else:
    print("Access Denied")

Explanation:

  • if: Checks if the condition is true.

  • else: Executes if the condition is false.

Adding elif for Multiple Conditions:

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

if age < 18:
    print("You are a minor.")
elif age >= 18 and age < 60:
    print("You are an adult.")
else:
    print("You are a senior citizen.")


2. Loops in Python

Loops are used to execute a block of code repeatedly. Python provides two types of loops: for loops and while loops.

2.1 For Loops

The for loop iterates over a sequence (like a list, string, or range) and executes a block of code for each item.

Syntax:

for variable in sequence:
    # Code to execute for each iteration

Example:

# Iterating through a list
hacking_tools = ["Nmap", "Metasploit", "Burp Suite"]

for tool in hacking_tools:
    print(f"Tool: {tool}")

Using range():

# Printing numbers from 1 to 5
for i in range(1, 6):
    print(i)


2.2 While Loops

The while loop executes a block of code as long as the condition is true.

Syntax:

while condition:
    # Code to execute while the condition is True

Example:

counter = 1

while counter <= 5:
    print(f"Counter: {counter}")
    counter += 1

Infinite Loops:

Be cautious with while loops, as forgetting to update the condition can result in an infinite loop. For example:

while True:
    print("This will run forever unless you break it.")

Use break to exit such loops.


3. Logical Operators

Logical operators are used to combine conditional statements or evaluate multiple conditions in Python. They are critical for writing complex decision-making code.

Types of Logical Operators:

Operator Description Example
and Returns True if both conditions are True x > 5 and x < 10
or Returns True if at least one condition is True x < 5 or x > 10
not Reverses the result of a condition not(x > 5)

Examples:

Using and:

username = "admin"
password = "1234"

if username == "admin" and password == "1234":
    print("Login Successful")
else:
    print("Invalid credentials")

Using or:

role = "user"

if role == "admin" or role == "moderator":
    print("You have elevated privileges.")
else:
    print("Access restricted.")

Using not:

is_authenticated = False

if not is_authenticated:
    print("You need to log in.")
else:
    print("Welcome back!")

4. Combining Control Flow Components

You can combine if statements, loops, and logical operators to create powerful scripts. Here’s a practical example:

Example: Password Brute Force Simulation

stored_password = "securepass"
attempts = 3

while attempts > 0:
    entered_password = input("Enter your password: ")
    
    if entered_password == stored_password:
        print("Access Granted")
        break
    else:
        attempts -= 1
        print(f"Incorrect password. {attempts} attempts left.")

if attempts == 0:
    print("Account locked. Too many failed attempts.")


5. Key Takeaways

  • If Statements: Allow decision-making based on conditions.

  • Loops: Enable repetitive execution of code.

    • Use for for iterating over sequences.

    • Use while for conditions that may change dynamically.

  • Logical Operators: Combine conditions to create complex logic.

By mastering these control flow tools, you’ll be able to write Python scripts that are not only efficient but also dynamic and flexible. These skills are essential for automating tasks, writing hacking tools, and solving problems effectively.


Comments