🐍 Python

Python Basics

A powerful, beginner-friendly programming language. Learn data types, control flow, functions, OOP, and file handling.

14Topics
FREECourse
ALLDevices

01 What is Python?

Python is a high-level, interpreted programming language known for its simplicity and readability. Used in web development, data science, AI, and automation.

# My first Python program
print("Hello, World!")

# Variables
name = "CodeVerse"
age = 25
print(name, age)
💡 Python uses dynamic typing — no need to declare variable types. Indentation matters!

02 Data Types

Python has several built-in data types: strings, integers, floats, booleans, and None.

text = "Hello"      # str
number = 42           # int
decimal = 3.14        # float
is_true = True        # bool
nothing = None        # NoneType

print(type(text))     # <class 'str'>

03 Strings & f-Strings

Work with text using string methods, slicing, and formatted strings (f-strings).

name = "CodeVerse"

# String methods
print(name.upper())       # CODEVERSE
print(len(name))          # 9

# f-Strings
print(f"{name} is awesome!")

# Slicing
print(name[0:4])          # Code

04 Lists & Tuples

Lists are mutable sequences. Tuples are immutable. Both can store multiple items.

# List (mutable)
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
fruits.remove("banana")
print(fruits[0])        # apple

# Tuple (immutable)
colors = ("red", "green", "blue")
print(colors[1])         # green

05 Dictionaries

Key-value pairs for structured data — fast lookups and flexible storage.

# Dictionary
user = {
    "name": "Alex",
    "age": 25,
    "skills": ["Python", "HTML"]
}

print(user["name"])      # Alex
user["email"] = "a@test.com"

06 Conditionals (if/elif/else)

Control program flow with conditional statements and comparison operators.

score = 85

if score >= 90:
    print("Excellent")
elif score >= 70:
    print("Good")
else:
    print("Fail")

# Ternary
result = "Pass" if score >= 50 else "Fail"

07 Loops (for & while)

Iterate over sequences with for loops and repeat actions with while loops.

# For loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Range
for i in range(5):
    print(i)      # 0 1 2 3 4

# While loop
count = 0
while count < 3:
    print(count)
    count += 1

08 Functions

Define reusable blocks of code with functions, parameters, and return values.

# Define function
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

# Call function
print(greet("Alex"))           # Hello, Alex!

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

09 Object-Oriented Programming

Create classes and objects with attributes and methods. Learn inheritance and encapsulation.

# Class definition
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def introduce(self):
        return f"I am {self.name}"

# Create object
p1 = Person("Alex", 25)
print(p1.introduce())

10 File Handling

Read from and write to files using Python's built-in file operations.

# Write to file
with open("file.txt", "w") as f:
    f.write("Hello, World!")

# Read from file
with open("file.txt", "r") as f:
    content = f.read()
    print(content)
💡 Always use with statement — it automatically closes the file after use.

11 Error Handling

Handle exceptions gracefully with try/except blocks to prevent crashes.

try:
    num = int(input("Enter a number: "))
    result = 100 / num
except ValueError:
    print("Please enter a valid number")
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("Execution complete")

12 List Comprehension

Create new lists in a single line with Python's elegant comprehension syntax.

# List comprehension
squares = [x**2 for x in range(10)]
print(squares)  # [0,1,4,9,16,25,36,49,64,81]

# With condition
evens = [x for x in range(20) if x % 2 == 0]

13 Modules & Imports

Organize code with modules and leverage Python's vast standard library.

# Import entire module
import math
print(math.sqrt(16))     # 4.0

# Import specific
from datetime import datetime
print(datetime.now())

# Import with alias
import random as rnd
print(rnd.randint(1, 10))

14 Best Practices

Write clean, Pythonic code following PEP 8 guidelines and industry standards.

✅ Snake Case

Use my_variable naming

✅ Docstrings

Document functions with """..."""

✅ Type Hints

def func(x: int) -> str:

✅ Virtual Env

Use venv for isolation

✅ PEP 8

Follow style guide

✅ List Comprehensions

Prefer over loops

✅ f-Strings

Use for formatting

✅ Context Managers

Use 'with' statements