0% found this document useful (0 votes)
10 views20 pages

PYTHONPDF.pdf.pdf

The document contains multiple Python programming tasks and their solutions. It covers various topics such as basic arithmetic operations, string manipulation, date formatting, list and dictionary operations, tuple handling, temperature conversion, factorial calculation, triangle validation, Fibonacci sequence, and printing patterns. Each task includes a description, code snippets, and expected outputs.

Uploaded by

udityaada
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views20 pages

PYTHONPDF.pdf.pdf

The document contains multiple Python programming tasks and their solutions. It covers various topics such as basic arithmetic operations, string manipulation, date formatting, list and dictionary operations, tuple handling, temperature conversion, factorial calculation, triangle validation, Fibonacci sequence, and printing patterns. Each task includes a description, code snippets, and expected outputs.

Uploaded by

udityaada
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

(Q.

1) Write a program to perform different operation on


number's of python ?
Answer :-
Function for addition def add(x, y): return x + y Function for subtraction

def subtract(x, y): return x - y Function for multiplication def multiply(x,

y): return x * y Function for division def divide(x, y): if y == 0: return

"Error! Division by zero." return x / y Function for modulus def

modulus(x, y): if y == 0: return "Error! Division by zero." return x % y

Function for exponentiation


def exponent(x, y): return x ** y

Function for exponentiation

def exponent(x, y): return x ** y Main program loop def main():

print("Select operation:") print("1. Add") print("2. Subtract")


