Python

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

Q1:

def find_roots(a, b, c):

d = b**2 - 4*a*c

if d >= 0:

root1 = (-b + (d ** 0.5)) / (2*a)

root2 = (-b - (d ** 0.5)) / (2*a)

return root1, root2

else:

return "No real roots"

a = float(input("Enter coefficient a: "))

b = float(input("Enter coefficient b: "))

c = float(input("Enter coefficient c: "))

roots = find_roots(a, b, c)

print("The roots are:", roots)

OUTPUT:
Q2:

def is_prime(num):

if num <= 1:

return False

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

if num % i == 0:

return False

return True

def primes_till_n(n):

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

if is_prime(i):

return [i]

def first_n_primes(n):

primes = []

num = 2

while len(primes) < n:

if is_prime(num):

primes.append(num)

num += 1

return primes

n = int(input("Enter a number 'n': "))

if is_prime(n):

print(n, "is a prime number.")

else:

print(n," is not a prime number.")

print("Prime numbers till ",n,primes_till_n(n))

print(f"First {n} prime numbers: {first_n_primes(n)}")

OUTPUT
Q3:

def pyramid(char, rows):

for i in range(1, rows + 1):

print(" " * (rows - i) + char * (2 * i - 1))

def reverse_pyramid(char, rows):

for i in range(rows, 0, -1):

print(" " * (rows - i) + char * (2 * i - 1))

char = input("Enter a character: ")

rows = int(input("Enter the number of rows: "))

print("\nPyramid:")

pyramid(char, rows)

print("\nReverse Pyramid:")

reverse_pyramid(char, rows)

OUTPUT

Q5:
string = input('enter a string:')

print("Original String:", string)

print("Frequency of 'g':", string.count('g'))

print("After replacing 'm' with 'x':", string.replace('m', 'x'))

print("After removing first 'r':", string.replace('r', '', 1))

print("After removing all 'r':", string.replace('r', ''))

OUTPUT:

Q6:
str1 = input("Enter the first string: ")

str2 = input("Enter the second string: ")

n = int(input("Enter the number of characters to swap: "))

if n > len(str1) or n > len(str2):

print("Error: 'n' is larger than the length of one of the strings.")

else:

str1, str2 = str2[:n] + str1[n:], str1[:n] + str2[n:]

print(f"After swapping:\nString 1: {str1}\nString 2: {str2}")

OUTPUT:

Q7:
def find_all_occurrences(main_str, sub_str):

indices = []

start = 0

while start < len(main_str):

start = main_str.find(sub_str, start)

if start == -1:

break

indices.append(start)

start += 1

return indices

main_str = input("Enter the main string: ")

sub_str = input("Enter the substring to find: ")

indices = find_all_occurrences(main_str, sub_str)

if indices:

print(f"The substring '{sub_str}' is found at indices: {indices}")

else:

print(f"The substring '{sub_str}' is not found in the main string.")

OUTPUT

Q8:

def cubes_of_even_integers(input_list):
even_cubes = []

for element in input_list:

if isinstance(element, int) and element % 2 == 0:

even_cubes.append(element ** 3)

return even_cubes

input_list = [1, 2, 'a', 4, 5.5, 6]

print(cubes_of_even_integers(input_list))

def cubes_of_even_integers(input_list):

return [element ** 3 for element in input_list if isinstance(element, int) and element % 2 == 0]

input_list = [1, 2, 'a', 4, 5.5, 6]

print(cubes_of_even_integers(input_list))

OUTPUT:

Q9:

def analyze_file(file_name):
try:

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

text = file.read()

total_chars = len(text)

total_words = len(text.split())

total_lines = len(text.split('\n')

print(f"Total Characters: {total_chars}")

print(f"Total Words: {total_words}")

print(f"Total Lines: {total_lines}")

char_frequency = {}

for char in text:

if char in char_frequency:

char_frequency[char] += 1

else:

char_frequency[char] = 1

print("\nCharacter Frequency:")

for char, frequency in char_frequency.items():

print(f"{char}: {frequency}")

except FileNotFoundError:

print(f"File '{file_name}' not found.")

analyze_file('example.txt')

Q10:

class Point:
def __init__(self, x, y):

self.x = x

self.y = y

def distance(self, other):

return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5

p1 = Point(1, 2)

p2 = Point(4, 6)

print(p1.distance(p2))

OUTPUT:

Q11:

def print_cube_dict(n):

cube_dict = {i: i**3 for i in range(1, n+1)}

print(cube_dict)

print_cube_dict(5)

OUTPUT:

Q12:

t1 = (1, 2, 5, 7, 9, 2, 4, 6, 8, 10)
print(t1[:5])

print(t1[5:])

print(tuple(i for i in t1 if i % 2 == 0))

t2 = (11, 13, 15)

print(t1 + t2)

print(max(t1 + t2))

print(min(t1 + t2))

OUTPUT:

Q13:

while True:

name = input("Enter your name: ")

if name.isalpha():

print("Hello,", name)

break

else:

print("Name cannot contain digits or special characters")

OUTPUT:

You might also like