- Create a Python dictionary containing information about a person (name, age, address).
- Add a new key-value pair to the dictionary.
- Write a function that iterates through the dictionary and prints all key-value pairs.
# Create a Python dictionary containing information about a person (name, age, address).
person_info = {
"name": "John Doe",
"age": 30,
"address": "123 Main Street, City"
}
# Add a new key-value pair to the dictionary.
person_info["email"] = "john@example.com"
# Write a function that iterates through the dictionary and prints all key-value pairs.
def print_person_info(info_dict):
for key, value in info_dict.items():
print(f"{key}: {value}")
# Call the function to print the person's information.
print_person_info(person_info)In this code:
- We create a dictionary called
person_infocontaining information about a person. - We add a new key-value pair
"email": "john@example.com"to the dictionary. - We define a function
print_person_infothat takes a dictionary as an argument and iterates through it using aforloop to print all key-value pairs. - Finally, we call the
print_person_infofunction with theperson_infodictionary to print the person's information.
Python File I/O:
- Create a text file and write some text into it using Python.
- Read the content of the file and print it to the console.
- Implement error handling to ensure the file is properly closed, even if an exception occurs.
try:
# Create and write to a text file
with open("example.txt", "w") as file:
file.write("Hello, this is some text written to the file.\n")
file.write("This is a second line of text.\n")
# Read the content of the file and print it to the console
with open("example.txt", "r") as file:
file_content = file.read()
print("File Content:")
print(file_content)
except FileNotFoundError:
print("The file was not found.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
print("File operation completed.")In this code:
- We use a
tryblock to handle potential exceptions that may occur during file operations. - Inside the first
withstatement, we open the file named "example.txt" in write mode ("w") and write some lines of text to it. - Inside the second
withstatement, we open the same file in read mode ("r"), read its content using theread()method, and print it to the console. - We use the
exceptblock to catch specific exceptions. In this example, we catchFileNotFoundErrorif the file does not exist and a generalExceptionfor other potential errors. - In the
finallyblock, we print a message to indicate that the file operation has completed. This block is executed regardless of whether an exception occurs, ensuring that the file is properly closed.
Make sure to replace the file name ("example.txt") and the content with your desired file name and text.
Python Functions:
- Define a Python function that takes two parameters and returns their sum.
- Use a lambda expression to define a small function that squares a given number.
Define a function to calculate the sum of two numbers:
def add_numbers(a, b):
return a + b
# Example usage:
result = add_numbers(5, 7)
print("Sum:", result) # Output: Sum: 12In this code, we define a function called add_numbers that takes two parameters (a and b) and returns their sum.
Use a lambda expression to create a function that squares a number:
square = lambda x: x ** 2
# Example usage:
result = square(4)
print("Square:", result) # Output: Square: 16Here, we define a lambda function square that takes a single parameter x and returns the square of x. Lambda expressions are useful for creating small, anonymous functions like this.
Python Lists and Tuples:
- Create a list of numbers and sort it in ascending order.
- Create a tuple containing the names of fruits and write a function to search for a specific fruit in the tuple.
Create a list of numbers and sort it in ascending order:
# Create a list of numbers
numbers = [5, 2, 9, 1, 7]
# Sort the list in ascending order
sorted_numbers = sorted(numbers)
# Print the sorted list
print("Sorted Numbers:", sorted_numbers)In this code, we first create a list of numbers and then use the sorted() function to sort the list in ascending order.
Create a tuple containing the names of fruits and write a function to search for a specific fruit:
# Create a tuple containing names of fruits
fruits = ("apple", "banana", "cherry", "date", "fig")
# Function to search for a specific fruit in the tuple
def search_fruit(fruit_name, fruit_tuple):
if fruit_name in fruit_tuple:
return f"{fruit_name} is in the list of fruits."
else:
return f"{fruit_name} is not in the list of fruits."
# Example usage:
search_result = search_fruit("banana", fruits)
print(search_result) # Output: banana is in the list of fruits.Here, we create a tuple called fruits containing the names of fruits. Then, we define a function search_fruit that takes the name of a fruit and the fruit tuple as parameters and checks if the given fruit is in the tuple.
Python Modules and Imports:
- Create a custom Python module that contains a function to calculate the area of a rectangle.
- Import and use this module in another Python script.
Create the Python Module (rectangle.py):
Create a file named rectangle.py, and define a function for calculating the area of a rectangle within this module.
# rectangle.py
def calculate_area(length, width):
return length * widthCreate a Python Script to Use the Module (main.py):
Create another Python script (e.g., main.py) where you import the custom module and use the calculate_area function.
# main.py
import rectangle # Import the custom module
# Use the calculate_area function from the module
length = 5
width = 10
area = rectangle.calculate_area(length, width)
print(f"The area of the rectangle with length {length} and width {width} is {area}.")Run the Python Script:
Now, you can run main.py, and it will import the rectangle module and use the calculate_area function from the module to calculate and print the area of a rectangle with the specified length and width.
$ python main.py
The area of the rectangle with length 5 and width 10 is 50.Python Regular Expression Usage:
- Write a Python program that uses regular expressions to validate email addresses.
- Use regular expressions to extract all phone numbers from a given text.
import re
# Regular expression pattern for validating email addresses
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
# Regular expression pattern for extracting phone numbers (assuming a basic pattern)
phone_pattern = r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b'
# Function to validate an email address
def is_valid_email(email):
return re.match(email_pattern, email) is not None
# Function to extract phone numbers from text
def extract_phone_numbers(text):
return re.findall(phone_pattern, text)
# Validate email addresses
emails = ["john@example.com", "jane@gmail.com", "invalid-email"]
for email in emails:
if is_valid_email(email):
print(f"{email} is a valid email address.")
else:
print(f"{email} is not a valid email address.")
# Extract phone numbers from text
text = "Call me at 123-456-7890 or 555.555.5555 for assistance."
phone_numbers = extract_phone_numbers(text)
print("Phone Numbers:", phone_numbers)In this code:
- We define a regular expression pattern for email validation (
email_pattern) and phone number extraction (phone_pattern). - The
is_valid_emailfunction usesre.matchto check if an email address matches the email pattern. - The
extract_phone_numbersfunction usesre.findallto find all phone numbers that match the phone number pattern in the given text. - We validate a list of email addresses and print whether they are valid or not.
- We extract phone numbers from the provided text and print them.
Please note that the email and phone number patterns provided in this example are simplified for demonstration purposes and may not cover all possible variations of email addresses and phone number formats. You can adjust the patterns to suit your specific needs.
Python Classes:
- Define a Python class representing a "Person" with attributes like name and age.
- Create a subclass of "Person" called "Student" with additional attributes like grade and school.
# Define the base class "Person"
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"Hello, my name is {self.name}, and I am {self.age} years old.")
# Create an instance of "Person"
person1 = Person("John", 30)
person1.introduce() # Output: Hello, my name is John, and I am 30 years old.
# Define the subclass "Student" that inherits from "Person"
class Student(Person):
def __init__(self, name, age, grade, school):
# Call the constructor of the base class ("Person") using super()
super().__init__(name, age)
self.grade = grade
self.school = school
def study(self):
print(f"I am a student in grade {self.grade} at {self.school}.")
# Create an instance of "Student"
student1 = Student("Alice", 15, 9, "ABC High School")
student1.introduce() # Output: Hello, my name is Alice, and I am 15 years old.
student1.study() # Output: I am a student in grade 9 at ABC High School.In this code:
- We first define a base class called "Person" with attributes
nameandage. It also has a methodintroduceto introduce the person. - We then create an instance of "Person" called
person1and use theintroducemethod to introduce the person. - Next, we define a subclass called "Student" that inherits from "Person." It has additional attributes
gradeandschool. We usesuper()to call the constructor of the base class. - We create an instance of "Student" called
student1, which inherits thenameandageattributes from the "Person" class, and we can also call theintroducemethod from the base class. Additionally, we have astudymethod specific to the "Student" subclass.
This demonstrates how to define a class hierarchy with inheritance in Python, where "Student" is a subclass of "Person."
Python Control Flow:
- Write a Python program using control flow statements to find the factorial of a number.
- Implement a loop that iterates through a list and prints even numbers.
Calculate the factorial of a number:
# Function to calculate the factorial of a number
def factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers."
elif n == 0:
return 1
else:
result = 1
while n > 0:
result *= n
n -= 1
return result
# Calculate and print the factorial of a number (e.g., 5)
number = 5
fact = factorial(number)
print(f"Factorial of {number} is {fact}")In this code, we define a function factorial that calculates the factorial of a non-negative integer using a while loop.
Iterate through a list and print even numbers:
# Create a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Iterate through the list and print even numbers
print("Even Numbers:")
for num in numbers:
if num % 2 == 0:
print(num)Here, we create a list called numbers, and then use a for loop to iterate through the list. We check if each number is even using the modulo operator %, and if it is even, we print it.
When you run this program, it will first calculate and print the factorial of the specified number (5 in this case), and then it will iterate through the list and print even numbers from the list.
Python Exception Handling:
- Create a Python program that attempts to open a non-existent file and handle the FileNotFoundError gracefully.
- Define a custom exception and raise it in your code.
# Attempt to open a non-existent file and handle FileNotFoundError
try:
with open("nonexistent_file.txt", "r") as file:
file_content = file.read()
print("File Content:", file_content)
except FileNotFoundError as e:
print(f"FileNotFoundError: {e}")
print("The file does not exist or cannot be opened.")
# Define a custom exception class
class CustomException(Exception):
def __init__(self, message):
super().__init__(message)
# Raise the custom exception
try:
raise CustomException("This is a custom exception.")
except CustomException as ce:
print(f"Custom Exception Raised: {ce}")In this code:
- We first attempt to open a non-existent file ("nonexistent_file.txt") within a
tryblock. If the file is not found, aFileNotFoundErroris raised. - We catch the
FileNotFoundErrorexception and handle it gracefully by printing an error message. - Next, we define a custom exception class
CustomExceptionthat inherits from the built-inExceptionclass. This custom exception class has an__init__method to set a custom error message. - We raise the custom exception using a
raisestatement within atryblock, and then we catch and handle the custom exception, printing the custom error message.
When you run this program, it will demonstrate handling the FileNotFoundError gracefully and raising and catching the custom exception.
Python Comprehensions:
- Create a list comprehension to generate a list of squares of numbers from 1 to 10.
- Use a dictionary comprehension to convert a list of tuples into a dictionary.
Create a list comprehension to generate squares of numbers:
# List comprehension to generate squares of numbers from 1 to 10
squares = [x ** 2 for x in range(1, 11)]
print("Squares of numbers from 1 to 10:", squares)In this code, the list comprehension [x ** 2 for x in range(1, 11)] generates a list of squares by iterating through numbers from 1 to 10.
Use a dictionary comprehension to convert a list of tuples into a dictionary:
# List of tuples
tuples_list = [("apple", 3), ("banana", 2), ("cherry", 5)]
# Dictionary comprehension to convert the list of tuples into a dictionary
fruit_dict = {key: value for key, value in tuples_list}
print("Dictionary from list of tuples:", fruit_dict)In this code, we have a list of tuples tuples_list, and the dictionary comprehension {key: value for key, value in tuples_list} converts each tuple into a key-value pair in the dictionary, resulting in a dictionary where the first element of each tuple becomes the key, and the second element becomes the value.
When you run this code, it will generate the list of squares from 1 to 10 and convert the list of tuples into a dictionary, printing the results.
Python Strings:
- Write a function that takes a string and returns the reversed string.
- Use slicing to extract specific portions of a string, such as the first three characters.
Write a function to reverse a string:
# Function to reverse a string
def reverse_string(input_string):
return input_string[::-1]
# Example usage:
original_string = "Hello, World!"
reversed_string = reverse_string(original_string)
print("Original String:", original_string)
print("Reversed String:", reversed_string)In this code, we define a function reverse_string that takes an input string and returns its reverse using slicing with [::-1].
Use slicing to extract specific portions of a string:
# Extract the first three characters of a string
input_string = "Python Programming"
first_three_characters = input_string[:3]
print("Input String:", input_string)
print("First Three Characters:", first_three_characters)Here, we use slicing [:3] to extract the first three characters of the input string.
When you run this code, it will reverse the original string and extract the first three characters from another string, printing the results.
Python Generators and Coroutines:
- Define a generator function that yields a sequence of even numbers.
- Implement a coroutine that asynchronously fetches data from a web API.
Define a generator function for even numbers:
# Generator function for even numbers
def even_numbers():
num = 2
while True:
yield num
num += 2
# Create a generator object
even_gen = even_numbers()
# Generate and print the first 5 even numbers
for _ in range(5):
print(next(even_gen))In this code, we define a generator function even_numbers that yields even numbers starting from 2 indefinitely. We create a generator object even_gen and use the next function to generate and print the first 5 even numbers.
Implement a coroutine for fetching data from a web API:
import asyncio
import aiohttp
async def fetch_data_from_api(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
data = await response.json()
return data
async def main():
url = "https://jsonplaceholder.typicode.com/todos/1" # Example API URL
data = await fetch_data_from_api(url)
print("Data from API:", data)
# Run the asynchronous main function
loop = asyncio.get_event_loop()
loop.run_until_complete(main())In this code:
- We import the
asyncioandaiohttplibraries for asynchronous operations and HTTP requests. - We define an asynchronous coroutine
fetch_data_from_apithat makes an asynchronous GET request to a web API usingaiohttp. - We define another asynchronous coroutine
mainthat callsfetch_data_from_apito fetch data from the API and print it. - We run the asynchronous
mainfunction using an event loop to asynchronously fetch and print data from the web API.
Make sure to replace the example API URL with the actual URL you want to use. This code demonstrates how to use Python's asyncio and aiohttp libraries to perform asynchronous web API requests.
Python Inheritance:
- Create a base class called "Animal" with common attributes and methods.
- Create subclasses like "Dog" and "Cat" that inherit from the "Animal" class.
# Define the base class "Animal"
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self):
pass # Placeholder method for making a sound
def describe(self):
print(f"I am a {self.species} named {self.name}.")
# Create a subclass "Dog" that inherits from "Animal"
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, species="Dog")
self.breed = breed
def make_sound(self):
return "Woof!"
def describe(self):
super().describe()
print(f"I am a {self.breed} dog.")
# Create a subclass "Cat" that inherits from "Animal"
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name, species="Cat")
self.color = color
def make_sound(self):
return "Meow!"
def describe(self):
super().describe()
print(f"I am a {self.color} cat.")
# Create instances of "Dog" and "Cat"
dog = Dog("Buddy", "Golden Retriever")
cat = Cat("Whiskers", "Gray")
# Describe and make sounds of the animals
dog.describe()
print(dog.make_sound()) # Output: Woof!
print()
cat.describe()
print(cat.make_sound()) # Output: Meow!In this code:
- We define a base class called "Animal" with attributes like
nameandspecies. It also has methods likemake_sound(a placeholder method) anddescribeto describe the animal. - We create a subclass called "Dog" that inherits from "Animal" and adds a
breedattribute. We override themake_soundanddescribemethods to provide specific behavior for dogs. - We create another subclass called "Cat" that inherits from "Animal" and adds a
colorattribute. Similarly, we override themake_soundanddescribemethods to provide specific behavior for cats. - We create instances of both "Dog" and "Cat" and call their methods to describe and make sounds.
This demonstrates how to create a class hierarchy with inheritance in Python, where "Dog" and "Cat" are subclasses of the "Animal" class.
Python Functional Programming:
- Write a function that takes a list of numbers and returns a new list with all even numbers squared.
- Use functional programming concepts like map and filter to process a list of strings.
Write a function to square even numbers in a list:
# Function to square even numbers in a list
def square_even_numbers(numbers):
# Use filter to get even numbers and map to square them
even_numbers = filter(lambda x: x % 2 == 0, numbers)
squared_even = map(lambda x: x ** 2, even_numbers)
return list(squared_even)
# Example usage:
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
result = square_even_numbers(numbers)
print("Squared Even Numbers:", result)In this code, we define a function square_even_numbers that takes a list of numbers. We use the filter function to filter out even numbers and the map function to square them, and then we convert the result to a list.
Process a list of strings using map and filter:
# List of strings
strings = ["apple", "banana", "cherry", "date", "fig"]
# Use map to capitalize the first letter of each string
capitalized_strings = map(lambda x: x.capitalize(), strings)
# Use filter to get strings longer than 5 characters
long_strings = filter(lambda x: len(x) > 5, strings)
print("Capitalized Strings:", list(capitalized_strings))
print("Long Strings:", list(long_strings))Here, we have a list of strings strings. We use the map function to capitalize the first letter of each string and the filter function to get strings longer than 5 characters. The results are then converted to lists and printed.
When you run this code, it will square even numbers in the list and process the list of strings using functional programming concepts.
Python Formatting and Decorators:
- Create a Python decorator that logs the execution time of a function.
- Use a decorator to add authentication checks to a function.
Create a decorator to log the execution time of a function:
import time
# Decorator function to log the execution time of a function
def timing_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function {func.__name__} took {end_time - start_time:.2f} seconds to execute.")
return result
return wrapper
# Use the decorator to time a function
@timing_decorator
def some_function():
# Simulate some work
time.sleep(2)
some_function()In this code, we define a decorator timing_decorator that measures the execution time of a function by recording the start and end times. We apply this decorator to the some_function using the @ syntax.
Create a decorator to add authentication checks to a function:
# Decorator function to perform authentication checks
def authentication_decorator(func):
def wrapper(*args, **kwargs):
# Simulate authentication checks (e.g., check if user is logged in)
is_authenticated = True # Replace with your authentication logic
if is_authenticated:
result = func(*args, **kwargs)
return result
else:
return "Authentication failed. Access denied."
return wrapper
# Use the decorator to add authentication checks to a function
@authentication_decorator
def protected_resource():
return "This is a protected resource."
# Simulate an authenticated user
authenticated_user = True
if authenticated_user:
result = protected_resource()
print(result)
else:
print("User is not authenticated.")In this code, we define a decorator authentication_decorator that performs authentication checks (you can replace the logic with your own authentication mechanism). We apply this decorator to the protected_resource function, which represents a protected resource that requires authentication.
When you run this code with an authenticated user, it will execute the protected_resource function and print the result. If the user is not authenticated, it will print "Authentication failed. Access denied."
Python Encapsulation:
- Define a Python class with private attributes and methods.
- Implement getter and setter methods to access and modify the private attributes.
class Person:
def __init__(self, name, age):
self.__name = name # Private attribute
self.__age = age # Private attribute
# Getter method for name
def get_name(self):
return self.__name
# Setter method for name
def set_name(self, new_name):
self.__name = new_name
# Getter method for age
def get_age(self):
return self.__age
# Setter method for age
def set_age(self, new_age):
if 0 <= new_age <= 150: # Adding validation for age
self.__age = new_age
else:
print("Invalid age value. Age should be between 0 and 150.")
def introduce(self):
print(f"My name is {self.__name} and I am {self.__age} years old.")
# Create an instance of the Person class
person = Person("John", 30)
# Access private attributes using getter methods
print("Name:", person.get_name()) # Output: Name: John
print("Age:", person.get_age()) # Output: Age: 30
# Modify private attributes using setter methods
person.set_name("Jane")
person.set_age(25)
# Call the introduce method
person.introduce() # Output: My name is Jane and I am 25 years old.
# Attempt to set an invalid age
person.set_age(200) # Output: Invalid age value. Age should be between 0 and 150.In this code:
- We define a
Personclass with private attributes__nameand__ageby prefixing them with double underscores. - We provide getter methods (
get_nameandget_age) to access these private attributes and setter methods (set_nameandset_age) to modify them. The setter for__agealso includes validation to ensure the age is within a valid range. - The
introducemethod is used to print the name and age of the person. - We create an instance of the
Personclass, access and modify its private attributes using the getter and setter methods, and demonstrate how encapsulation helps control access to the private attributes while providing methods to interact with them.