print("3. Multiply") print("4. Divide") print("5. Modulus")
print("6. Exponent

while True:

# Take user input for operation


choice = input("Enter choice (1/2/3/4/5/6): ")

# Check if the choice is valid


if choice not in ['1', '2', '3', '4', '5', '6']:
print("Invalid Input. Please select a valid
operation.")
continue

# Take input for numbers


try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter numeric
values.")
continue

# Perform operation based on user's choice


if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}")
elif choice == '2':
print(f"{num1} - {num2} = {subtract(num1, num2)}")
elif choice == '3':
print(f"{num1} * {num2} = {multiply(num1, num2)}")
elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")
elif choice == '5':
print(f"{num1} % {num2} = {modulus(num1, num2)}")
elif choice == '6':
print(f"{num1} ^ {num2} = {exponent(num1, num2)}")

# Ask if the user wants to perform another operation


next_calculation = input("Do you want to perform
another operation? (yes/no): ")
if next_calculation.lower() != 'yes':
break

Run the main function

if name == "main": main()


(Q.2) write a Program to create concatenate $ Print a string.
Answer:-

Here is a Python program that creates, concatenates, and prints a


string:

Define two strings

str1 = "Hello, " str2 = "World!"

Concatenate the strings

str3 = str1 + str2


Print the concatenated string
print("Concatenated String: ", str3)

Create a new string using concatenation

str4 = "I am " + "learning " + "Python."

Print the new string

print("New String: ", str4)

Create a string using the format() method

name = "John" age = 30 str5 = "My name is {} and I am {} years


old.".format(name, age)
Print the formatted string

print("Formatted String: ", str5)

Create a string using f-strings (Python 3.6+)

str6 = f"My name is {name} and I am {age} years old."

Print the f-string

print("F-String: ", str6)


Q.3 write a Python script to print current date in the following

format "Sunday May 21"


Answer:-

from datetime import datetime

Get current date and time

current_date = datetime.now()

Format the current date as "DayOfWeek Month Day"

formatted_date = current_date.strftime("%A %B %d")

Print the formatted date

print(formatted_date)
(Q.4) WAP to Create, append & remove list in Python

Answer:-

# Function to append an item to the list def append_to_list(lst, item):


lst.append(item) print(f"Item '{item}' has been added to the list.")
Function to remove an item from the list

def remove_from_list(lst, item): if item in lst: lst.remove(item) print(f"Item


'{item}' has been removed from the list.") else: print(f"Item '{item}' not found
in the list.")

Main program

def main(): my_list = [] # Initialize an empty list


while True:
print("\nChoose an operation:") print("1.
Append item to list") print("2. Remove item
from list") print("3. Display the list")
print("4. Exit")
choice = input("Enter choice (1/2/3/4): ")

if choice == '1':

item = input("Enter the item to append: ")


append_to_list(my_list, item)

elif choice == '2':


item = input("Enter the item to remove: ")
remove_from_list(my_list, item)

elif choice == '3':


print("Current list:", my_list)

elif choice == '4':


print("Exiting program...")
break

else:
print("Invalid choice. Please choose a valid
option.")
Run the main program if name == "main":

main()
(Q.5) wap to demonstrate working ith tuple ?
answer :-

# Function to demonstrate basic tuple operations def


tuple_operations(): # Creating a tuple my_tuple = (10, 20, 30, 40, 50)
print("Original Tuple:", my_tuple)
(indexing)
print("\nAccessing elements:") print("Element at index

# Accessing elements of a tuple

0:", my_tuple[0]) print("Element at #i


t nFdierxs
e3l:e"m,
my_tuple[3]) ent
# Fourth element
# Negative indexing (accessing from the end)
print("\nNegative indexing:")
print("Element at index -1:", my_tuple[-1]) # Last element
print("Element at index -2:", my_tuple[-2]) # Second last
element

# Slicing the tuple


print("\nSlicing the tuple:")
print("Elements from index 1 to 3:", my_tuple[1:4]) #
Elements from index 1 to 3
# Concatenating two tuples
another_tuple = (60, 70)
concatenated_tuple = my_tuple + another_tuple
print("\nConcatenated Tuple:", concatenated_tuple)
# Repeating a tuple
repeated_tuple = my_tuple * 2
print("\nRepeated Tuple:", repeated_tuple) #

Checking if an element exists in a tuple


print("\nCheck if element exists:")
print("Is 20 in my_tuple?", 20 in my_tuple) # True
print("Is 100 in my_tuple?", 100 in my_tuple) # False
# Length of the tuple
print("\nLength of my_tuple:", len(my_tuple))
# Iterating through a tuple
print("\nIterating through the tuple:")
for item in my_tuple:

print(item, end=" ")


Main function to run the demonstration
def main(): tuple_operations()

Run the main function

if name == "main": main()


(Q.6) wap to demonstrate working with dictionaries in python

Answers:-

Choose an operation:

• Add item to dictionary


• Update item in dictionary
• Remove item from dictionary
• Display dictionary
• Exit Enter choice (1/2/3/4/5): 1 Enter the key to add: name Enter the
value for the key: Alice Added: name -> Alice

Choose an operation:

1. Add item to dictionary


2. Update item in dictionary
3. Remove item from dictionary
4. Display dictionary
5. Exit Enter choice (1/2/3/4/5): 4 Current dictionary: {'name': 'Alice'}

Choose an operation:

1. Add item to dictionary


2. Update item in dictionary
3. Remove item from dictionary
4. Display dictionary
5. Exit Enter choice (1/2/3/4/5): 2 Enter the key to update: name Enter the

new value for the key: Bob Updated: name -> Bob
Choose an operation:

1. Add item to dictionary


2. Update item in dictionary
3. Remove item from dictionary
4. Display dictionary
5. Exit Enter choice (1/2/3/4/5): 4 Current dictionary: {'name': 'Bob'}

Choose an operation:

1. Add item to dictionary


2. Update item in dictionary
3. Remove item from dictionary
4. Display dictionary
5. Exit Enter choice (1/2/3/4/5): 3 Enter the key to remove: name
Removed: name
Choose an operation:

1. Add item to dictionary


2. Update item in dictionary
3. Remove item from dictionary

4. Display dictionary
5. Exit Enter choice (1/2/3/4/5): 4 Current dictionary: {}

Choose an operation:

1. Add item to dictionary


2. Update item in dictionary
3. Remove item from dictionary
4. Display dictionary
5. Exit Enter choice (1/2/3/4/5): 5 Exiting program...
(Q.7) Wap to find largest of 3 numbers
Answer:-

Enter the first number: 10

Enter the second number: 20

Enter the third number: 15

The largest number is: 20.0


(Q.8) wap to convert temperature to $ from Celsius
Fahrenheit c/s =f-32/9
Answer :-

# Function to convert Fahrenheit to Celsius def


fahrenheit_to_celsius(fahrenheit): celsius = (fahrenheit - 32) * 5/9 return
celsius
Main program def main(): # Taking input for temperature in Fahrenheit

fahrenheit =
float(input("Enter temperature in Fahrenheit: "))

# Converting Fahrenheit to Celsius celsius =

fahrenheit_to_celsius(fahrenheit)

# Displaying the result


print(f"{fahrenheit}° Fahrenheit is equal to {celsius:.2f}°
Celsius.")

Running the main function

if name == "main": main()


(Q.9) wap of a class to convert an integer to a roman
numeral ?
Answer:-

class RomanConverter: def init(self, number): self.number = number


# Method to convert integer to Roman numeral
def to_roman(self):
# Roman numeral mappings for various values
val = [
1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4,
1
]
syb = [
"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X",
"IX", "V", "IV", "I"
]
# Initialize result string
roman_numeral = ''
num = self.number

# Loop through the values and symbols to build the

Roman numeral

for i in range(len(val)):
# Determine how many times the Roman symbol fits
into the number
while num >= val[i]:
roman_numeral += syb[i]
num -= val[i]
return roman_numeral
Main program

def main(): # Take input for an integer number = int(input("Enter an integer to


convert to Roman numeral: "))

# Create an instance of RomanConverter


converter = RomanConverter(number)
# Get the Roman numeral
roman = converter.to_roman()
# Display the result
print(f"The Roman numeral for {number} is {roman}.")

Run the main function

if name == "main": main()


(Q.10) write a python script that print numbers less than 20
Answer:-

# Python script to print numbers less than 20 def


print_numbers_less_than_20(): for number in range(20): print(number)
Calling the function to print numbers less than 20

print_numbers_less_than_20()

output:- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
(Q.11)wap to find factorial of a number using recursion
Answer:-

# Function to find the factorial of a number using recursion def factorial(n): #


Base case: if n is 0 or 1, return 1 if n == 0 or n == 1: return 1 # Recursive
case: n * factorial of (n-1) else: return n * factorial(n - 1)

Main program def main(): # Taking input from the user number =

int(input("Enter a number
find its factorial: "))
# Finding the factorial using the recursive function result
= factorial(number)
# Displaying the result
print(f"The factorial of {number} is {result}.")

Running the main function

if name == "main": main()output :- Enter a number to find its factorial: 5 The


factorial of 5 is 120.
(Q.12) wap to accept the lengths of 3 sides of triangle as I/p
the program o/p should indicate whether or not the triangle
is right triangle
Answer : - # Function to check if the triangle is a right triangle def

is_right_triangle(a, b,

=c) : # Sort the sides to ensure the largest is treated as the hypotenuse sides
sorted([a, b, c])
# Check if the sum of squares of the two smaller sides
equals the square of the largest side
if sides[0]**2 + sides[1]**2 == sides[2]**2:
return True
else:
return False

Main program

def main(): # Accept the lengths of the three sides of the triangle a =
float(input("Enter the length of side a: ")) b = float(input("Enter the length of
side b: ")) c = float(input("Enter the length of side c: "))

# Check if the triangle is a right triangle


if is_right_triangle(a, b, c):
print("The triangle is a right triangle.")
else:
print("The triangle is not a right triangle.")

Run the main function

if name == "main": main()

output: - Enter the length of side a: 3 Enter the length of side b: 4 Enter the
length of side c: 5 The triangle is a right triangle.
Enter the length of side a: 6 Enter the length of side b: 8 Enter the length of
side c: 10 The triangle is a right triangle.
Enter the length of side a: 2 Enter the length of side b: 3 Enter the length of
side c: 4 The triangle is not a right triangle.
(Q.13) wap to define a module to find fibonacci number and
import the module to another program?
Answer :-

# Function to return the nth Fibonacci number def fibonacci(n): if n <= 0:


return "Input should be a positive integer" elif n == 1: return 0 # First
Fibonacci number is 0 elif n == 2: return 1 # Second Fibonacci number is 1
else: a, b = 0, 1 for _ in range(2, n): a, b = b, a + b return b
Importing the fibonacci module

import fibonacci_module

Main program to take user input and find the Fibonacci number

def main(): # Accepting the value of n from the user n = int(input("Enter the
position to find the Fibonacci number: "))
# Calling the fibonacci function from the fibonacci_module
result = fibonacci_module.fibonacci(n)
# Displaying the result
print(f"The {n}th Fibonacci number is: {result}")

Running the main function

if name == "main": main()


Example Output:Enter the position to find the Fibonacci number: 7 The 7th
Fibonacci number is: 8

(Q.14)*

**
***
****
*****
******
*******
********
*********
**********
Answer:- Function to print a right triangle pattern of asterisks def

print_asterisk_pattern(): # Loop through numbers 1 to 10 to create the


pattern for i in range(1, 11):
print('*' * i)
Calling the function to print the
pattern

You might also like