Start your journey in programming
Start learning step by step
Check your understanding
Prepare for real interviews
Test your skills
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!")
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 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 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)
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)
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")
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)
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)
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
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)
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")
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
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
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)
While loops repeat code as long as a condition is True.
count = 0
while count < 5:
print("Count is", count)
count += 1
Functions let you reuse code by grouping statements together.
# Define a function
def greet():
print("Hello, Python!")
# Call the function
greet()
Functions can take inputs called parameters.
def greet(name):
print("Hello,", name)
greet("Zohil")
greet("Alice")
Functions can return values to use later in the program.
def add(a, b):
return a + b
result = add(5, 10)
print(result)
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
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))
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
You can import only specific functions or variables from a module.
from math import sqrt, pi
print(sqrt(25))
print(pi)
Exceptions are errors that occur during program execution. You can handle them gracefully.
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
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 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)
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)
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)
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)
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()
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
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
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
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()
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
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)
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}
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())
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)
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
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()
return statement.
for loops for iterating over sequences and while loops that run as long as a condition is true.
__init__.py file, allowing modular and reusable code across projects.
__init__ in a class. It is automatically called when an object is created to initialize its attributes.
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?