Python practice test 2.
Question 1: Calculator App
Create a Python program that acts as a simple calculator. It should take two numbers and an operator as input and perform the corresponding operation.
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y != 0:
return x / y
else:
return "Error: Cannot divide by zero"
# Get user input
num1 = float(input("Enter the first number: "))
operator = input("Enter the operator (+, -, *, /): ")
num2 = float(input("Enter the second number: "))
# Perform calculations based on the operator
if operator == "+":
result = add(num1, num2)
elif operator == "-":
result = subtract(num1, num2)
elif operator == "*":
result = multiply(num1, num2)
elif operator == "/":
result = divide(num1, num2)
else:
result = "Error: Invalid operator"
# Display the result
print(f"Result: {result}")
Output Screenshot:
Question 2: File Manipulation
Write a Python script to read a text file, count the occurrences of each word, and display the result.
import string
def count_word_occurrences(file_path):
word_count = {}
with open(file_path, 'r', encoding='utf-8') as file:
# Read the content of the file
content = file.read()
# Remove punctuation and convert to lowercase
translator = str.maketrans('', '', string.punctuation)
content = content.translate(translator).lower()
# Tokenize the content into words
words = content.split()
# Count occurrences of each word
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
return word_count
def display_word_occurrences(word_count):
for word, count in word_count.items():
print(f'{word}: {count}')
if __name__ == "__main__":
# Example usage
file_path = 'sample_text.txt' # Replace with the path to your text file
try:
word_count = count_word_occurrences(file_path)
display_word_occurrences(word_count)
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
Output Screenshots:
Question 3: String Formatting
Write a Python function that takes a sentence as input and returns the number of words in it.
def count_words(sentence):
# Split the sentence into words
words = sentence.split()
# Return the number of words
return len(words)
# Example usage:
input_sentence = "This is a sample sentence."
word_count = count_words(input_sentence)
print(f"The number of words in the sentence is: {word_count}")
Output Screenshot:
Question 4: User Authentication
Develop a Python program that simulates user authentication. Ask the user to enter a username and password, and validate them against predefined values.
def authenticate_user(username, password):
# Predefined username and password
valid_username = "user123"
valid_password = "password123"
# Check if entered username and password match the predefined values
if username == valid_username and password == valid_password:
return True
else:
return False
# Get user input for username and password
username_input = input("Enter your username: ")
password_input = input("Enter your password: ")
# Authenticate the user
authentication_result = authenticate_user(username_input, password_input)
# Display the authentication result
if authentication_result:
print("Authentication successful! Welcome, " + username_input + ".")
else:
print("Authentication failed. Please check your username and password.")
Output Screenshots:
Question 5: Date Difference
Write a Python function that calculates the difference in days between two given dates.
from datetime import datetime
def date_difference(date_str1, date_str2):
# Convert date strings to datetime objects
date1 = datetime.strptime(date_str1, '%Y-%m-%d')
date2 = datetime.strptime(date_str2, '%Y-%m-%d')
# Calculate the difference in days
difference = abs((date2 - date1).days)
return difference
# Example usage:
date1_input = input("Enter the first date (YYYY-MM-DD): ")
date2_input = input("Enter the second date (YYYY-MM-DD): ")
try:
# Call the function and display the result
difference_in_days = date_difference(date1_input, date2_input)
print(f"The difference between the two dates is {difference_in_days} days.")
except ValueError:
print("Invalid date format. Please use the format YYYY-MM-DD.")
Output Screenshot:
Question 6: Reverse String
Write a Python function that takes a sentence as input and returns the sentence with reversed words.
def reverse_words(sentence):
# Split the sentence into words
words = sentence.split()
# Reverse the order of words
reversed_sentence = ' '.join(reversed(words))
return reversed_sentence
# Example usage:
input_sentence = "This is a sample sentence."
result = reverse_words(input_sentence)
print(f"Original sentence: {input_sentence}")
print(f"Reversed sentence: {result}")
Output Screenshot:
Question 7: Random Password Generator
Write a Python function that generates a random password of a specified length, combining letters, numbers, and symbols.
import random
import string
def generate_random_password(length=12):
# Define characters for password generation
letters = string.ascii_letters
digits = string.digits
symbols = string.punctuation
# Combine characters
all_characters = letters + digits + symbols
# Generate a random password
password = ''.join(random.choice(all_characters) for _ in range(length))
return password
# Example usage:
password_length = 16
generated_password = generate_random_password(password_length)
print(f"Generated Password: {generated_password}")
Output Screenshot:
Question 8: Email Validator
Develop a Python function that validates whether a given string is a valid email address or not.
import re
def is_valid_email(email):
# Define a regular expression pattern for a basic email validation
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
# Use re.match to check if the email matches the pattern
match = re.match(pattern, email)
# Return True if the email is valid, otherwise False
return bool(match)
# Example usage:
input_email = input("Enter an email address: ")
if is_valid_email(input_email):
print(f"The email address '{input_email}' is valid.")
else:
print(f"The email address '{input_email}' is not valid.")
Output Screenshots:
Question 9: Temperature Converter
Write a Python program that converts temperatures between Celsius and Fahrenheit based on user input
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
# Get user input for temperature and unit
temperature = float(input("Enter the temperature: "))
unit = input("Enter the unit (C for Celsius, F for Fahrenheit): ")
# Perform conversion based on user input
if unit.upper() == 'C':
converted_temperature = celsius_to_fahrenheit(temperature)
print(f"{temperature} degrees Celsius is equal to {converted_temperature:.2f} degrees Fahrenheit.")
elif unit.upper() == 'F':
converted_temperature = fahrenheit_to_celsius(temperature)
print(f"{temperature} degrees Fahrenheit is equal to {converted_temperature:.2f} degrees Celsius.")
else:
print("Invalid unit. Please enter 'C' for Celsius or 'F' for Fahrenheit.")
Output Screenshots:
Question 10: Social Media Post Analyzer
Create a Python script that analyzes a given social media post. It could count the number of words, find hashtags, or determine the sentiment
pip install nltk
import nltk
import re
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.sentiment import SentimentIntensityAnalyzer
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('vader_lexicon')
def analyze_social_media_post(post):
# Count the number of words
word_count = len(word_tokenize(post))
# Find hashtags
hashtags = re.findall(r'\#\w+', post)
# Determine sentiment
sia = SentimentIntensityAnalyzer()
sentiment_score = sia.polarity_scores(post)['compound']
# Print results
print("Number of words:", word_count)
print("Hashtags:", hashtags)
print("Sentiment score:", sentiment_score)
if __name__ == "__main__":
# Example usage
social_media_post = "Excited to share my #Python script for analyzing social media posts! #NLTK #SentimentAnalysis"
analyze_social_media_post(social_media_post)
Output Screenshots: