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

Python File.

Uploaded by

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

Python File.

Uploaded by

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

SCHOOL OF OPEN LEARNING

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.

2. WAP TO CONCATINATE STRINGS.

3. WAP TO CALCULATE AREA OF CIRCLE.

WAP TO CALCULATE SQUARE OF A NUMBER.


4.
5. WAP TO PRINT VALUE OF PI.

6. WAP TO TAKE INPUT FROM USER AND USE ARITHMETIC


OPERATORS.

7. WAP THAT CALCULATES CIRCUMFRENCE OF A CIRCLE BASED ON


THE RADIUS ENTERED BY USER .
INDEX
S.No. EXPERIMENT DATE SING.

WAP TO TAKE MARKS OF FIVE SUBJECTS FROM THE


8. USER ,FIND TOTAL AND PERCENTAGE .PRINT GRADE
ALSO .

S.No. EXPERIMENT DATE SING.


WAP TO TAKE MARKS OF FIVE
WAP TO TAKE THREE SIDES OF TRIANGLE AND FIND
9. SUBJECTS FROM THE USER ,FIND
WHETHER IT IS SCALENE,ISOSCELES,EQUILATERAL OR
TOTAL AND PERCENTAGE .PRINT
RIGHT TRIANGLE. 8. GRADE ALSO .
WAP TO TAKE THREE SIDES OF
TRIANGLE AND FIND WHETHER
IT IS
SCALENE,ISOSCELES,EQUILATERA
L OR RIGHT TRIANGLE.
WAP THAT ACCECPTS THE USER’S FIRST AND LAST
10. 9.
NAME AND PRINTS THEM IN REVERSE ORDER WITH A
WAP THAT ACCECPTS THE
SPACE BETWEEN THEM. USER’S FIRST AND LAST NAME
AND PRINTS THEM IN REVERSE
ORDER WITH A SPACE BETWEEN
10. THEM.
WAP TO CHECK WHETHER A
NUMBER IS EVEN OR ODD.
11.
WAP TO CHECK WHETHER A NUMBER IS EVEN OR ODD.
11.
WAP TO CHECK WHETHER A
NUMBER IS DIVISIBLE BY 13 OR
12. NOT.
WAP TO PRINT 100 MULTIPLES
WAP TO CHECK WHETHER A NUMBER IS DIVISIBLE
OF 17.BY
12. 13 OR NOT. 13.
WAP TO PRINT 50 MULTIPLES OF
21.
14.
WAP TO PRINT 100 MULTIPLES OF 17. WAP TO PRINT SQUARES OF
13. FIRST 20 NUMBERS.
15.
WAP TO PRINT CUBES OF FIRST
30 NUMBERS.
WAP TO PRINT 50 MULTIPLES OF 21.
14. 16.

WAP TO PRINT SQUARES OF FIRST 20 NUMBERS.


15.
WAP TO PRINT CUBES OF FIRST 30 NUMBERS.
16.
INDEX
S.No. EXPERIMENT DATE SING.

WAP TO PRINT THE PATTERN


17.

WAP TO FIND THE SUM OF THE SERIES. 1+2+3+4+……+n 19.


18.

WAP TO FIND THE SUM OF THE SERIES 1/1!+2/2!+3/3!+4/4!+…….+n/n!


19.

WAP TO FIND THE SUM OF THE SERIES. 1-2+3-4+5-6+7-8+…..+n


20.

CREATE A PROGRAM THAT ALLOWS THE USER TO GUESS A SECRET


21. NUMBER BETWEEN 1 TO 100. THE PROGRAM SHUOLD KEEP
PROMPTING THE USER UNTIL THEY GUESS THE CORRECT NUMBER.

WAP TO GENERATE THE FIBONACCI SEQUENCE UP TO A GIVEN NUMBER


22. OF TERMS.

CREATE A PROGRAM THAT ALLOWS TWO PLAYERS TO PLAY A GAME OF


23. ROCK,PAPER, SCISSORS.
INDEX
S.No. EXPERIMENT DATE SING.
25. WAP THAT OPENS A FILE HANDLES A FILENOTFOUNDERROR
EXCEPTION IF THE FILE DOES NOT EXIST.

S.No. EXPERIMENT DATE SING.


26. WAP THAT EXECUTES AN OPERATION ON A LIST AND HANDLES AN
INDEXERROR EXCEPTION IF THE INDEX
25.
IS OUT OF RANGE.
WAP THAT OPENS A FILE
HANDLES A
FILENOTFOUNDERROR
EXCEPTION IF THE FILE DOES
NOT EXIST.

