Python File.
Python File.
UNIVERSITY OF DELHI
PROGRAMME: PYTHON
COURSE: B.A. IN COMPUTER APPLICATIONS
SEMESTER: 1
NAME: Anshu
SOL ROLL NO: 24-1-11-000207
INDEX
S.No. EXPERIMENT DATE SING.
1. WAP TO SWAP 2 NUMBERS WITHOUT USING ANOTHER VARIABLE.
ARITHMETIC ERROR.
EXCEPTION IF THERE IS AN
ARITHMETIC ERROR.
28. WAP TO PRINT THE REVERSE NUMBER PATTERN USING A FOR LOOP.
PROGRAM :-
a = 10
b = 20
print("a=",a,"b=",b,)
a,b=b,a
print("a=",a,"b=",b,)
OUTPUT
EXPERIMENT:- 2
AIM :- WAP TO CONCATINATE STRINGS
PROGRAM :-
str1 = "good "
str2 = "morning"
print(str1+str2)
str3 = "hello"
str4 = "world"
print(str3+str4)
OUTPUT
EXPERIMENT:- 3
AIM :- : WAP TO CALCULATE AREA OF CIRCLE
PROGRAM :-
OUTPUT
EXPERIMENT:- 4
AIM :- : WAP TO CALCULATE SQUARE OF A NUMBER
PROGRAM :-
s= float(input("enter a nunber: "))
n=s*s
print("square of nuber: ",n)
OUTPUT
EXPERIMENT:- 5
AIM :- : WAP TO PRINT VALUE OF PI
PROGRAM :-
import math
print("PI="math.pi )
OUTPUT
EXPERIMENT:- 6
AIM :- WAP TO TAKE INPUT FROM USER AND USE ARITHMETIC OPERATORS
PROGRAM :-
#write a program to show arithmetic operations.
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
print("addition:", num1 + num2 )
print("subtraction :", num1 - num2 )
print("multiplication :", num1 * num2 )
print("division :", num1 / num2 )
OUTPUT
EXPERIMENT:- 7
AIM :- : WAP THAT CALCULATES CIRCUMFERENCE OF A CIRCLE BASED ON THE RADIUS ENTERED BY USER
PROGRAM :-
import math
radius = float(input("Enter the radius of a circle: "))
circumference = 2 * (math.pi) * radius
print("The circumference of the circle is:", circumference)
OUTPUT
EXPERIMENT:- 8
AIM :- : WAP TO TAKE MARKS OF FIVE SUBJECTS FROM THE USER ,FIND TOTAL AND PERCENTAGE .PRINT GRADE
ALSO .
If marks greater than equal to 90 : Grade A+
If marks greater than equal to 80 but less than 90 : Grade A
If marks greater than equal to 70 but less than 80 : Grade B+
If marks greater than equal to 60 but less than 70 : Grade B
If marks greater than equal to 50 but less than 60 : Grade C
If marks greater than equal to 40 but less than 50 : Grade D
If marks less than 40: Grade F
PROGRAM :-
marks1 = float(input("Enter marks for Subject 1: ")) ; marks2 = float(input("Enter marks for Subject 2: "))
marks3 = float(input("Enter marks for Subject 3: ")) ; marks4 = float(input("Enter marks for Subject 4: "))
marks5 = float(input("Enter marks for Subject 5: ")) ; total_marks = marks1 + marks2 + marks3 + marks4 + marks5
grade = 'A+’
grade = 'A'
PROGRAM :-
def check_triangle_type(a, b, c):
# Check if the three sides can form a triangle
if a + b > c and a + c > b and b + c > a:
# Check if it's an equilateral triangle
if a == b == c:
return "Equilateral Triangle"
# Check if it's an isosceles triangle
elif a == b or b == c or a == c:
return "Isosceles Triangle"
# Check if it's a right triangle (Pythagorean theorem)
elif a**2 + b**2 == c**2 or b**2 + c**2 == a**2 or a**2 + c**2 == b**2:
return "Right Triangle"
# If none of the above, it's a scalene triangle
else:
return "Scalene Triangle"
else:
return "Not a valid triangle"
PROGRAM :-
# Input from the user
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
# Print the names in reverse order
print(last_name + " " + first_name)
OUTPUT
EXPERIMENT:- 11
AIM :- WAP TO CHECK WHETHER A NUMBER IS EVEN OR ODD.
PROGRAM :-
# Input from the user
number = int(input("Enter a number: "))
# Check if the number is even or odd
if number % 2 == 0:
print(f"{number} is an Even number.")
else:
print(f"{number} is an Odd number.")
OUTPUT
EXPERIMENT:- 12
AIM :- WAP TO CHECK WHETHER A NUMBER IS DIVISIBLE BY 13 OR NOT.
PROGRAM :-
# Input from the user
number = int(input("Enter a number: "))
PROGRAM :-
def print_multiples_of_21():
for i in range(1, 51):
print(f"{i} * 21 = {i * 21}")
OUTPUT
print_multiples_of_21()
EXPERIMENT:- 15
AIM :- WAP TO PRINT SQUARES OF FIRST 20 NUMBERS.
PROGRAM :-
def print_square_of_numbers():
for i in range(1, 21):
print(f"square of {i} = {i ** 2}")
print_square_of_numbers() OUTPUT
EXPERIMENT:- 16
AIM :- WAP TO PRINT CUBE OF FIRST 30 NUMBERS.
PROGRAM :-
def print_cube_of_numbers():
for i in range(1, 31):
print(f"cube of {i} = {i ** 3}")
print_cube_of_numbers()
OUTPUT :
EXPERIMENT:- 17
AIM :- WAP TO PRINT THE PATTERN OF PYRAMID
PROGRAM :-
PART : A
def print_pyramid(rows):
# Print spaces
# Print stars
OUTPUT
print("*" * (2 * i - 1))
print_pyramid(rows)
PART : B
rows = int(input("Enter numbers of rows: "))
k=1
alpha = 65
for i in range (1,rows + 1):
for space in range(1,(rows-i)+1):
print(end=" ")
while k<=(2*i-1):
print(chr(alpha),end=" ")
k += 1 OUTPUT
alpha+=1
k=1
alpha=65
print()
EXPERIMENT:- 18
AIM :- WAP TO FIND THE SUM OF THE SERIES.
1+2+3+4+……+n
PROGRAM :-
# Function to calculate the sum of the series
def sum_of_series(n):
return n * (n + 1) // 2
result = sum_of_series(n)
OUTPUT
EXPERIMENT:- 19
AIM :- WAP TO FIND THE SUM OF THE SERIES.
1/1!+2/2!+3/3!+4/4!+…….+n/n!
PROGRAM :-
# Function to calculate factorial of a number
def factorial(num):
if num == 0 or num == 1:
return 1
else:
result = 1
for i in range(2, num + 1):
result *= i
return result
# Function to calculate the sum of the series
def sum_of_series(n):
total_sum = 0
for i in range(1, n + 1):
total_sum += i / factorial(i)
return total_sum
# Input from the user
n = int(input("Enter the value of n: "))
# Calculate the sum and display the result
result = sum_of_series(n)
print("The sum of the series 1/1! + 2/2! + 3/3! + ... +", n, "/", n, "!", "is:", result)
OUTPUT
EXPERIMENT:- 20
AIM :- WAP TO FIND THE SUM OF THE SERIES.
1-2+3-4+5-6+7-8+…..+n
PROGRAM :-
# Function to calculate the sum of the series
def sum_of_series(n):
total_sum = 0
for i in range(1, n + 1):
# If the term is odd, add it; if even, subtract it
if i % 2 == 0:
total_sum -= i OUTPUT
else:
total_sum += i
return total_sum
# Input from the user
n = int(input("Enter the value of n: "))
# Calculate the sum and display the result
result = sum_of_series(n)
print("The sum of the series 1 - 2 + 3 - 4 + ... +", n, "is:", result
EXPERIMENT:- 21
AIM :- CREATE A PROGRAM THAT ALLOWS THE USER TO GUESS A SECRET NUMBER BETWEEN 1 TO 100. THE PROGRAM SH0ULD KEEP PROMPTING THE USER UNTIL THEY GUESS THE
CORRECT NUMBER.
PROGRAM :-
# Generate a random secret number between 1 and 100
secret_number = random.randint(1, 100)
print("Welcome to the Guessing Game!")
print("I have chosen a number between 1 and 100. Can you guess what it is?")
# Initialize the user's guess to None
guess = None
# Loop until the user guesses the correct number
while guess != secret_number:
# Get user input and convert it to an integer
guess = int(input("Enter your guess: "))
# Check if the guess is too low, too high, or correct
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print("Congratulations! You've guessed the
correct number:", secret_number)
OUTPUT
EXPERIMENT:- 22
AIM :- WAP TO GENERATE THE FIBONACCI SEQUENCE UP TO A GIVEN NUMBER OF TERMS.
PROGRAM :-
OUTPUT
EXPERIMENT:- 23
AIM :- CREATE A PROGRAM THAT ALLOWS TWO PLAYERS TO PLAY A GAME OF ROCK,PAPER, SCISSORS.
PROGRAM :-
# Function to determine the winner
def determine_winner(player1_choice, player2_choice):
if player1_choice == player2_choice:
return "It's a tie!"
elif (player1_choice == "rock" and player2_choice == "scissors") or \
(player1_choice == "scissors" and player2_choice == "paper") or \
(player1_choice == "paper" and player2_choice == "rock"):
return "Player 1 wins!"
else:
return "Player 2 wins!"
# Instructions
print("Welcome to Rock, Paper, Scissors!")
print("Choices: rock, paper, scissors")
# Player 1's choice
player1_choice = input("Player 1, enter your choice: ").lower()
# Player 2's choice
player2_choice = input("Player 2, enter your choice: ").lower()
# Check if inputs are valid
valid_choices = ["rock", "paper", "scissors"]
if player1_choice not in valid_choices or player2_choice not in valid_choices:
print("Invalid input. Please choose rock, paper, or scissors.")
else:
# Determine and display the winner
result = determine_winner(player1_choice, player2_choice)
print(result) OUTPUT
EXPERIMENT:- 24
AIM :- WAP TO HANDLE DIVISION BY ZERO, VALUE ERROR AND NAME ERROR USING TRY EXCEPT ELSE FINALLY BLOCK.
PROGRAM :-
# Prompt the user to enter two numbers
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
# Attempt division
result = num1 / num2
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Invalid input. Please enter a valid integer.")
except NameError:
OUTPUT
print("Error: A variable is not defined.")
else:
# This block runs if there were no exceptions
print("The result of the division is:", result)
EXPERIMENT:- 25
AIM :- WAP THAT OPENS A FILE HANDLES A FILENOTFOUNDERROR EXCEPTION IF THE FILE DOES NOT EXIST.
PROGRAM :-
# Prompt the user to enter the filename
filename = input("Enter the filename to open: ")
try:
# Attempt to open the file in read mode
with open(filename, 'r') as file:
# Read and display the content of the file OUTPUT
content = file.read()
print("File content:")
print(content)
except FileNotFoundError:
# Handle the case where the file does not exist
print("Error: The file", filename, "was not found. Please check the filename and try again.")
EXPERIMENT:- 26
AIM :- WAP THAT EXECUTES AN OPERATION ON A LIST AND HANDLES AN INDEXERROR EXCEPTION IF THE INDEX IS OUT OF RANGE.
PROGRAM :-
# Sample list
my_list = [10, 20, 30, 40, 50]
# Display the list to the user
print("The list is:", my_list)
try:
# Prompt the user to enter an index
index = int(input("Enter the index of the element you want to access: "))
# Attempt to access the list element at the given index
element = my_list[index]
# Display the element
print("Element at index", index, "is:", element)
except IndexError:
# Handle the case where the index is out of range
print("Error: The index is out of range. Please enter an index between 0 and", len(my_list) - 1)
except ValueError:
# Handle the case where the input is not an integer
print("Error: Please enter a valid integer for the index.")
OUTPUT
EXPERIMENT:- 27
AIM :- WAP THAT EXECUTES DIVISION AND HANDLES AN ARITHMETIC ERROR.EXCEPTION IF THERE IS AN ARITHMETIC ERROR.
PROGRAM :-
try:
# Prompt the user to enter two numbers
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
# Attempt to perform division
result = numerator / denominator
except ArithmeticError:
# Handle any arithmetic errors (like division by zero) OUTPUT
print("Error: An arithmetic error occurred. Division by zero is not allowed.")
else:
# If no exception, print the result
print("The result of the division is:", result)
EXPERIMENT:- 28
AIM :- WAP TO PRINT THE REVERSE NUMBER PATTERN USING A FOR LOOP.
54321
5432
543
54
5
PROGRAM :-
# Input from the user
n = int(input("Enter the number of rows: ")) OUTPUT
# Generate the reverse number pattern
for i in range(n, 0, -1):
for j in range(n, n - i, -1):
print(j, end=" ")
print()
EXPERIMENT:- 29
AIM :- WAP TO PRINT ALL PRIME NUMBER WITHIN A GIVEN RANGE.
PROGRAM :-
OUTPUT
EXPERIMENT:- 30
AIM :- WAP TO REVERSE ITS DIGIT .
PROGRAM :-
# Input from the user
num = int(input("Enter a number: ")
# Initialize a variable to store the reversed number
reversed_num = 0
# Process each digit
while num > 0:
# Get the last digit
digit = num % 10
# Append the digit to the reversed number
reversed_num = reversed_num * 10 + digit
OUTPUT
# Remove the last digit from the original number
num = num // 10
# Display the reversed number
print("Reversed number is:", reversed_num)