CODY ← Back to Courses
🐍

Python — Programming for Everyone

Clean, readable, powerful. Python is the go-to language for data science, AI, automation, and web backends. Perfect for beginners and professionals alike.

Beginner Friendly Data Science AI / ML

What is Python?

Python is a high-level, interpreted programming language created by Guido van Rossum in 1991. It emphasizes code readability and simplicity, making it ideal for beginners while remaining powerful enough for experts.

🐍 Readable Code

Python uses indentation instead of braces. Code looks almost like plain English, reducing the learning curve.

🔋 Batteries Included

The standard library covers file I/O, networking, math, dates and much more — right out of the box.

🌍 Everywhere

Web (Django, Flask), data (pandas, numpy), AI (TensorFlow, PyTorch), automation, scripting — Python does it all.

Basic Syntax

Python syntax is clean and minimal. No semicolons, no curly braces — just clean indentation to define code blocks.

basics.py
# This is a comment
name = "Alice"        # string variable
age  = 25             # integer variable
pi   = 3.14           # float variable
active = True         # boolean variable

# Print to console
print(f"Hello, {name}! You are {age} years old.")

# Input from user
user = input("Enter your name: ")
print("Welcome,", user)
💡 Note: Indentation (4 spaces or 1 tab) is not optional in Python — it defines code blocks. Inconsistent indentation causes errors.

Data Types

Python has several built-in data types. Understanding them is fundamental to writing correct programs.

TypeExampleDescription
str"hello"Text / string of characters
int42Whole number
float3.14Decimal number
boolTrue / FalseBoolean (logical) value
list[1, 2, 3]Ordered mutable sequence
tuple(1, 2, 3)Ordered immutable sequence
dict{"key": "val"}Key-value pairs (map)
set{1, 2, 3}Unordered unique values
type_check.py
x = 42
print(type(x))          # <class 'int'>

# Type conversion
s = str(x)              # "42"
f = float(x)            # 42.0
b = bool(x)             # True (non-zero = True)

Control Flow

Control flow lets your program make decisions and repeat actions. Python provides if/elif/else and two loop types.

conditions.py
score = 75

if score >= 90:
    print("Grade: A")
elif score >= 70:
    print("Grade: B")
elif score >= 50:
    print("Grade: C")
else:
    print("Grade: F")
loops.py
# for loop — iterate over a range
for i in range(5):
    print(i)              # 0, 1, 2, 3, 4

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

# while loop
count = 0
while count < 3:
    print("tick", count)
    count += 1

Functions

Functions group reusable code. Use the def keyword to define them. Python also supports lambda functions and default arguments.

functions.py
# Basic function
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Bob"))             # Hello, Bob!
print(greet("Eve", "Hi"))       # Hi, Eve!

# Lambda (anonymous) function
square = lambda x: x ** 2
print(square(5))                 # 25

# *args and **kwargs
def add_all(*nums):
    return sum(nums)

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

Lists & Dictionaries

Lists store ordered sequences, dictionaries store key-value pairs. These two data structures are used in almost every Python program.

lists.py
colors = ["red", "green", "blue"]

colors.append("yellow")     # add to end
colors.remove("red")        # remove by value
print(colors[0])            # "green" (0-indexed)
print(colors[-1])           # "yellow" (last item)
print(colors[1:3])          # slice ["blue","yellow"]

# List comprehension
squares = [x**2 for x in range(1, 6)]
# [1, 4, 9, 16, 25]
dicts.py
person = {
    "name": "Alice",
    "age": 30,
    "city": "London"
}

print(person["name"])        # Alice
person["email"] = "a@x.com"  # add new key
del person["city"]           # remove key

for key, val in person.items():
    print(key, "→", val)

OOP — Classes & Objects

Object-Oriented Programming organizes code into classes that bundle data and behaviour. Python supports full OOP with inheritance and special methods.

classes.py
class Animal:
    def __init__(self, name, sound):
        self.name  = name
        self.sound = sound

    def speak(self):
        return f"{self.name} says {self.sound}!"

class Dog(Animal):               # inheritance
    def fetch(self):
        return f"{self.name} fetches the ball!"

dog = Dog("Rex", "Woof")
print(dog.speak())              # Rex says Woof!
print(dog.fetch())              # Rex fetches the ball!

🛠 Mini Project: Number Guessing Game

Put it all together — variables, loops, conditions, functions. Build a small but complete interactive game.

guessing_game.py
import random

def play_game():
    secret   = random.randint(1, 100)
    attempts = 0
    print("Guess a number between 1 and 100!")

    while True:
        guess = int(input("Your guess: "))
        attempts += 1

        if   guess < secret: print("Too low!")
        elif guess > secret: print("Too high!")
        else:
            print(f"🎉 Correct in {attempts} attempts!")
            break

play_game()
🎯 Challenge: Add a difficulty setting (easy=20 attempts, hard=5 attempts). If the player runs out of attempts, reveal the secret number and ask to play again.