26. WAP THAT EXECUTES AN

27. WAP THAT EXECUTES DIVISION AND HANDLES ANONARITHMETIC


OPERATION A LIST AND
HANDLES AN INDEXERROR
ERROR.
EXCEPTION IF THERE IS AN ARITHMETIC ERROR.
EXCEPTION IF THE INDEX IS
OUT OF RANGE.

27. WAP THAT EXECUTES


DIVISION AND HANDLES AN

ARITHMETIC ERROR.

EXCEPTION IF THERE IS AN
ARITHMETIC ERROR.

28. WAP TO PRINT THE REVERSE NUMBER PATTERN USING A FOR LOOP.

28. WAP TO PRINT THE REVERSE


NUMBER PATTERN USING A
FOR LOOP.

29. WAP TO PRINT ALL PRIME NUMBER 29.


WITHIN A GIVEN RANGE.
WAP TO PRINT ALL PRIME
NUMBER WITHIN A GIVEN
RANGE.

30. WAP TO REVERSE ITS DIGIT .

30. WAP TO REVERSE ITS DIGIT .


EXPERIMENT-1_______________________________________
AIM :- WAP TO SWAP 2 NUMBERS WITHOUT USING ANOTHER VARIABLE

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 :-

r = float(input("enter the radius of circle"))


a= 3.14*r*r
print("area of cirlce=", a)

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

percentage = (total_marks / 500) * 100

if percentage >= 90:

grade = 'A+’

elif percentage >= 80:

grade = 'A'

elif percentage >= 70:


grade = 'B+'
elif percentage >= 60:
grade = 'B'
elif percentage >= 50:
grade = 'C'
elif percentage >= 40:
grade = 'D'
else: OUTPUT
grade = 'F'
print("\nTotal Marks:", total_marks)
print("Percentage:", percentage)
print("Grade:", grade)
EXPERIMENT:- 9
AIM :- WAP TO TAKE THREE SIDES OF TRIANGLE AND FIND WHETHER IT IS SCALENE,ISOSCELES,EQUILATERAL OR RIGHT TRIANGLE.

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"

# Input from the user


side1 = float(input("Enter the length of side 1: "))
side2 = float(input("Enter the length of side 2: "))
side3 = float(input("Enter the length of side 3: "))
# Output the result
triangle_type = check_triangle_type(side1, side2, side3)
OUTPUT
print("The triangle is:", triangle_type)
EXPERIMENT:- 10
AIM :- WAP THAT ACCECPTS THE USER’S FIRST AND LAST NAME AND PRINTS THEM IN REVERSE ORDER WITH A SPACE BETWEEN
THEM.

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: "))

# Check if the number is divisible by 13


if number % 13 == 0:
print(f"{number} is divisible by 13.")
else:
print(f"{number} is not divisible by 13.")
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: "))
# Check if the number is divisible by 13
if number % 13 == 0:
print(f"{number} is divisible by 13.")
else:
print(f"{number} is not divisible by 13.")
OUTPUT
EXPERIMENT:- 13
AIM :- WAP TO PRINT 100 MULTIPLES OF 17.
PROGRAM :-
def print_multiples_of_17():
for i in range(1, 101):
print(f"{i} * 17 = {i * 17}")
OUTPUT
print_multiples_of_17()
EXPERIMENT:- 14
AIM:-WAP TO PRINT 50 MULTIPLES OF 21.

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):

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

# Print spaces

print(" " * (rows - i), end="")

# Print stars
OUTPUT
print("*" * (2 * i - 1))

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

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):

# Using the formula for sum of first n natural numbers: n * (n + 1) // 2

return n * (n + 1) // 2

# 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 + ... +", n, "is:", result)

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 :-

# Function to generate the Fibonacci sequence


def fibonacci_sequence(n):
sequence = []
a, b = 0, 1
for _ in range(n):
sequence.append(a)
a, b = b, a + b
return sequence
# Input from the user
n = int(input("Enter the number of terms: "))
# Generate and display the Fibonacci sequence
if n <= 0:
print("Please enter a positive integer.")
else:
result = fibonacci_sequence(n)
print("Fibonacci sequence up to", n, "terms:")
print(result)

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 :-

# Function to check if a number is prime


def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
# Input from the user
start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))
# Display all prime numbers within the range
print("Prime numbers between", start, "and", end, "are:")
for number in range(start, end + 1):
if is_prime(number):
print(number, end=" ")

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)

You might also like