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):
return input_string[::-1]
# Example usage
original_string = "I am learning Python"
reversed_string = reverse_string(original_string)
print(reversed_string)
Output Screenshot:
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):
"""Check if a number is prime."""
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):
"""Generate a list of prime numbers up to n."""
prime_list = [num for num in range(2, n+1) if is_prime(num)]
return prime_list
# Example usage:
n = 20
prime_numbers = generate_prime(n)
print(f"Prime numbers up to {n}: {prime_numbers}")
Output Screenshot:
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):
"""Calculate the factorial of a given non-negative integer."""
if n == 0 or n == 1:
return 1
else:
result = 1
for i in range(2, n + 1):
result *= i
return result
# Example usage:
num = 5
result_factorial = factorial(num)
print(f"The factorial of {num} is: {result_factorial}")
Output Screenshot:
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):
"""Count the number of words in a given sentence."""
words = sentence.split()
return len(words)
# Example usage:
input_sentence = "Write a Python function to count the number of words in a given sentence."
word_count = count_words(input_sentence)
print(f"The number of words in the sentence is: {word_count}")
Output Screenshot:
Question 5: Finding Maximum Element
Finding Maximum Element. Write a Python function to find the maximum element in a list. The list of no is [ 10, 5, 20, 3, 2, 8, 20, 2] If the list is empty it should return None. Create a function with the name find_max_element answer for this in code in a simple way.
def find_max_element(lst):
"""Find the maximum element in a given list."""
if not lst:
return None
else:
max_element = lst[0]
for element in lst:
if element > max_element:
max_element = element
return max_element
# Example usage:
number_list = [10, 5, 20, 3, 2, 8, 20, 2]
max_value = find_max_element(number_list)
print(f"The maximum element in the list is: {max_value}")