Python Tutorials

"Learn Python from basics to advanced level"

Python

Python is a versatile, high-level programming language used for web development, data science, automation, and more.

Hello World

print("Hello, World!")

Variables and Data Types

x = 10          # Integer
y = 3.14        # Float
name = "Alice"  # String
is_active = True # Boolean
nums = [1,2,3]  # List
person = {"name":"Bob","age":25} # Dictionary

Operators

a, b = 10, 5
print(a + b) # 15
print(a - b) # 5
print(a * b) # 50
print(a / b) # 2.0
print(a % b) # 0
print(a > b) # True

Conditional Statements

age = 18
if age >= 18:
    print("Adult")
else:
    print("Minor")

Loops

# For loop
for i in range(5):
    print(i)

# While loop
j = 0
while j < 5:
    print(j)
    j += 1

Functions

def greet(name):
    return "Hello " + name

print(greet("Alice"))

# Lambda
add = lambda x, y: x + y
print(add(2,3))

Lists

fruits = ["apple","banana","cherry"]
fruits.append("orange")
print(fruits[0])
for f in fruits:
    print(f)

Dictionaries

person = {"name":"Alice","age":25}
print(person["name"])
person["age"] = 30
for k,v in person.items():
    print(k, v)

Classes & Objects

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        print(f"Hello, I am {self.name}")

p1 = Person("Alice", 25)
p1.greet()

File Handling

# Write
with open("test.txt", "w") as f:
    f.write("Hello File")

# Read
with open("test.txt", "r") as f:
    print(f.read())

Exception Handling

try:
    x = 10 / 0
except ZeroDivisionError as e:
    print("Error:", e)
finally:
    print("Done")

Modules

# math module
import math
print(math.sqrt(16))

# custom module
# utils.py
def add(a,b): return a+b

# main.py
from utils import add
print(add(2,3))

Virtual Environment

python -m venv myenv
source myenv/bin/activate   # Linux/Mac
myenv\Scripts\activate      # Windows

Packages (pip)

pip install requests
pip list
pip uninstall requests

Inheritance & Polymorphism

class Animal:
    def speak(self):
        print("Some sound")

class Dog(Animal):
    def speak(self):
        print("Woof!")

d = Dog()
d.speak()

Decorators

def my_decorator(func):
    def wrapper():
        print("Before function")
        func()
        print("After function")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

Generators

def counter():
    for i in range(3):
        yield i

for val in counter():
    print(val)

Async IO

import asyncio

async def hello():
    print("Hello")
    await asyncio.sleep(1)
    print("World")

asyncio.run(hello())