Variable Declaration
# Declaring variables
name = "John"
age = 30
is_active = True
Lists
# Creating a list
numbers = [1, 2, 3, 4, 5]
# Appending to a list
numbers.append(6)
# Accessing list elements
first_number = numbers[0] # 1
Dictionaries
# Creating a dictionary
person = {"name": "John", "age": 30}
# Accessing dictionary values
name = person["name"]
# Adding new key-value pairs
person["city"] = "New York"
Loops
# For loop
for i in range(5):
print(i)
# While loop
count = 0
while count < 5:
print(count)
count += 1
Conditionals
# If, elif, else
if age < 20:
print("Teenager")
elif age < 60:
print("Adult")
else:
print("Senior")
Functions
# Defining a function
def greet(name):
return "Hello " + name
# Calling a function
greeting = greet("John")
print(greeting)
File Handling
# Writing to a file
with open('example.txt', 'w') as file:
file.write('Hello, World!')
# Reading from a file
with open('example.txt', 'r') as file:
content = file.read()
print(content)
Exception Handling
# Try, except block
try:
result = 10 / 0
except ZeroDivisionError:
print("Divided by zero!")
Modules
# Importing a module
import math
# Using a function from the math module
result = math.sqrt(16) # 4.0