
Python Tutorial
1. Basic Syntax
Hello World:
print("Hello, World!")
Variables:
x = 5
name = "Alice"
Data Types:
Python has various built-in data types, such as:
- Integer (int)
- Float (float)
- String (str)
- Boolean (bool)
x = 5 // int
y = 3.14 // float
name = "John" // str
is_active = True // bool
2. Control Flow
If Statements:
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
For Loops:
// Iterate through a range
for i in range(5):
print(i)
// Iterate through a list
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(name)
While Loops:
count = 0
while count < 5:
print(count)
count += 1
Break and Continue:
for i in range(10):
if i == 5:
break // exit the loop
if i == 3:
continue // skip the rest of the loop and continue
print(i)
3. Functions
Defining Functions:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Returning Values:
def add(a, b):
return a + b
result = add(3, 4)
print(result) // Outputs: 7
Keyword Arguments:
def person_info(name, age):
print(f"Name: {name}, Age: {age}")
person_info(age=30, name="John")
4. Data Structures
Lists (ordered, mutable):
fruits = ["apple", "banana", "cherry"]
fruits.append("date") // Adds an element to the list
print(fruits[1]) // Access element by index (starts at 0)
Tuples (ordered, immutable):
coordinates = (4, 5)
print(coordinates[0]) // Access element by index
Dictionaries (unordered, key-value pairs):
person = {"name": "Alice", "age": 25}
print(person["name"]) // Access value by key
Sets (unordered, no duplicates):
numbers = {1, 2, 3, 4, 5}
numbers.add(6) // Adds an element
print(numbers)
5. List Comprehensions
List Comprehensions allow you to create lists in a more compact and readable way.
squares = [x ** 2 for x in range(5)]
print(squares) // Outputs: [0, 1, 4, 9, 16]
Conditional List Comprehension:
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers) // Outputs: [0, 2, 4, 6, 8]
6. Object-Oriented Programming (OOP)
Defining a Class:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says woof!")
dog1 = Dog("Rex", 3)
dog1.bark() // Outputs: Rex says woof!
Inheritance:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Dog(Animal):
def speak(self):
print(f"{self.name} barks")
dog = Dog("Buddy")
dog.speak() // Outputs: Buddy barks
7. File Handling
Opening and Reading Files:
// Open file and read content
with open("example.txt", "r") as file:
content = file.read()
print(content)
Writing to Files:
with open("output.txt", "w") as file:
file.write("Hello, world!")
Appending to Files:
with open("output.txt", "a") as file:
file.write("\nAppended text.")
8. Error Handling
Try-Except Blocks:
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Finally Block (for cleanup):
try:
file = open("data.txt", "r")
// Some operations
except FileNotFoundError:
print("File not found")
finally:
file.close()
9. Libraries and Modules
Importing a Module:
import math
print(math.sqrt(16)) // Outputs: 4.0
Importing Specific Functions:
from math import sqrt
print(sqrt(16)) // Outputs: 4.0
Creating a Module:
// mymodule.py
def greet(name):
return f"Hello, {name}!"
// Another script
import mymodule
print(mymodule.greet("Alice")) // Outputs: Hello, Alice!
10. Decorators
Function Decorators:
def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()
11. Lambda Functions
Anonymous Functions:
add = lambda x, y: x + y
print(add(2, 3)) // Outputs: 5
12. Iterators and Generators
Creating an Iterator:
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def __next__(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
counter = Counter(1, 3)
for num in counter:
print(num)
Generators:
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
gen = count_up_to(3)
for number in gen:
print(number)
13. Regular Expressions
Using the re module:
import re
pattern = r"\d+" // Matches one or more digits
text = "The number is 42"
match = re.search(pattern, text)
if match:
print(match.group()) // Outputs: 42
14. Working with Dates and Times
Datetime module:
import datetime
now = datetime.datetime.now()
print(now) // Outputs: current date and time
date_str = "2025-03-08"
date_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d")
print(date_obj) // Outputs: 2025-03-08 00:00:00
15. Virtual Environments
Creating a Virtual Environment:
python -m venv myenv
Activating the Virtual Environment:
Windows:
myenv\Scripts\activate
Mac/Linux:
source myenv/bin/activate
Deactivating:
deactivate