0% found this document useful (0 votes)
2 views

FDS Week 2 Practical

The document contains a series of Python programming exercises, including scripts for printing prime numbers, calculating factorials using recursion, checking for right triangles, and working with Fibonacci numbers. It also includes programs for copying file contents and extracting unique words from a text file. Each exercise is accompanied by code examples and expected outputs.

Uploaded by

Sayee Bankhele
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

FDS Week 2 Practical

The document contains a series of Python programming exercises, including scripts for printing prime numbers, calculating factorials using recursion, checking for right triangles, and working with Fibonacci numbers. It also includes programs for copying file contents and extracting unique words from a text file. Each exercise is accompanied by code examples and expected outputs.

Uploaded by

Sayee Bankhele
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

FDS Week 2 Practical

1. Write a Python script that prints prime numbers less than 20.

Program:

def is_prime(num):

"""Check if a number is prime."""

if num <= 1:

return False

for i in range(2, int(num**0.5) + 1):

if num % i == 0:

return False

return True

def print_primes_less_than_n(n):

"""Print all prime numbers less than n."""

for num in range(n):

if is_prime(num):

print(num)

# Print prime numbers less than 20

print_primes_less_than_n(20)

output:
2. Write a python program to find factorial of a number using Recursion.

Program:

def factorial(n):

"""Calculate the factorial of a number using recursion."""

if n < 0:

return "Factorial is not defined for negative numbers."

elif n == 0 or n == 1:

return 1

else:

return n * factorial(n - 1)

# Input from the user

number = int(input("Enter a number to find its factorial: "))

result = factorial(number)

# Display the result

print(f"The factorial of {number} is: {result}")

Output:

Enter a number to find its factorial: 7

The factorial of 7 is: 5040

3. Write a program that accepts the lengths of three sides of a triangle as inputs. The program

output should indicate whether or not the triangle is a right triangle (Recall from the

Pythagorean Theorem that in a right triangle, the square of one side equals the sum of the
squares of the other two sides).

Program:

def is_right_triangle(a, b, c):

"""Check if the triangle with sides a, b, and c is a right triangle."""

# Sort the sides to identify the longest side

sides = sorted([a, b, c])

# Check the Pythagorean theorem

return sides[2]**2 == sides[0]**2 + sides[1]**2

# Input from the user

try:

side1 = float(input("Enter the length of the first side: "))

side2 = float(input("Enter the length of the second side: "))

side3 = float(input("Enter the length of the third side: "))

# Check if it's a right triangle

if is_right_triangle(side1, side2, side3):

print("The triangle with sides {:.2f}, {:.2f}, and {:.2f} is a right triangle.".format(side1,
side2, side3))

else:

print("The triangle with sides {:.2f}, {:.2f}, and {:.2f} is not a right triangle.".format(side1,
side2, side3))

except ValueError:

print("Please enter valid numerical values for the lengths of the sides.")

Output:
4. Write a python program to define a module to find Fibonacci Numbers and import the module

to another program.

Program:

# fibonacci.py

def fibonacci(n):

"""Return the nth Fibonacci number."""

if n < 0:

raise ValueError("Input cannot be negative.")

elif n == 0:

return 0

elif n == 1:

return 1

else:

a, b = 0, 1

for _ in range(2, n + 1):

a, b = b, a + b

return b

def fibonacci_sequence(n):

"""Return a list of Fibonacci numbers up to the nth number."""

if n < 0:

raise ValueError("Input cannot be negative.")

sequence = []

for i in range(n):

sequence.append(fibonacci(i))

return sequence

Output:
5. Write a python program to define a module and import a specific function in that module to

another program.

Program:

def square(num):

"""Return the square of a number."""

return num ** 2

# main.py

from math_operations import square

def main():

try:

number = float(input("Enter a number to find its square: "))

# Calculate the square using the imported function

result = square(number)

print(f"The square of {number} is: {result}")

except ValueError:

print("Please enter a valid number.")

if __name__ == "__main__":

main()

Output:
6. Write a script named copyfile.py. This script should prompt the user for the names of two text

files. The contents of the first file should be input and written to the second file.

Program:

def copy_file_contents():
"""Copy contents from one file to another."""
# Prompt the user for the names of the files
source_file = input("Enter the name of the source file (including .txt): ")
destination_file = input("Enter the name of the destination file (including .txt): ")

try:
# Open the source file for reading
with open(source_file, 'r') as src:
contents = src.read() # Read the contents of the source file

# Open the destination file for writing


with open(destination_file, 'w') as dest:
dest.write(contents) # Write the contents to the destination file

print(f"Contents copied from {source_file} to {destination_file} successfully.")

except FileNotFoundError:
print(f"Error: The file '{source_file}' does not exist.")
except Exception as e:
print(f"An error occurred: {e}")

if __name__ == "__main__":
copy_file_contents()

Output:
7. Write a program that inputs a text file. The program should print all of the unique words in

the file in alphabetical order.

Program:

def extract_unique_words(file_name):

"""Extract unique words from a text file and return them in alphabetical order."""

try:

with open(file_name, 'r') as file:

# Read the contents of the file

contents = file.read()

# Split the contents into words, removing punctuation and converting to lowercase

words = contents.split()

unique_words = set(word.strip('.,!?()[]{}"\'').lower() for word in words)

# Sort the unique words alphabetically

sorted_unique_words = sorted(unique_words)

return sorted_unique_words

except FileNotFoundError:

print(f"Error: The file '{file_name}' does not exist.")

return []

except Exception as e:

print(f"An error occurred: {e}")

return []

def main():

# Input from the user for the text file name

file_name = input("Enter the name of the text file (including .txt): ")

# Extract unique words and print them


unique_words = extract_unique_words(file_name)

if unique_words:

print("Unique words in alphabetical order:")

for word in unique_words:

print(word)

if __name__ == "__main__":

main()

Output:

Enter the name of the text file (including .txt): sayee.txt

Unique words in alphabetical order:

again

hello

is

test

this

world

You might also like