Python Fundamentals – Level 1: Introduction to Python Programming

🐍 Python Fundamentals — Level 1: Getting Started with Python

Python is one of the most widely used programming languages in cybersecurity. It is used for automation, penetration testing, network analysis, scripting, data processing, and security research.

Before building security tools or automating cybersecurity tasks, it's important to understand the fundamentals of programming.

In this tutorial, we'll cover the essential building blocks of Python, from working with strings and user input to conditional statements and loops.

1. Strings

A string is a sequence of characters used to represent text.

Strings can contain:

  • Letters (A–Z, a–z)

  • Numbers (0–9)

  • Spaces

  • Special characters (!, @, #, $, etc.)

In Python, strings must be enclosed in either single quotation marks (' ') or double quotation marks (" ").

Example:

message = "Hello there"
name = 'Ana'

print(message)
print(name)

Output:

Hello there
Ana

Both quotation styles work. Just make sure the opening and closing quotation marks match.

1.1 Concatenating Strings

String concatenation means joining two or more strings together.

Python uses the + operator to concatenate strings.

hi = "hello there"
name = "Ana"

greet = hi + name

print(greet)

Output:

hello thereAna

Notice that Python doesn't automatically add spaces between strings.

To include a space, concatenate an additional string:

greeting = hi + " " + name

print(greeting)

Output:

hello there Ana

1.2 Repeating Strings

Python also allows you to repeat strings using the multiplication (*) operator.

hi = "hello there"
name = "Ana"

operation = hi + " " + name * 3

print(operation)

Output:

hello there AnaAnaAna

The multiplication operator repeats the string three times before concatenating it with the other strings.

You can also repeat an entire string:

message = "Python! "

print(message * 3)

Output:

Python! Python! Python!

2. Input and Output

Input and output allow programs to communicate with users.

  • Input: Receives information from the user.

  • Output: Displays information to the user.

2.1 The input() Function

Python uses the input() function to receive information from the user.

text = input("Type anything... ")

print(text)

Example execution:

Type anything... Hello Python!
Hello Python!

The value entered by the user is stored in the variable text.

The print() function then displays that value.

2.2 Working with Numbers as Input

An important detail about Python's input() function is that it always returns a string, even when the user enters a number.

For example:

num = input("Type a number... ")

print(num)

If the user enters 5, Python stores it as the string "5", not the integer 5.

To perform mathematical operations, we need to convert the input into a numeric data type.

num = int(input("Type a number... "))

print(5 * num)

Example execution:

Type a number... 5
25

Here, int() converts the user's input into an integer before multiplication.

3. Comparison Operators

Comparison operators are used to compare two values.

They evaluate the comparison and return a Boolean result:

  • True

  • False

Let's assume we have two variables:

i = 10
j = 5

The following comparison operators are available:

OperatorMeaningExampleResult
>Greater thani > jTrue
>=Greater than or equal toi >= jTrue
<Less thani < jFalse
<=Less than or equal toi <= jFalse
==Equal toi == jFalse
!=Not equal toi != jTrue

Example:

i = 10
j = 5

print(i > j)
print(i == j)
print(i != j)

Output:

True
False
True

You can compare integers, floating-point numbers, and strings. However, comparisons must use compatible types. Python does not allow direct ordering comparisons between a string and an integer.

Important: = and == are not the same.

  • = assigns a value to a variable.

  • == checks whether two values are equal.

4. Logical Operators

Logical operators allow us to combine or reverse Boolean conditions.

Python has three main logical operators:

  • and

  • or

  • not

Let's assume we have two Boolean variables:

a = True
b = False

4.1 The NOT Operator

The not operator reverses a Boolean value.

a = True

print(not a)

Output:

False

If the original value is False, applying not returns True.

4.2 The AND Operator

The and operator returns True only when both conditions are true.

a = True
b = False

print(a and b)

Output:

False

Both conditions must be True for the result to be True.

4.3 The OR Operator

The or operator returns True when at least one condition is true.

a = True
b = False

print(a or b)

Output:

True

4.4 Logical Operators Truth Table

ABA and BA or B
TrueTrueTrueTrue
TrueFalseFalseTrue
FalseTrueFalseTrue
FalseFalseFalseFalse

The not operator reverses the value:

Anot A
TrueFalse
FalseTrue

5. Type Casting

Type casting is the process of converting a value from one data type into another.

Python provides several built-in conversion functions:

FunctionConverts intoExample
int()Integerint("10") → 10
float()Floating-point numberfloat("3.14") → 3.14
str()Stringstr(100) → "100"
bool()Booleanbool(1) → True

Example:

number = "25"

print(type(number))

number = int(number)

print(type(number))

Output:

<class 'str'>
<class 'int'>

The type() function identifies the data type of a variable.

Practical Example

age = input("Enter your age: ")

age = int(age)

next_year = age + 1

print("Next year, you will be:")
print(next_year)

Without converting the input using int(), Python would treat the entered value as text.

Note: Not every string can be converted into a number. For example, int("hello") raises a ValueError.

6. Formatting Strings and Floats

String formatting allows us to insert variables and values into text.

Python supports several formatting methods. One of the most convenient is the f-string.

6.1 F-Strings

An f-string starts with the letter f before the opening quotation mark.

name = "Ana"
age = 25

print(f"My name is {name} and I am {age} years old.")

Output:

My name is Ana and I am 25 years old.

Variables and expressions can be placed inside curly brackets {}.

6.2 Formatting Floating-Point Numbers

A floating-point number is a number that contains a decimal component.

For example:

price = 19.98765

print(f"Price: {price:.2f}")

Output:

Price: 19.99

The .2f format specifies that the number should be displayed with two decimal places.

Additional examples:

number = 12.34567

print(f"{number:.1f}")
print(f"{number:.2f}")
print(f"{number:.3f}")

Output:

12.3
12.35
12.346

This is particularly useful when displaying prices, percentages, measurements, and calculated results.

7. If Conditions

Conditional statements allow programs to make decisions based on specific conditions.

Python uses:

  • if

  • elif

  • else

7.1 The IF Statement

The if statement executes a block of code only when its condition evaluates to True.

age = 20

if age >= 18:
    print("You are an adult.")

Output:

You are an adult.

If the condition is false, the code inside the if block will not execute.

7.2 The ELSE Statement

The else statement executes when the if condition is false.

age = 16

if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

Output:

You are a minor.

7.3 The ELIF Statement

The elif statement allows us to check additional conditions.

grade = 75

if grade >= 90:
    print("Excellent")
elif grade >= 70:
    print("Good")
elif grade >= 50:
    print("Passed")
else:
    print("Failed")

Output:

Good

Python checks the conditions from top to bottom and executes the first matching block.

Important: Python uses indentation to define code blocks. The standard convention is four spaces.

8. For Loops

A for loop allows us to repeat a block of code for each item in a sequence or iterable.

This is useful when we want to perform the same operation multiple times without writing the same code repeatedly.

8.1 Basic For Loop

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

Output:

0
1
2
3
4

The range(5) function generates numbers starting from 0 and ending before 5.

8.2 Understanding range()

The range() function can accept up to three arguments:

range(start, stop, step)

  • start: The starting number.

  • stop: The number where iteration stops (exclusive).

  • step: The amount by which the number increases or decreases.

Example:

for i in range(1, 6):
    print(i)

Output:

1
2
3
4
5

Another example using a step:

for i in range(0, 11, 2):
    print(i)

Output:

0
2
4
6
8
10

8.3 Looping Through Strings

A for loop can also iterate through individual characters in a string.

word = "Python"

for letter in word:
    print(letter)

Output:

P
y
t
h
o
n

8.4 Looping Through a List

Loops can also process collections of values.

tools = ["Nmap", "Wireshark", "Burp Suite"]

for tool in tools:
    print(tool)

Output:

Nmap
Wireshark
Burp Suite

This concept will become particularly useful when automating cybersecurity tasks involving multiple files, IP addresses, or security tools.

9. While Loops

A while loop repeatedly executes a block of code as long as a specified condition remains True.

Unlike a for loop, which commonly iterates over a sequence, a while loop continues based on a condition.

9.1 Basic While Loop

i = 0

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

Output:

0
1
2
3
4

Let's break it down:

  1. i = 0 initializes the variable.

  2. while i < 5 checks whether the condition is true.

  3. print(i) displays the current value.

  4. i += 1 increases the variable by one.

  5. The loop repeats until the condition becomes false.

9.2 Infinite Loops

An infinite loop occurs when the condition never becomes false.

For example:

while True:
    print("This will run forever!")

This loop continues indefinitely until it is interrupted.

To avoid this, ensure that the loop has a condition that can eventually become false or use a break statement when appropriate.

9.3 Using BREAK

The break statement immediately terminates a loop.

i = 0

while i < 10:
    print(i)

    if i == 5:
        break

    i += 1

Output:

0
1
2
3
4
5

Once i reaches 5, the loop stops.

9.4 Using CONTINUE

The continue statement skips the current iteration and moves to the next one.

for i in range(5):
    if i == 2:
        continue

    print(i)

Output:

0
1
3
4

The number 2 is skipped, but the loop continues running.


10. Practical Exercises

Time to put what you've learned into practice!

Try solving these exercises without looking at the examples above.

Exercise 1 — String Manipulation

Create two variables, first_name and last_name. Combine them into a single variable and display the complete name.

Exercise 2 — User Input

Ask the user to enter their age. Convert the input into an integer and display their age five years from now.

Exercise 3 — Comparisons

Create two integer variables and print the results of all six comparison operators.

Exercise 4 — Logical Operators

Create two Boolean variables and test the and, or, and not operators.

Exercise 5 — Type Casting

Ask the user to enter a number as text. Convert it into a floating-point number and multiply it by two.

Exercise 6 — String Formatting

Create variables for a product name and price. Display them using an f-string, formatting the price to two decimal places.

Exercise 7 — IF Conditions

Create a program that asks the user for a number and determines whether it is positive, negative, or zero.

Exercise 8 — FOR Loop

Write a program that prints all even numbers between 1 and 20.

Exercise 9 — WHILE Loop

Create a counter that starts at 10 and counts down to 1.

Exercise 10 — Mini Project: Login Simulator

Create a simple login simulator that:

  1. Stores a predefined username and password.

  2. Asks the user to enter their credentials.

  3. Compares the entered values with the stored credentials.

  4. Displays a success or failure message.

Note: This is a beginner programming exercise, not a secure authentication implementation.


Conclusion

Congratulations! You've completed Level 1 of the OZZ961 Python Fundamentals series.

You have learned how to:

  • Work with strings and concatenate text.

  • Receive user input and display output.

  • Compare values using comparison operators.

  • Combine conditions using logical operators.

  • Convert between different data types.

  • Format strings and floating-point numbers.

  • Make decisions using conditional statements.

  • Automate repetitive tasks using for and while loops.

These fundamentals are the foundation for everything that follows.

What's Next? — Level 2

In Level 2, we'll explore Python functions and how to organize and reuse code. We'll cover built-in functions, the Python standard library, third-party packages, and how to define our own functions.

We'll also introduce modules, libraries, objects, data types, methods, and attributes to help us understand how Python works behind the scenes.

These concepts will help us write cleaner, more reusable programs and prepare us for developing practical cybersecurity scripts.

Keep learning. Keep building. Keep breaking things (responsibly).

Comments

Popular posts from this blog

Information disclosure in version control history

Linux AAA

Hashcat LAB