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

Python Codes

The document contains 8 code snippets that perform various tasks related to strings, lists, exceptions, and functions in Python. The snippets include programs to find roots of a quadratic equation, check if a number is prime, generate pyramids of characters, analyze characters, perform string operations, swap string characters, create lists by filtering other lists, and validate user input with exceptions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Python Codes

The document contains 8 code snippets that perform various tasks related to strings, lists, exceptions, and functions in Python. The snippets include programs to find roots of a quadratic equation, check if a number is prime, generate pyramids of characters, analyze characters, perform string operations, swap string characters, create lists by filtering other lists, and validate user input with exceptions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

1. WAP to find the roots (real, complex) of a quadratic equation.

import cmath # Importing the complex math module

def find_roots(a, b, c):

# Calculate the discriminant

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

# Check if the discriminant is positive, negative, or zero

if discriminant > 0:

# Real and distinct roots

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

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

return root1, root2

elif discriminant == 0:

# Real and equal roots

root = -b / (2 * a)

return root,

else:

# Complex roots

root1 = (-b + cmath.sqrt(discriminant)) / (2 * a)

root2 = (-b - cmath.sqrt(discriminant)) / (2 * a)

return root1, root2

# Input coefficients from the user

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

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

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

# Call the function and print the roots


roots = find_roots(a, b, c)

print("Roots:", roots)

2. WAP to accept a number ‘n’ and

(a) Check if ’n’ is prime


(b) Generate all prime numbers till ‘n’
(c) Generate first ‘n’ prime numbers
(d) This program may be done using functions.

# Define a function to check if a number is prime


def is_prime(num):
"""Check if a number is prime."""
if num < 2: # If the number is less than 2, it's not prime
return False
for i in range(2, int(num**0.5) + 1): # Check divisibility up to the square root
of the number
if num % i == 0: # If the number is divisible by any i, it's not prime
return False
return True # If no divisors are found, the number is prime

# Define a function to generate all prime numbers up to a given number


def generate_primes_up_to_n(n):
"""Generate all prime numbers up to 'n'."""
primes = [num for num in range(2, n + 1) if is_prime(num)] # Use the
is_prime function to filter prime numbers
return primes

# Define a function to generate the first 'n' prime numbers


def generate_first_n_primes(n):
"""Generate the first 'n' prime numbers."""
primes = [] # Initialize an empty list to store prime numbers
num = 2 # Start checking for primes from 2
while len(primes) < n: # Continue until the desired number of primes are
found
if is_prime(num): # If the current number is prime
primes.append(num) # Add it to the list of primes
num += 1 # Move on to the next number
return primes # Return the list of first 'n' prime numbers

# Accept a number 'n' from the user


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

# (a) Check if 'n' is prime


if is_prime(n):
print(f"{n} is a prime number.")
else:
print(f"{n} is not a prime number.")

# (b) Generate all prime numbers till 'n'


primes_up_to_n = generate_primes_up_to_n(n)
print(f"Prime numbers up to {n}: {primes_up_to_n}")

# (c) Generate first 'n' prime numbers


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

3. WAP to create a pyramid of the character ‘*’ and a reverse pyramid

def create_pyramid(height):

"""Create a pyramid of '*' with the given height."""

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

print(' ' * (height - i) + '*' * (2 * i - 1))

def create_reverse_pyramid(height):

"""Create a reverse pyramid of '*' with the given height."""

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

print(' ' * (height - i) + '*' * (2 * i - 1))

# Accept the height of the pyramids from the user

height = int(input("Enter the height of the pyramids: "))


# Create and print the pyramid

print("Pyramid:")

create_pyramid(height)

# Create and print the reverse pyramid

print("\nReverse Pyramid:")

create_reverse_pyramid(height)

4. WAP that accepts a character and performs the following:

(a) print whether the character is a letter or numeric digit or a


special character (b) if the character is a letter, print whether the
letter is uppercase or lowercase

# Accept a character from the user

char = input("Enter a character: ")

# (a) Check whether the character is a letter, numeric digit, or a special


character

if char.isalpha():

if char.isupper():

print(f"{char} is an uppercase letter.")

elif char.islower():

