PYTHON PROGRAMMING - LAB EXERCISES (23UCSCCP01)
PYTHON PROGRAMMING LAB
|
Ex.No: 01
|
Program
using variables, constants, I/O statements in Python |
|
Date:
|
Aim:
To
write a Python program using variables, constants, input, and output statements.
Algorithm:
1.
Start the program
2.
Define a constant PI
3. Get the radius of the circle
4.
Calculate the area using the formula:
area
= PI *radius * radius
5.
Display the calculated area value
6.
End the program
#Program using variables,
constants, I/O statements in Python
#
Constant: Pi value (usually written in uppercase)
PI
= 3.14159
#
Input: Read radius from user
radius
= float(input("Enter the radius of the circle (in meters): "))
#
Variable: Calculate area using formula area = PI * radius^2
area
= PI * radius * radius
#
Output: Display the result
print("The
area of the circle with radius", radius, "meters is:", area,
"square meters")
Output:
Enter the radius of the
circle (in meters): 2.5
The area of the circle
with radius 2.5 meters is: 19.6349375 square meters
Result:
Thus,
the program has been executed successfully and produces the expected output.
|
Ex.No: 02
|
Program
using Operators in Python |
|
Date:
|
Aim:
To
write a Python program that performs arithmetic, relational, and logical
operations on two numbers and displays the results.
Algorithm:
1.
Start the program
2.
Read the first number (num1)
3.
Read the second number (num2)
4.
Perform arithmetic operations:
Addition:
num1 + num2
Subtraction:
num1 - num2
Multiplication:
num1 * num2
Division:
num1 / num2
5.
Perform relational operation:
Check
if the two numbers are equal: (num1 == num2)
6.
Perform logical operation:
Check
if both numbers are positive: (num1 > 0) and (num2 > 0)
7.
Display the results of all operations
8.
End the program
#
Program using Operators in Python.
#
Input two numbers from user
num1
= float(input("Enter first number: "))
num2
= float(input("Enter second number: "))
#
Arithmetic Operations
add
= num1 + num2
sub
= num1 - num2
mul
= num1 * num2
div
= num1 / num2
#
Relational Operation
is_equal
= (num1 == num2)
#
Logical Operation
is_positive
= (num1 > 0) and (num2 > 0)
#
Output the results
print("Addition:",
add)
print("Subtraction:",
sub)
print("Multiplication:",
mul)
print("Division:",
div)
print("Are
both numbers equal?", is_equal)
print("Are
both numbers positive?", is_ positive)
Output:
Enter first number: 5.2
Enter second number:
3.3
Addition: 8.5
Subtraction: 1.9000000000000004
Multiplication: 17.16
Division:
1.575757575757576
Are both numbers equal?
False
Are both numbers
positive? True
Result:
Thus,
the program has been executed successfully and produces the expected output.
|
Ex.No: 03
|
Program
using Conditional Statements |
|
Date:
|
Aim:
To
write a Python program that checks whether the number is positive, negative, or
zero using conditional statements.
Algorithm:
1.
Start the program
2.
Read the number (num) from the user
3.
Use conditional statements to check:
If the num > 0, print "The number
is positive."
Else if the num < 0, print "The
number is negative."
Else, print "The number is zero."
4.
End the program
# Program using
Conditional Statements.
#
Program to check whether a number is positive, negative, or zero
#
Input: Read number from user
num=
int(input("Enter a number: "))
#
Conditional Statements
if
num > 0:
print("The number is positive.")
elif
num < 0:
print("The number is negative.")
else:
print("The number is zero.")
Output:
Enter a number: 7
The number is positive.
Enter a number: 0
The number is zero.
Enter a number: -7
The number is negative.
Result:
Thus,
the program has been executed successfully and produces the expected output.
|
Ex.No: 04
|
Program
using Loops
|
|
Date:
|
Aim:
To
write a Python program that calculates the sum and average of n numbers using a
loop.
Algorithm:
1.
Start the program
2.
Read the value of n
3.
Initialize sum as 0
4.
for loop from 1 to n:
read
a number from the user
Add the number to sum.
5.
Calculate : average = sum / n
6.
Display the sum and average
7.
End the program
# Program using Loops.
#
Program to calculate sum and average of n numbers using a loop
n
= int(input("Enter how many numbers you want to add: "))
sum
= 0
for
i in range(n):
number = float(input(f"Enter number
{i+1}: "))
sum += number
average
= sum / n
print("Sum
of the numbers is:", sum)
print("Average
of the numbers is:", average)
Output:
Enter how many numbers
you want to add: 5
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Enter number 4: 40
Enter number 5: 50
Sum of the numbers is:
150.0
Average of the numbers
is: 30.0
Result:
Thus,
the program has been executed successfully and produces the expected output.
|
Ex.No: 05
|
Program
using Jump Statements |
|
Date:
|
Aim:
To
write a Python program that prints numbers from 1 to 10 but skips number 5
using continue and stops the loop completely if the number becomes 8 using
break.
Algorithm:
1.
Start the program.
2.
for loop to iterate numbers from 1 to 10.
3.
In each iteration:
If
the number is 5, use continue to skip printing number 5.
If
the number is 8, use break to exit the loop completely.
Otherwise,
print the number.
4.
End the program.
# Program using Jump
Statements (break and continue)
for
i in range(1, 11):
if i == 5:
continue # Skip number 5
if i == 8:
break # Stop the loop when i is 8
print(i)
Output:
1
2
3
4
6
7
Result:
Thus,
the program has been executed successfully and produces the expected output.
|
Ex.No: 06
|
Program
using Functions |
|
Date:
|
Aim:
To
write a Python program that uses a function to calculate the factorial of a number
.
Algorithm:
1.
Start the program
2.
Define a function factorial(n):
Initialize fact = 1.
Use a loop from 1 to n to multiply fact by
each number
Return the value of fact
3.
Get a number (n) from the user
4.
Call the function factorial(n)
5.
Print the result (fact).
6.
End the program
# Function to calculate
factorial
def
factorial(n):
fact = 1
for i in range(1, n + 1):
fact *= i
return fact
# Main program
num
= int(input("Enter a number to find its factorial: "))
result
= factorial(num)
print(f"The
factorial of {num} is: {result}")
Output:
Enter a number to find
its factorial: 5
The factorial of 5 is:
120
Result:
Thus,
the program has been executed successfully and produces the expected output.
|
Ex.No: 07 |
Program
using Recursion |
|
Date: |
Aim:
To
write a Python program that calculates the factorial of a number using
recursion.
Algorithm:
1.
Start the program
2.
Define a recursive function factorial(n):
Base case: If
n == 0 or n == 1, return 1.
Recursive case: Return n*factorial(n -
1)
3.
Read an integer number from the user
4.
Call the recursive function factorial(n)
5.
Print the result (factorial of the number)
6.
End the program
# Recursive function to
calculate factorial
def
factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Main program
num
= int(input("Enter a number to find its factorial using recursion:
"))
result
= factorial(num)
print(f"The
factorial of {num} is: {result}")
Output:
Enter a number to find
its factorial using recursion: 5
The factorial of 5 is:
120
Result:
Thus,
the program has been executed successfully and produces the expected output.
Ex.No: 08
|
Program
using Arrays (Lists) |
|
Date:
|
Aim:
To
write a Python program that stores n numbers in an array and finds the sum and
average of those numbers.
Algorithm:
1.
Start the program.
2.
Create an empty list numbers = [].
3.
Read the value of n
4.
for loop from 1 to n:
Get
a number
Append
the number to the numbers list.
5.
Calculate the sum using the built-in sum() function.
6.
Calculate the average as sum / n.
7.
Display the array, sum, and average.
8.
End the program.
# Program to store n
numbers in an array and calculate sum and average
#
Step 1: Create an empty list
numbers
= []
#
Step 2: Input how many numbers to store
n
= int(input("Enter the number of elements: "))
#
Step 3: Read numbers from user and store in the array
for
i in range(n):
num = float(input(f"Enter number {i +
1}: "))
numbers.append(num)
#
Step 4: Calculate sum and average
total
= sum(numbers)
average
= total / n
#
Step 5: Display results
print("\nArray
of numbers:", numbers)
print("Sum
of numbers:", total)
print("Average
of numbers:", average)
Output:
Enter the number of
elements: 4
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Enter number 4: 40
Array of numbers:
[10.0, 20.0, 30.0, 40.0]
Sum of numbers: 100.0
Average of numbers:
25.0
Result:
Thus,
the program has been executed successfully and produces the expected output.
|
Ex.No: 09 |
Python
Program using Strings |
|
Date: |
Aim:
To
write a Python program that takes a string input from the user and performs the
following string operations.
Algorithm:
1.
Start the program.
2.
Read a string input from the user.
3.
Calculate and display the length of the string using len().
4.
Convert and display the string in uppercase using .upper().
5.
Reverse and display the string using slicing ([::-1]).
6.
Initialize a vowel counter to 0.
7.
Loop through each character of the string:
If the character is a vowel (a, e, i, o,
u), increment the counter.
8.
Display the total number of vowels.
9.
End the program.
# Program to perform
string operations
#
Step 1: Read string from user
text
= input("Enter a string: ")
#
Step 2: Length of string
len
= len(text)
#
Step 3: Convert to uppercase
caps
= text.upper()
#
Step 4: Reverse the string
rev
= text[::-1]
#
Step 5: Count vowels
vowels
= 'aeiouAEIOU'
vc
= 0
for
char in text:
if char in vowels:
vc += 1
#
Step 6: Display results
print("\nLength
of the string:", len)
print("Uppercase
string:", caps)
print("Reversed
string:", rev)
print("Number
of vowels:", vc)
Output:
Enter a string:
tamilnadu
Length of the string: 9
Uppercase string:
TAMILNADU
Reversed string:
udanlimat
Number of vowels: 4
Result:
Thus,
the program has been executed successfully and produces the expected output.
|
Ex.No: 10
|
Program
using Modules |
|
Date:
|
Aim:
To
write a Python program that uses the built-in math module to calculate and
display the square root, power, and factorial of a number.
Algorithm:
1.
Start the program.
2.
Import the math module.
3.
Read a number from the user.
4.
Calculate the square root using math.sqrt().
5.
Calculate the power of 2 using math.pow().
6.
Calculate the factorial using math.factorial().
7.
Display the results.
8.
End the program.
# Program demonstrating
the use of math module
import
math
#
Step 1: Input number from user
num
= int(input("Enter a positive integer: "))
#
Step 2: Calculate square root
squ
= math.sqrt(num)
# Step 3: Calculate power (num^2)
power
= math.pow(num, 2)
#
Step 4: Calculate factorial
fact
= math.factorial(num)
#
Step 5: Display results
print(f"\nSquare
root of {num} is: {squ }")
print(f"{num}
raised to power 2 is: {power}")
print(f"Factorial
of {num} is: {fact}")
Output:
Enter a positive
integer: 9
Square root of 9 is:
3.0
9 raised to power 2 is:
81.0
Factorial of 9 is:
362880
Result:
Thus,
the program has been executed successfully and produces the expected output.
|
Ex.No: 11
|
Program Using Lists |
|
Date:
|
Aim:
To write a Python program that
demonstrates creation, accessing, and manipulation of lists.
Algorithm:
- Start the program.
- Create a list containing fruit names.
- Display the list elements.
- Access individual elements using
indexes.
- Add a new element to the list.
- Remove an element from the list.
- Update an element in the list.
- Display the modified list.
- End the program.
# Creating a list
fruits =
["apple", "banana", "cherry", "orange"]
# Display
the list
print("Fruits
list:", fruits)
#
Accessing elements
print("First
fruit:", fruits[0])
print("Last
fruit:", fruits[-1])
# Adding a
new fruit
fruits.append("grape")
print("\nAfter
adding 'grape':", fruits)
# Removing
a fruit
fruits.remove("banana")
print("After
removing 'banana':", fruits)
# Updating
an element
fruits[1]
= "mango"
print("After
updating second element to 'mango':", fruits)
# Display
all elements using loop
print("\nList
of fruits:")
for fruit
in fruits:
print(fruit)
Output:
Fruits
list: ['apple', 'banana', 'cherry', 'orange']
First
fruit: apple
Last
fruit: orange
After adding
'grape': ['apple', 'banana', 'cherry', 'orange', 'grape']
After
removing 'banana': ['apple', 'cherry', 'orange', 'grape']
After
updating second element to 'mango': ['apple', 'mango', 'orange', 'grape']
List of
fruits:
apple
mango
orange
grape
Result:
Thus,
the program has been executed successfully and produces the expected output.
|
Ex.No: 12
|
Program Using Tuples |
|
Date:
|
Aim:
To write a Python program that
demonstrates the creation, accessing, and manipulation of tuples.
Algorithm:
- Start the program.
- Create a tuple containing fruit
names.
- Display the elements of the tuple.
- Access individual elements using
indexes.
- Find the length of the tuple.
- Use a loop to print all elements
of the tuple.
- Check if a specific element exists
in the tuple.
- End the program.
# Creating a tuple
fruits
= ("apple", "banana", "cherry",
"orange")
#
Display the tuple
print("Fruits
tuple:", fruits)
#
Accessing elements
print("First
fruit:", fruits[0])
print("Last
fruit:", fruits[-1])
#
Tuple length
print("Number
of fruits:", len(fruits))
#
Iterating through tuple
print("\nList
of fruits:")
for
fruit in fruits:
print(fruit)
#
Checking membership
if
"banana" in fruits:
print("\nYes,
'banana' is in the fruits tuple!")
Output:
Fruits
tuple: ('apple', 'banana', 'cherry', 'orange')
First
fruit: apple
Last
fruit: orange
Number
of fruits: 4
List
of fruits:
apple
banana
cherry
orange
Yes,
'banana' is in the fruits tuple!
Combined
tuple: ('apple', 'banana', 'cherry', 'orange', 'grape', 'mango')
Result:
Thus,
the program has been executed successfully and produces the expected output.
|
Ex.No: 13
|
Program Using Dictionaries |
|
Date:
|
Aim:
To write a Python program that
demonstrates the creation, accessing, updating, and manipulation of
dictionaries.
Algorithm:
- Start the program.
- Create a dictionary containing
key-value pairs of student details.
- Display the dictionary.
- Access values using keys.
- Add a new key-value pair to the
dictionary.
- Update an existing value.
- Remove a key-value pair.
- Display all keys and values using a
loop.
- End the program.
#
Creating a dictionary
student = {
"name": "Tharun",
"age": 12,
"class": "6th Blue",
"school": "Spectrum Life School"
}
# Display the dictionary
print("Student Dictionary:", student)
# Accessing values
print("Name:", student["name"])
print("Class:",
student["class"])
# Adding a new key-value pair
student["grade"] = "A"
print("\nAfter adding grade:", student)
# Updating an existing value
student["age"] = 13
print("After updating age:", student)
# Removing a key-value pair
student.pop("class")
print("After removing class:", student)
# Display all keys and values
print("\nStudent Details:")
for key, value in student.items():
print(key, ":", value)
Output:
Student Dictionary: {'name': 'Tharun', 'age': 12,
'class': '6th Blue', 'school': 'Spectrum Life School'}
Name: Tharun
Class: 6th Blue
After adding grade: {'name': 'Tharun', 'age': 12,
'class': '6th Blue', 'school': 'Spectrum Life School', 'grade': 'A'}
After updating age: {'name': 'Tharun', 'age': 13,
'class': '6th Blue', 'school': 'Spectrum Life School', 'grade': 'A'}
After removing class: {'name': 'Tharun', 'age': 13,
'school': 'Spectrum Life School', 'grade': 'A'}
Student Details:
name :Tharun
age : 13
school : Spectrum Life School
grade : A
Result:
Thus,
the program has been executed successfully and produces the expected output.
|
Ex.No: 14
|
Program for File Handling |
|
Date:
|
Aim:
To write a Python program that
demonstrates file handling operations such as writing to and reading from a
text file.
Algorithm:
- Start the program.
- Open a text file in write mode.
- Write some data into the file.
- Close the file after writing.
- Open the same file in read mode.
- Read the contents of the file.
- Display the file contents.
- Close the file.
- End the program.
#
Writing data to a file
file = open("sample.txt", "w")
file.write("Welcome to Python File
Handling!\n")
file.write("This file demonstrates writing and
reading operations.\n")
file.close()
# Reading data from the file
file = open("sample.txt", "r")
content = file.read()
print("File Contents:\n")
print(content)
file.close()
Output:
File Contents:
Welcome to Python File Handling!
This file demonstrates writing and reading
operations.
Result:
Thus,
the program has been executed successfully and produces the expected output.
Comments
Post a Comment