Python Lab Experiments With Algm_n_code
Python Lab Experiments With Algm_n_code
# Calculate sum
sum_result = num1 + num2
# Calculate difference
difference = num1 - num2
# Calculate average
average = sum_result / 2
6. Write a program in Python to swap two numbers using third variable and find the
area of a triangle with these swapped values
Algorithm : swap two numbers using third variable and find the area of a triangle with
these swapped values
1. Input the two numbers, num1 and num2.
2. Swap the numbers:
o Use a third variable, temp, to hold the value of num1.
o Assign the value of num2 to num1.
o Assign the value of temp to num2.
3. Calculate the area of the triangle:
o Treat the swapped num1 as the base and num2 as the height.
o Use the formula for the area of a triangle: Area=12×base×height\text{Area} =
\frac{1}{2} \times \text{base} \times \text{height}Area=21×base×height
4. Output the swapped values and the area.
Program in Python to swap two numbers using third variable and find the area of a
triangle with these swapped values
import math
# Input two numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
OUTPUT
Enter the first number: 12
Enter the second number: 11
After swapping: First number = 11.0, Second number = 12.0
Enter the third side of the triangle: 13
The area of the triangle with sides 11.0, 12.0, and 13.0 is: 61.48170459575759
Algorithm
1. Input the number of rows for the pattern from the user.
2. Use an outer loop to iterate through each row:
o The loop variable represents the current row.
3. Use an inner loop to control the number of stars (*) printed in each row:
o The number of stars printed equals the row number in most patterns.
4. Print the stars in each row and move to the next line.
5. Stop once all rows are printed.
Pattern 3: Diamond
# Upper part
for i in range(1, rows + 1):
print(" " * (rows - i) + "*" * (2 * i - 1))
# Lower part
for i in range(rows - 1, 0, -1):
print(" " * (rows - i) + "*" * (2 * i - 1))
*
***
*****
*******
*********
*******
*****
***
*
8. Write a program in Python to print the Fibonacci series up to a given limit N
Algorithm to Print Fibonacci Series up to a Given Limit (N)
1. Start.
2. Input the limit NNN from the user.
3. Initialize two variables:
o a=0(first Fibonacci number).
o b=1 (second Fibonacci number).
4. Print aaa, the first number in the Fibonacci series.
5. While aaa is less than or equal to NNN:
6. Print 𝑎
7. Calculate the next Fibonacci number
8. temp = b (store the value of b).
9. b=a+b (update b to the next Fibonacci number)
10. a=temp (update a to the value of the old b).
11. Stop the loop when a>N.
12. End.
Program
# Input the limit
n = int(input("Enter the limit (N): "))
# Initialize the first two numbers of the Fibonacci series
a, b = 0, 1
# Print the Fibonacci series up to N
print("Fibonacci series up to", n, ":")
while a <= n:
print(a, end=" ")
a, b = b, a + b # Update to the next numbers in the series
OUTPUT
Enter the limit (N): 8
Fibonacci series up to 8 :
0 112358
1. Start.
3. Initialize reverse = 0 and original = num to store the reverse of the number and preserve
the original value for comparison.
o Remove the last digit from num using num = num // 10.
7. End.
Program to check whether a number is palindrome or not.
# Input a number
# Initialize variables
original = num
reverse = 0
if original == reverse:
print(f"{original} is a palindrome.")
else:
OUTPUT:
Enter a number: 121
121 is a palindrome.
Enter a number: 123
123 is not a palindrome.
10. Program to convert a decimal number to binary and an octal number.
# Perform conversions
binary_representation = decimal_to_binary(decimal_number)
octal_representation = decimal_to_octal(decimal_number)
# Display results
print(f"Binary representation: {binary_representation}")
print(f"Octal representation: {octal_representation}")
# Perform conversions
binary_representation = decimal_to_binary(decimal_number)
octal_representation = decimal_to_octal(decimal_number)
# Display results
print(f"Binary representation: {binary_representation}")
print(f"Octal representation: {octal_representation}")
OUTPUT
Enter a decimal number: 45
Binary representation: 101101
Octal representation: 55
LAB CYCLE 2
11. A program that prints prime numbers less than N with algorithm and program
in python
Algorithm
1. Initialize Variables:
• Create an empty list lst to store prime numbers.
• Initialize a flag variable to 0.
2. Iterate Over the Range:
• Loop through each number iii from starting_range to ending_range - 1.
3. Check for Primality:
• Skip numbers less than 2 as they are not prime.
• For each number iii, iterate through potential divisors jjj from 2 to i−1i -
1i−1.
• If i%j==0:
Set flag = 1 and break the inner loop (indicating iii is not prime).
• Otherwise, ensure flag = 0.
4. Append to Prime List:
• After exiting the inner loop, if flag == 0, append iii to lst.
5. Print the Result:
• After the outer loop completes, print the list lst containing all prime numbers
Program
# Input range
N=int(input(“Enter the range”))
# Initialize list for prime numbers
lst = [ ]
# Iterate through the range
for i in range(N):
if i < 2: # Skip numbers less than 2
continue
flag = 0 # Reset flag for each number
for j in range(2, i): # Check divisors from 2 to (i-1)
if i % j == 0: # If divisible, not a prime number
flag = 1
break
if flag == 0: # If flag remains 0, it's a prime number
lst.append(i)
Algorithm
1. BaseCase:
If n=0 or n=1, return 1. This is because 0!=1!=1.
2. RecursiveCase:
For n>1, the factorial of n can be defined as:
n!=n×(n−1)!
3. Termination:
The recursion ends when the base case is reached.
Program
def factorial(n):
# Base case
if n == 0 or n == 1:
return 1
# Recursive case
else:
return n * factorial(n - 1)
if num < 0:
else:
13. Program to create a menu driven desktop calculator using Python. Only the five
basic arithmetic operators.
Algorithm
To create a menu-driven desktop calculator in Python that supports five basic arithmetic
operators:
1. Display Menu:
1.1 Show options for addition, subtraction, multiplication, division, and
modulus.
1.2 Include an option to exit the program.
2. User Input:
2.1 Prompt the user to select an operation by entering a number corresponding
to the menu option.
3. Perform Calculation:
3.1 Based on the user's choice, prompt for two numbers.
3.2 Perform the selected operation and display the result.
4. Loop:
4.1 Keep displaying the menu until the user chooses to exit.
5. Exit:
5.1 Terminate the program when the user selects the exit option.
Program
while True:
print("6. Exit")
if choice == 6:
break
elif choice == 2:
elif choice == 3:
elif choice == 4:
if num2 != 0:
else:
elif choice == 5:
if num2 != 0:
else:
else:
OUTPUT:
Algorithm
1. Create a String:
2. Concatenate Strings:
o Create another string and concatenate it with the first string using the + operator.
4. Access a Substring:
Program:
OUTPUT
15. Familiarize time and date in various formats (Eg. “Thu Jul 11 10:26:23 IST
2024”).
Algorithm
o Use Python's built-in datetime module to handle date and time operations.
o Use the strftime() method to format the date and time in different styles.
o Specify format codes to control the output format (e.g., %A for weekday, %B
for month name).
Program
current_datetime = datetime.now()
OUTPUT:
Algorithm
1. Base Case:
2. Recursive Case:
3. Termination:
Program
Output
17. Recursive function to multiply two positive numbers.
Algorithm
Program
18. Recursive function to find the greatest common divisor of two positive numbers.
Algorithm
To find the greatest common divisor (GCD) of two positive numbers aaa and bbb using
recursion:
2. Use the Euclidean algorithm, which states: GCD(a, b)=GCD(b, a mod b).
Program
19. Program to check whether the given number is a valid mobile number or not using
functions.
[Rules: 1. every number should contain exactly 10 digits. 2. The first digit should
be 7 or 8 or 9]
Algorithm
1. Input and Accept the mobile number as a string to handle cases like leading zeros or
non-numeric characters.
2. Check Length: Verify that the length of the number is exactly 10 digits.
4. Check for Digits Only: Ensure the number consists only of digits.
5.1 If all conditions are met, print that the number is valid.
5.2 Otherwise, indicate that it is invalid.
Program:
OUTPUT
CYCLE 3
20. A program that accepts the lengths of three sides of a triangle as inputs. The
program should output whether or not the triangle is a right triangle (Recall from
the Pythagorean Theorem that in a right triangle, the square of one side equals the
sum of the squares of the other two sides). Implement using functions.
Algorithm
1. Input three numbers representing the sides of a triangle.
2. Sort the three sides in ascending order so the largest side is treated as the hypotenuse.
3. Check Pythagorean Theorem: c2=a2+b2 (where c is the largest side).
o If the condition holds, it's a right triangle; otherwise, it's not.
4. Print whether the triangle is a right triangle or not.
Program
OUTPUT:
21. Write a program to create, append, and remove lists in Python using NumPy.
Algorithm
1. Initialize NumPy: Import the numpy library.
2. Create a List: Use numpy.array() to create a NumPy array.
3. Append Elements: Use numpy.append() to add elements to the array.
4. Remove Elements: Use slicing or other NumPy operations to remove elements (as
numpy arrays do not have a direct method like remove() in Python lists).
5. Output the Results: Display the list after each operation
Program
Output
22. Input two lists from the user. Merge these lists into a third list such that in the
merged list, all even numbers occur first followed by odd numbers. Both the even
numbers and odd numbers should be in sorted order
Algorithm
1. Input Two Lists of numbers.
2. Merge the Lists: two lists into a single list.
3. Iterate through the merged list, separating even and odd numbers into two separate lists.
4. Sort the even numbers list and the odd numbers list.
5. Merge Sorted Lists: - Combine the sorted even numbers list followed by the sorted odd
numbers list.
6. Display the merged and sorted list.
Program:
even_numbers.sort()
odd_numbers.sort()
print("\nFinal List with evens first (sorted) and odds next (sorted):")
print(result)
Output
23. Program to define a module to find Fibonacci Numbers and import the module to
another program
Algorithm
1. Define a Module:
o Create a Python file (e.g., fibonacci_module.py) with functions to generate
Fibonacci numbers.
2. Implement Functionality:
o Implement a function to generate Fibonacci numbers up to a certain number or
count.
Main Program:
3. Import the Module:
o Import the custom module into another program.
4. Call the Function:
o Use the functions from the module to calculate Fibonacci numbers and display
the results.
Program
def fibonacci_by_count(count):
sequence = []
a, b = 0, 1
for _ in range(count):
sequence.append(a)
a, b = b, a + b
return sequence
def fibonacci_up_to(max_value):
sequence = []
a, b = 0, 1
sequence.append(a)
a, b = b, a + b
return sequence
import fibonacci_module
print("Choose mode:")
if choice == 1:
result = fibonacci_module.fibonacci_by_count(n)
elif choice == 2:
result = fibonacci_module.fibonacci_up_to(max_value)
else:
print("Invalid choice!")