print(f"{char} is a lowercase letter.")

else:

if char.isdigit():

print(f"{char} is a numeric digit.")

else:

print(f"{char} is a special character.")


# (b) If the character is a letter, print whether it is uppercase or lowercase

5. WAP to perform the following operations on a string

(a) Find the frequency of a character in a string.


(b) Replace a character by another character in a string.
(c) Remove the first occurrence of a character from a string.
(d) Remove all occurrences of a character from a string

def find_frequency(char, string):

"""Find the frequency of a character in a string."""

frequency = string.count(char)

return frequency

def replace_character(old_char, new_char, string):

"""Replace a character by another character in a string."""

new_string = string.replace(old_char, new_char)

return new_string

def remove_first_occurrence(char, string):

"""Remove the first occurrence of a character from a string."""

index = string.find(char)

if index != -1:

new_string = string[:index] + string[index + 1:]

return new_string

else:

return string

def remove_all_occurrences(char, string):

"""Remove all occurrences of a character from a string."""


new_string = string.replace(char, '')

return new_string

# Accept a string from the user

input_string = input("Enter a string: ")

# (a) Find the frequency of a character in a string

char_to_find = input("Enter the character to find its frequency: ")

frequency = find_frequency(char_to_find, input_string)

print(f"The frequency of '{char_to_find}' in the string is: {frequency}")

# (b) Replace a character by another character in a string

old_char = input("Enter the character to replace: ")

new_char = input("Enter the character to replace it with: ")

string_after_replace = replace_character(old_char, new_char, input_string)

print(f"The string after replacement is: {string_after_replace}")

# (c) Remove the first occurrence of a character from a string

char_to_remove_first = input("Enter the character to remove the first occurrence:


")

string_after_remove_first = remove_first_occurrence(char_to_remove_first,
input_string)

print(f"The string after removing the first occurrence of '{char_to_remove_first}' is:


{string_after_remove_first}")

# (d) Remove all occurrences of a character from a string

char_to_remove_all = input("Enter the character to remove all occurrences: ")

string_after_remove_all = remove_all_occurrences(char_to_remove_all,
input_string)

print(f"The string after removing all occurrences of '{char_to_remove_all}' is:


{string_after_remove_all}")
6. WAP to swap the first n characters of two strings.

def swap_first_n_characters(str1, str2, n):

"""Swap the first 'n' characters of two strings."""

if n <= min(len(str1), len(str2)):

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

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

return new_str1, new_str2

else:

return "Invalid input: 'n' is greater than the length of one or both strings."

# Accept two strings from the user

string1 = input("Enter the first string: ")

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

# Accept the value of 'n'

n = int(input("Enter the value of 'n' for swapping: "))

# Swap the first 'n' characters of the two strings

result = swap_first_n_characters(string1, string2, n)

# Print the result

print("Result after swapping first", n, "characters:")

if isinstance(result, tuple):

print("String 1:", result[0])

print("String 2:", result[1])

else:
print(result)

7. WAP to create a list of the cubes of only the even integers appearing in the
input list (may have elements of other types also) using the ’for’ loop

def cube_of_even_integers(input_list):

"""Create a list of cubes of even integers from the input list."""

result_list = []

for element in input_list:

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

result_list.append(element**3)

return result_list

# Accept a list from the user (may have elements of other types)

input_list = eval(input("Enter a list (may have elements of other types): "))

# Create a list of cubes of even integers using a 'for' loop

result = cube_of_even_integers(input_list)

# Print the result

print("List of cubes of even integers:", result)

8. WAP to accept a name from a user. Raise and handle appropriate


exception(s) if the text entered by the user contains digits and/or special
characters

def validate_name(name):

"""Validate the entered name and raise exceptions if needed."""

for char in name:

if not char.isalpha() and char != ' ':


raise ValueError("Invalid character in the name. Only alphabets and spaces are
allowed.")

# Accept a name from the user

try:

user_name = input("Enter your name: ")

# Validate the entered name

validate_name(user_name)

# If the validation passes, print the name

print("Entered name:", user_name)

except ValueError as e:

# Handle the exception by printing the error message

print("Error:", e)

You might also like