Python Practice Test
Practice set-1
Question 1: Reversing a String
Reversing a String. Write a Python function to reverse a given string. The string is “I am learning Python”. Create a function for reversing the string. The name of the function should be “reverse_string”.
def reverse_string(input_string):
reversed_string = input_string[::-1]
return reversed_string
# Example
original_string = "I am learning Python"
reversed_result = reverse_string(original_string)
print(reversed_result)Question 2: Finding Prime Numbers
Finding Prime Numbers. Write a Python function to generate a list of prime numbers up to a given number n. Create a function named generate_prime which will take an input of numbers. Find prime no till 20.
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def generate_prime(n):
primes = [num for num in range(2, n + 1) if is_prime(num)]
return primes
# Example
n = 20
prime_numbers = generate_prime(n)
print(prime_numbers)Question 3: Calculating Factorial
Calculating Factorial. Write a Python function to calculate the factorial of a given non-negative integer. If someone tries to find the factorial of 0 & 1 it should return 1 to the user. The function name should be “factorial” taking an input parameter “n”.
def factorial(n):
if n == 0 or n == 1:
return 1
else:
result = 1
for i in range(2, n + 1):
result *= i
return result
# Example
num = 5
result = factorial(num)
print(result)Question 4: Counting Words in a Sentence
Counting Words in a Sentence. Write a Python function to count the number of words in a given sentence. It should count the words in a sentence. The function name is count_words taking.
def count_words(sentence):
words = sentence.split()
return len(words)
# Example
input_sentence = "Counting Words in a Sentence"
number_of_words = count_words(input_sentence)
print(number_of_words)split() method to split the input sentence into a list of words, and then it returns the length of that list, which gives the count of words in the sentence.Question 5: Finding Maximum Element
Finding Maximum Element. Write a Python function to find the maximum element in a list. List of no is [ 10 , 5 , 20 , 3, 2, 8, 20 , 2]. If the list is empty it should return None. Create function with name find_max_element answer for this in code in simple way.
def find_max_element(lst):
if not lst:
return None
else:
max_element = max(lst)
return max_element
# Example
numbers = [10, 5, 20, 3, 2, 8, 20, 2]
max_num = find_max_element(numbers)
print(max_num)Python Practice set — 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 calculator(num1, operator, num2):
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
return num1 / num2
else:
return "Enter a valid Input...."
# Example
a = int(input("enter the first operand:"))
b = int(input("enter the second operand:"))
op = input("enter the operation you want to perform:")
print(calculator(a, op, b))Question 2: File Manipulation
Write a Python script to read a text file, count the occurrences of each word, and display the result.
def count_word_occurrences(file_path):
word_counts = {}
with open(file_path, 'r') as file:
for line in file:
words = line.split()
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1
return word_counts
# Example
file_path = 'delete_after_usage.txt'
word_occurrences = count_word_occurrences(file_path)
print(word_occurrences)Get Shyam Kumar Khatri’s stories in your inbox
Join Medium for free to get updates from this writer.
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):
words = sentence.split()
return len(words)
# Example
input_sentence = "Counting Words in a Sentence"
number_of_words = count_words(input_sentence)
print(number_of_words)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():
correct_username = "user123"
correct_password = "password123"
input_username = input("Enter your username: ")
input_password = input("Enter your password: ")
if input_username == correct_username and input_password == correct_password:
print("Authentication successful! Welcome,", input_username)
else:
print("Authentication failed. Incorrect username or password.")
authenticate_user()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(date1, date2):
date_format = "%Y-%m-%d"
date1 = datetime.strptime(date1, date_format)
date2 = datetime.strptime(date2, date_format)
difference = abs((date2 - date1).days)
return difference
# Example
date1 = "2024-01-01"
date2 = "2024-01-05"
difference_days = date_difference(date1, date2)
print(difference_days)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):
words = sentence.split()
reversed_sentence = ' '.join(reversed(words))
return reversed_sentence
# Example
sentence = "Write a Python function that takes a sentence as input and returns the sentence with reversed words"
reversed_sentence = reverse_words(sentence)
print(reversed_sentence)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):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))
return password
# Example
random_password = generate_random_password(12)
print(random_password)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):
pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
return re.match(pattern, email) is not None
# Example
email_input = input("Enter an email address: ")
if is_valid_email(email_input):
print("Valid email address.")
else:
print("Invalid email address.")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
# Example
temperature_celsius = 25
temperature_fahrenheit = celsius_to_fahrenheit(temperature_celsius)
print(f"{temperature_celsius} Celsius is {temperature_fahrenheit:.2f} Fahrenheit.")Question 10: Social Media Post Analyzer
Create a Python script that analyses a given social media post. It could count the number of words, find hashtags, or determine the sentiment.
def analyze_social_media_post(post):
word_count = len(post.split())
hashtags = [word for word in post.split() if word.startswith('#')]
sentiment_analysis = "Positive" # Placeholder, you can use a library for sentiment analysis
return {
'word_count': word_count,
'hashtags': hashtags,
'sentiment_analysis': sentiment_analysis
}
# Example
social_media_post = "Create a Python script that analyzes a given social media post. #Python #DataScience"
analysis_result = analyze_social_media_post(social_media_post)
print(analysis_result)




