Home
Education
D/L Mode
HTML CSS JavaScript Python SQL Node.js PHP Java C++

Welcome to PYTHON

Start your journey in programming

Lessons

Start learning step by step

Question & Answer

Check your understanding

Interview Asked Questions

Prepare for real interviews

Quiz

Test your skills

🐍 Python Lesson 1: Introduction to Python

Python is a powerful, easy-to-learn programming language. It is used for web development, data science, AI, automation, and more.

# Print your first message
print("Hello, Python!")
    
βœ”

🐍 Python Lesson 2: Variables

Variables store data. You can store numbers, text, and more.

# Numbers
age = 20

# Text
name = "Zohil"

# Boolean
is_student = True

print(name, age, is_student)
    
βœ”

🐍 Python Lesson 3: Data Types

Python has different data types like integer, float, string, and boolean.

# Integer
x = 10

# Float
y = 3.14

# String
text = "Hello"

# Boolean
flag = False

print(type(x), type(y), type(text), type(flag))
    
βœ”

🐍 Python Lesson 4: Basic Operations

Python can perform basic math operations easily.

a = 10
b = 5

# Addition
print(a + b)

# Subtraction
print(a - b)

# Multiplication
print(a * b)

# Division
print(a / b)

# Floor Division
print(a // b)

# Modulus
print(a % b)
    
βœ”

🐍 Python Lesson 5: Strings

Strings are sequences of characters. You can manipulate them in many ways.

text = "Python is awesome!"

# Length
print(len(text))

# Uppercase
print(text.upper())

# Lowercase
print(text.lower())

# Replace
print(text.replace("awesome", "amazing"))

# Concatenate
name = "Zohil"
print("Hello " + name)
    
βœ”

🐍 Python Lesson 6: User Input

You can ask the user for input using input().

# Ask for user name
name = input("Enter your name: ")

# Ask for age
age = input("Enter your age: ")

print("Hello", name, "You are", age, "years old")
    
βœ”

🐍 Python Lesson 7: Lists

Lists store multiple items in order. You can add, remove, or access items.

fruits = ["apple", "banana", "cherry"]

# Access first item
print(fruits[0])

# Add a new fruit
fruits.append("orange")

# Remove a fruit
fruits.remove("banana")

print(fruits)
    
βœ”

🐍 Python Lesson 8: Tuples

Tuples are like lists but **cannot be changed** (immutable).

colors = ("red", "green", "blue")

# Access first color
print(colors[0])

# Tuples cannot be modified
# colors[0] = "yellow"  # This will give an error

print(colors)
    
βœ”

🐍 Python Lesson 9: Sets

Sets are unordered collections of **unique items**.

numbers = {1, 2, 3, 2, 1}

# Add a number
numbers.add(4)

# Remove a number
numbers.remove(2)

print(numbers)  # Output will have unique items only
    
βœ”

🐍 Python Lesson 10: Dictionaries

Dictionaries store data in **key-value pairs**.

person = {
    "name": "Zohil",
    "age": 20,
    "city": "Kabul"
}

# Access value
print(person["name"])

# Add a new key-value
person["profession"] = "Student"

# Remove a key
del person["age"]

print(person)
    
βœ”

🐍 Python Lesson 11: If Statements

If statements let your program make decisions based on conditions.

age = 18

if age >= 18:
    print("You are an adult")
else:
    print("You are a minor")
    
βœ”

🐍 Python Lesson 12: Comparison Operators

Comparison operators help compare values.

a = 10
b = 5

print(a == b)   # Equal
print(a != b)   # Not equal
print(a > b)    # Greater than
print(a < b)    # Less than
print(a >= b)   # Greater or equal
print(a <= b)   # Less or equal
    
βœ”

🐍 Python Lesson 13: Logical Operators

Logical operators combine conditions.

x = 10
y = 5

print(x > 0 and y > 0)   # True if both are True
print(x > 0 or y < 0)    # True if at least one is True
print(not(x > 0))        # Inverts the condition
    
βœ”

🐍 Python Lesson 14: For Loops

For loops repeat code for each item in a sequence.

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

# Loop with range
for i in range(5):
    print(i)
    
βœ”

🐍 Python Lesson 15: While Loops

While loops repeat code as long as a condition is True.

count = 0

while count < 5:
    print("Count is", count)
    count += 1
    
βœ”

🐍 Python Lesson 16: Functions

Functions let you reuse code by grouping statements together.

# Define a function
def greet():
    print("Hello, Python!")

# Call the function
greet()
    
βœ”

🐍 Python Lesson 17: Function Parameters

Functions can take inputs called parameters.

def greet(name):
    print("Hello,", name)

greet("Zohil")
greet("Alice")
    
βœ”

🐍 Python Lesson 18: Return Values

Functions can return values to use later in the program.

def add(a, b):
    return a + b

result = add(5, 10)
print(result)
    
βœ”

🐍 Python Lesson 19: Scope

Scope defines where variables can be accessed in your code.

x = 10  # Global variable

def my_func():
    y = 5  # Local variable
    print("Inside function:", x, y)

my_func()
print("Outside function:", x)
# print(y)  # This will give an error because y is local
    
βœ”

🐍 Python Lesson 20: Lambda Functions

Lambda functions are small, anonymous functions you can write in one line.

# Normal function
def square(x):
    return x * x

# Lambda function
square = lambda x: x * x

print(square(5))
    
βœ”

🐍 Python Lesson 21: Modules

Modules are files containing Python code (functions, variables, classes) that you can reuse.

# Import the math module
import math

print(math.sqrt(16))  # Square root
print(math.pi)        # Pi value
    
βœ”

🐍 Python Lesson 22: Importing Specific Items

You can import only specific functions or variables from a module.

from math import sqrt, pi

print(sqrt(25))
print(pi)
    
βœ”

🐍 Python Lesson 23: Exception Handling

Exceptions are errors that occur during program execution. You can handle them gracefully.

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
    
βœ”

🐍 Python Lesson 24: Try / Except / Finally

The finally block always runs, whether an exception occurred or not.

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("That's not a valid number!")
finally:
    print("Execution finished.")
    
βœ”

🐍 Python Lesson 25: File Handling

Python can read from and write to files.

# Write to a file
with open("example.txt", "w") as file:
    file.write("Hello Python!\n")

# Read from a file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
    
βœ”

🐍 Python Lesson 26: Classes

Classes let you create your own data types with attributes and methods.

# Define a class
class Person:
    pass

# Create an object
p1 = Person()
print(p1)
    
βœ”

🐍 Python Lesson 27: Objects

Objects are instances of a class and can have their own attributes.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Create objects
p1 = Person("Zohil", 20)
p2 = Person("Alice", 25)

print(p1.name, p1.age)
print(p2.name, p2.age)
    
βœ”

🐍 Python Lesson 28: Constructors

Constructors (__init__) initialize object attributes when creating objects.

class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

my_car = Car("Toyota", "Corolla")
print(my_car.brand, my_car.model)
    
βœ”

🐍 Python Lesson 29: Methods

Methods are functions defined inside a class that operate on objects.

class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print("Hello, my name is", self.name)

p1 = Person("Zohil")
p1.greet()
    
βœ”

🐍 Python Lesson 30: Inheritance

Inheritance allows a class to inherit attributes and methods from another class.

# Parent class
class Animal:
    def eat(self):
        print("Eating...")

# Child class
class Dog(Animal):
    def bark(self):
        print("Barking...")

d = Dog()
d.eat()   # Inherited method
d.bark()  # Own method
    
βœ”

🐍 Python Lesson 31: Polymorphism

Polymorphism allows different classes to have methods with the same name but behave differently.

class Cat:
    def speak(self):
        print("Meow")

class Dog:
    def speak(self):
        print("Bark")

animals = [Cat(), Dog()]

for animal in animals:
    animal.speak()  # Each object uses its own method
    
βœ”

🐍 Python Lesson 32: Encapsulation

Encapsulation hides data to prevent direct access from outside the class.

class Person:
    def __init__(self, name, age):
        self.__name = name  # Private attribute
        self.__age = age

    def get_name(self):
        return self.__name

p = Person("Zohil", 20)
print(p.get_name())    # Access via method
# print(p.__name)      # This will give an error
    
βœ”

🐍 Python Lesson 33: Decorators

Decorators are functions that modify the behavior of another function.

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

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

say_hello()
    
βœ”

🐍 Python Lesson 34: Iterators

Iterators allow you to traverse through a collection one item at a time.

numbers = [1, 2, 3]
it = iter(numbers)

print(next(it))  # 1
print(next(it))  # 2
print(next(it))  # 3
    
βœ”

🐍 Python Lesson 35: Generators

Generators are functions that yield values one at a time using yield.

def my_generator():
    for i in range(5):
        yield i

gen = my_generator()

for value in gen:
    print(value)
    
βœ”

🐍 Python Lesson 36: List & Dictionary Comprehensions

Comprehensions let you create lists or dictionaries in a single line.

# List comprehension
squares = [x*x for x in range(5)]
print(squares)  # [0, 1, 4, 9, 16]

# Dictionary comprehension
square_dict = {x: x*x for x in range(5)}
print(square_dict)  # {0:0, 1:1, 2:4, 3:9, 4:16}
    
βœ”

🐍 Python Lesson 37: Regular Expressions

Regular expressions (regex) are used to find patterns in text.

import re

text = "My phone number is 123-456-7890"
pattern = r"\d{3}-\d{3}-\d{4}"

match = re.search(pattern, text)
if match:
    print("Phone number found:", match.group())
    
βœ”

🐍 Python Lesson 38: Working with JSON

JSON is used to store and exchange data. Python can read and write JSON easily.

import json

data = {"name": "Zohil", "age": 20, "city": "Kabul"}

# Convert to JSON string
json_string = json.dumps(data)
print(json_string)

# Convert back to Python dictionary
python_data = json.loads(json_string)
print(python_data)
    
βœ”

🐍 Python Lesson 39: Virtual Environments

Virtual environments allow you to manage project-specific dependencies.

# Create a virtual environment
# python -m venv myenv

# Activate environment (Windows)
# myenv\Scripts\activate

# Activate environment (Mac/Linux)
# source myenv/bin/activate

# Install packages inside virtual environment
# pip install requests
    
βœ”

🐍 Python Lesson 40: Final Project Example

Let's combine everything learned in a small Python project: a simple contact manager.

# Simple contact manager
contacts = {}

def add_contact(name, phone):
    contacts[name] = phone

def show_contacts():
    for name, phone in contacts.items():
        print(name, ":", phone)

# Add contacts
add_contact("Zohil", "123-456-7890")
add_contact("Alice", "987-654-3210")

# Show contacts
show_contacts()
    
πŸŽ‰ Congratulations! You have completed all Pythons lessons!
Keep practicing and building amazing Applications!

πŸ’‘ Python Questions & Answers

❓ What is Python?
Python is a high-level, interpreted programming language known for its simplicity and readability. It's used in web development, data science, automation, and more.
❓ What are Python's key features?
Python has simple syntax, dynamic typing, supports multiple programming paradigms (procedural, object-oriented, functional), and has a large standard library.
❓ What is a Python variable?
A variable is a name that stores data in memory. Python automatically determines the type, so you don’t need to declare it explicitly.
❓ What is a Python list?
A list is an ordered collection of items that can be of different types. Lists are mutable, meaning you can change their content after creation.
❓ What is a Python function?
A function is a reusable block of code that performs a specific task. It can take inputs (parameters) and return an output using the return statement.
❓ What is a Python tuple?
A tuple is an ordered collection of items, similar to a list, but it is immutable, meaning its content cannot be changed after creation.
❓ What is a Python dictionary?
A dictionary is an unordered collection of key-value pairs. Each key must be unique, and values can be of any data type.
❓ What is a Python set?
A set is an unordered collection of unique items. Sets are mutable, but they do not allow duplicate elements and do not maintain order.
❓ What is a Python loop?
A loop is used to execute a block of code repeatedly. Python has for loops for iterating over sequences and while loops that run as long as a condition is true.
❓ What is a Python if-else statement?
An if-else statement is used to make decisions in Python. It executes a block of code if a condition is true, and another block if the condition is false.
❓ What is a Python module?
A module is a file containing Python code (functions, classes, variables) that can be imported and used in other Python programs to organize code efficiently.
❓ What is a Python package?
A package is a collection of Python modules organized in a directory with an __init__.py file, allowing modular and reusable code across projects.
❓ What is Python’s `None` value?
`None` is a special value in Python that represents the absence of a value or a null value. It is often used to signify β€œno result” or an uninitialized variable.
❓ What is the difference between Python lists and tuples?
Lists are mutable (can be changed), while tuples are immutable (cannot be changed). Both store ordered collections, but tuples are faster and safer for fixed data.
❓ What are Python’s data types?
Python has several built-in data types, including integers (`int`), floating-point numbers (`float`), strings (`str`), lists (`list`), tuples (`tuple`), sets (`set`), dictionaries (`dict`), and boolean (`bool`).
❓ What is Python’s indentation rule?
Python uses indentation (spaces or tabs) to define blocks of code instead of braces. Proper indentation is mandatory; incorrect indentation causes errors.
❓ What is the difference between `==` and `is` in Python?
`==` checks if the values of two objects are equal, while `is` checks if both objects refer to the same memory location (i.e., the same object).
❓ What is a Python class?
A class is a blueprint for creating objects. It defines attributes (variables) and methods (functions) that the objects created from the class can use.
❓ What is a Python object?
An object is an instance of a class. It contains data (attributes) and functions (methods) defined by its class and can perform actions or hold information.
❓ What is inheritance in Python?
Inheritance allows a class (child) to acquire attributes and methods from another class (parent), promoting code reuse and hierarchical relationships.
❓ What is polymorphism in Python?
Polymorphism allows objects of different classes to be treated as objects of a common superclass. It lets the same operation work on different types of objects.
❓ What is encapsulation in Python?
Encapsulation is the practice of restricting access to a class’s internal data and methods. It protects the object’s state and provides controlled access via methods.
❓ What is a Python constructor?
A constructor is a special method named __init__ in a class. It is automatically called when an object is created to initialize its attributes.
❓ What is the difference between Python `deepcopy` and `shallow copy`?
A shallow copy creates a new object but references the original nested objects, so changes affect both. A deep copy creates a completely independent copy of the object and its nested objects.
❓ What is Python’s `pass` statement?
The `pass` statement is a placeholder that does nothing. It is used when a statement is syntactically required but no action is needed.
❓ What is Python’s `break` statement?
The `break` statement is used inside loops to immediately exit the loop, even if the loop condition is still true.
❓ What is Python’s `continue` statement?
The `continue` statement skips the rest of the current iteration in a loop and moves to the next iteration without exiting the loop.
❓ What is Python’s `try-except` block?
A `try-except` block is used for error handling. Code inside `try` is executed, and if an exception occurs, the `except` block handles it without crashing the program.
❓ What is Python’s `with` statement?
The `with` statement is used to wrap the execution of a block with methods defined by a context manager. It ensures proper resource management, like automatically closing files.
❓ What is Python’s `lambda` function?
A `lambda` function is an anonymous, small function defined with the `lambda` keyword. It can take any number of arguments but has only a single expression.

🎯 Python Interview Questions

❓ What is Python and why is it popular?
Python is a high-level, interpreted programming language known for its simplicity and readability. It’s popular because of its versatility, extensive libraries, and ease of learning.
❓ What are Python’s key features?
Python has simple syntax, dynamic typing, support for multiple paradigms (procedural, OOP, functional), automatic memory management, and a vast standard library.
❓ What is the difference between Python lists and tuples?
Lists are mutable (can be changed) while tuples are immutable (cannot be changed). Tuples are faster and safer for fixed data, lists are flexible for dynamic data.
❓ What is Python’s pass statement?
The `pass` statement is a placeholder that does nothing. It is used when a statement is syntactically required but no action needs to be performed.
❓ What are Python decorators?
Decorators are functions that modify the behavior of other functions or methods. They are often used for logging, access control, and memoization.
❓ What is the difference between Python shallow copy and deep copy?
A shallow copy copies the object but references the same nested objects. A deep copy creates a completely independent copy of the object and all its nested objects.
❓ What is Python’s GIL (Global Interpreter Lock)?
The GIL is a mutex that allows only one thread to execute Python bytecode at a time. It prevents race conditions but can limit multi-threaded CPU-bound performance.
❓ What is Python’s difference between `==` and `is`?
`==` checks if the values of two objects are equal, while `is` checks if both objects refer to the same memory location (the same object).
❓ What are Python’s built-in data types?
Python has several built-in data types: int, float, str, list, tuple, dict, set, bool, and NoneType.
❓ What are Python modules and packages?
A module is a file containing Python code (functions, classes, variables). A package is a collection of modules organized in directories with an `__init__.py` file.

πŸ“ Python Quiz: Test Your Knowledge

1. What does Python stand for?

2. Which symbol is used for comments in Python?

3. How do you declare a variable in Python?

4. Which function is used to print output in Python?

5. Which operator is used for exponentiation?

6. Which keyword is used to define a function in Python?

7. How do you create a list in Python?

8. Which keyword is used for conditional statements?

9. Which method adds an item at the end of a list?

10. Which keyword is used to handle exceptions?

11. Which operator is used for floor division?

12. Which of these is immutable?

13. How do you start a for loop in Python?

14. Which function converts a string to an integer?

×