Home /Python /Crash Course

Python Course

Python Crash Course

The Essential Reference Guide for Beginners

1. Variables & Data Types

Python is dynamically typed — you don't declare types. The interpreter infers them at runtime. The four most common primitive types are str, int, float, and bool.

# Assignment — no type declaration needed
name       = "Ayman"     # str
age        = 35          # int
gpa        = 3.9         # float
is_active  = True        # bool

# Check the type of any value
print(type(name))       # <class 'str'>

# Multiple assignment
x, y, z = 1, 2, 3

Info

Python variable names are case-sensitive. Name and name are different variables.

2. Operators

Python supports arithmetic, comparison, logical, and assignment operators.

# Arithmetic
print(10 + 3)   # 13  — addition
print(10 - 3)   # 7   — subtraction
print(10 * 3)   # 30  — multiplication
print(10 / 3)   # 3.333 — float division
print(10 // 3)  # 3   — floor division
print(10 % 3)   # 1   — modulus (remainder)
print(2 ** 8)   # 256 — exponentiation

# Comparison (returns bool)
print(5 == 5)    # True
print(5 != 4)    # True
print(3 >= 3)    # True

# Logical
print(True and False)  # False
print(True or  False)  # True
print(not True)        # False

3. Strings

Strings are immutable sequences of characters. Python provides powerful built-in string methods.

name = "ayman alzaid"

# Common methods
print(name.upper())         # "AYMAN ALZAID"
print(name.title())         # "Ayman Alzaid"
print(name.replace("a", "@")) # "@ym@n @lz@id"
print(name.split(" "))      # ['ayman', 'alzaid']
print(name.strip())         # removes leading/trailing spaces

# f-strings (recommended for formatting)
course = "Python"
score  = 98.5
print(f"{name.title()} scored {score}% in {course}")

# Slicing:  s[start : stop : step]
s = "Hello, World!"
print(s[0:5])   # "Hello"
print(s[-6:])   # "World!"
print(s[::-1])  # reversed string

4. Control Flow

Use if / elif / else to branch execution. Python uses indentation (4 spaces) to define blocks.

score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")   # ← this runs
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")

# Ternary (one-liner)
label = "Pass" if score >= 60 else "Fail"

Watch Out

Python does not use curly braces. Inconsistent indentation causes an IndentationError.

5. Loops

Python has two loop constructs: for for iterating sequences, and while for condition-based repetition.

# for loop — iterate a range
for i in range(5):
    print(i)                    # 0 1 2 3 4

# for loop — iterate a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit.upper())

# enumerate gives index + value
for idx, fruit in enumerate(fruits):
    print(f"{idx}: {fruit}")

# while loop
count = 0
while count < 3:
    print(f"count = {count}")
    count += 1

# break & continue
for n in range(10):
    if n == 3: continue   # skip 3
    if n == 6: break      # stop at 6
    print(n)

6. Lists

Lists are ordered, mutable sequences. They can hold mixed types and are zero-indexed.

nums = [10, 20, 30, 40]

# Indexing & slicing
print(nums[0])       # 10  (first)
print(nums[-1])      # 40  (last)
print(nums[1:3])     # [20, 30]

# Mutation
nums.append(50)      # add to end
nums.insert(0, 5)   # insert at index 0
nums.remove(20)      # remove first occurrence of 20
nums.pop()            # removes & returns last element
nums.sort()           # sort in place

# List comprehension — concise and fast
squares = [x**2 for x in range(6)]
evens   = [x    for x in range(20) if x % 2 == 0]

Tip

List comprehensions are idiomatic Python — prefer them over manual for loops when building new lists.

7. Dictionaries

Dictionaries store key → value pairs. Keys must be unique and immutable (strings, numbers, tuples).

student = {
    "name":  "Ayman",
    "grade": 90,
    "major": "CS"
}

# Access
print(student["name"])           # "Ayman"
print(student.get("gpa", 0))     # 0 (safe default)

# Mutate
student["grade"] = 95
student["year"]  = 2             # adds new key
del student["major"]

# Iterate
for key, val in student.items():
    print(f"{key}{val}")

# Useful methods
print(student.keys())   # dict_keys([...])
print(student.values()) # dict_values([...])
print("name" in student) # True

8. Functions

Functions group reusable logic. Use def to define, and add type hints for readability.

# Basic function
def greet(name: str) -> str:
    return f"Hello, {name}!"

print(greet("Ayman"))   # Hello, Ayman!

# Default parameters
def power(base: int, exp: int = 2) -> int:
    return base ** exp

print(power(3))      # 9  (exp defaults to 2)
print(power(3, 4))   # 81

# *args — variable positional arguments
def total(*nums):
    return sum(nums)

print(total(1, 2, 3, 4))   # 10

# Lambda — anonymous one-line function
square = lambda x: x ** 2
print(square(7))   # 49

Tip

Add docstrings immediately after def: """Returns greeting string.""" — they show up in help().

9. OOP & Classes

Classes bundle data and behavior. Python uses __init__ as the constructor and self to refer to the instance.

class Student:
    """Represents a course student."""

    def __init__(self, name: str, grade: int):
        self.name  = name
        self.grade = grade

    def letter_grade(self) -> str:
        if   self.grade >= 90: return "A"
        elif self.grade >= 80: return "B"
        elif self.grade >= 70: return "C"
        else:                    return "F"

    def __str__(self) -> str:
        return f"{self.name} ({self.letter_grade()})"

# Instantiate
s = Student("Ayman", 92)
print(s)               # Ayman (A)
print(s.grade)         # 92

# Inheritance
class GradStudent(Student):
    def __init__(self, name, grade, thesis):
        super().__init__(name, grade)
        self.thesis = thesis

10. File I/O

Python's built-in open() function handles reading and writing files. Always use a with block — it automatically closes the file even on errors.

# Write to a file
with open("notes.txt", "w") as f:
    f.write("Python is powerful.\n")
    f.write("File I/O is easy.\n")

# Read entire file
with open("notes.txt", "r") as f:
    content = f.read()
    print(content)

# Read line by line
with open("notes.txt", "r") as f:
    for line in f:
        print(line.strip())

# Append (doesn't overwrite)
with open("notes.txt", "a") as f:
    f.write("Appended line.\n")

Warning

Mode "w" overwrites the file completely. Use "a" to append without destroying existing content.