AGAmirali Gholian

Amirali Gholian

💻 Python | 🐧 Linux | 🚀 AI
← Back to Home

🐍 Python Programming

A complete guide to Python programming from basics to advanced concepts

1. Variables and Data Types

What is it? Variables store information like a box. Data types tell what kind of information (text, number, etc).
python_basics.py
# Variables store data name = "Alice" # Text (String) age = 25 # Whole number (Integer) height = 5.9 # Decimal number (Float) is_student = True # True or False (Boolean) # Print to show output print(f"Name: {name}") # Convert between types num_text = "123" num = int(num_text) # Convert text to number

2. If Statements (Conditions)

What is it? Conditions let your code make decisions. "If this happens, do that. Otherwise, do something else."
if_statements.py
age = 25 if age >= 18: print("You are an adult") elif age >= 13: print("You are a teenager") else: print("You are a child") # Check multiple conditions if age >= 18 and has_license: print("Can drive")

3. Loops (Repeat Code)

What is it? Loops repeat code multiple times. Useful for doing the same thing over and over.
loops.py
# For loop - repeat a set number of times for i in range(5): print(i) # Prints: 0, 1, 2, 3, 4 # For loop - go through a list fruits = ["apple", "banana", "orange"] for fruit in fruits: print(fruit) # While loop - repeat until condition is false count = 0 while count < 3: print(count) count = count + 1

4. Lists (Store Multiple Items)

What is it? A list is like a shopping list - it stores multiple items in order. You can add, remove, or change items.
lists.py
# Create a list numbers = [1, 2, 3, 4, 5] # Access items (0 is first) print(numbers[0]) # Shows: 1 print(numbers[-1]) # Shows: 5 (last item) # Add and remove numbers.append(6) # Add 6 to end numbers.remove(3) # Remove 3 from list numbers.pop() # Remove last item # List length print(len(numbers)) # Shows: 5 # Check if item in list if 2 in numbers: print("Found it!")

5. Functions (Reusable Code)

What is it? Functions are blocks of code you can reuse. Instead of writing the same code multiple times, put it in a function and call it.
functions.py
# Define a simple function def greet(name): return f"Hello {name}!" result = greet("Alice") print(result) # Shows: Hello Alice! # Function with default value def add(a, b=0): return a + b print(add(5)) # Uses default: 5 + 0 = 5 print(add(5, 3)) # 5 + 3 = 8 # Function that doesn't return anything def say_hello(name): print(f"Hello {name}!") say_hello("Bob")

6. Dictionaries (Key-Value Storage)

What is it? A dictionary stores pairs of information - like a phone book where you look up a name (key) to find a number (value).
dictionaries.py
# Create a dictionary person = { "name": "Alice", "age": 25, "city": "New York" } # Access by key print(person["name"]) # Shows: Alice # Add new key-value person["email"] = "alice@example.com" # Update value person["age"] = 26 # Remove key del person["city"] # Get all keys print(person.keys())

7. Classes and Objects

What is it? Classes are blueprints for creating objects. Like a cookie cutter that makes the same shape cookies, a class defines how objects should look and behave.
classes.py
# Define a class class Dog: def __init__(self, name, age): self.name = name self.age = age def bark(self): return f"{self.name} says Woof!" # Create objects from the class dog1 = Dog("Buddy", 3) dog2 = Dog("Max", 5) # Use the objects print(dog1.name) # Shows: Buddy print(dog1.bark()) # Shows: Buddy says Woof!

8. File Handling (Read and Write)

What is it? Working with files lets you save data to your computer and read it back later.
files.py
# Read a file with open("file.txt", "r") as f: content = f.read() print(content) # Write to a file with open("output.txt", "w") as f: f.write("Hello, World!") # Add to a file (append) with open("log.txt", "a") as f: f.write("\nNew message")

9. Error Handling (Try-Except)

What is it? Sometimes code fails (like dividing by zero). Try-Except lets you handle errors gracefully instead of crashing.
error_handling.py
try: num = int("abc") result = 10 / 0 except ValueError: print("That's not a valid number") except ZeroDivisionError: print("Can't divide by zero") except Exception as e: print(f"Something went wrong: {e}") else: print("No errors!")

10. Lambda (Quick Functions)

What is it? Lambda is a way to write small functions quickly without using def. Perfect for simple, one-time operations.
lambda.py
# Lambda function - quick and simple square = lambda x: x ** 2 print(square(5)) # Shows: 25 # Use with map - apply to all items numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, numbers)) print(squared) # Shows: [1, 4, 9, 16, 25] # Use with filter - keep only matching items even = list(filter(lambda x: x % 2 == 0, numbers)) print(even) # Shows: [2, 4]