0% found this document useful (0 votes)
24 views13 pages

Monday Lab

The document outlines a series of Python programming exercises aimed at teaching various concepts such as user input, arithmetic operations, string manipulation, and mathematical functions. Each exercise includes an aim, source code, and example output. The topics covered range from basic operations like addition and string reversal to more complex tasks like calculating Fibonacci sequences and checking for prime numbers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views13 pages

Monday Lab

The document outlines a series of Python programming exercises aimed at teaching various concepts such as user input, arithmetic operations, string manipulation, and mathematical functions. Each exercise includes an aim, source code, and example output. The topics covered range from basic operations like addition and string reversal to more complex tasks like calculating Fibonacci sequences and checking for prime numbers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Programs based on above Syllabus for 18.03.

2025 lab
1. Write a Python program to accept a user's name and age, then print a greeting message.

AIM: To write a Python program to accept a user's name and age for printing a greeting message.

SOURCE CODE:

# Accept user input for name


name = input("Enter your name: ")

# Loop until a valid numeric age is entered


while True:
age = input("Enter your age: ")
if age.isdigit(): # Check if input consists of digits only
age = int(age) # Convert to an integer
break
else:
print("Invalid input. Please enter a numeric age.")

# Print a greeting message


print(f"Hello, {name}! You are {age} years old.")

OUTPUT:

Enter your name: John


Enter your age: 30
Hello, John! You are 30 years old.

2. Accept two integers from the user and perform addition, subtraction, multiplication, and division.

AIM: To accept two integers from the user and perform addition, subtraction, multiplication and
division.

SOURCE CODE:

# Accept two integers from the user


num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

# Perform arithmetic operations


addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2 if num2 != 0 else "Undefined (division by zero)"

# Display results
print(f"\nResults:")
print(f"Addition: {num1} + {num2} = {addition}")
print(f"Subtraction: {num1} - {num2} = {subtraction}")
print(f"Multiplication: {num1} × {num2} = {multiplication}")
print(f"Division: {num1} ÷ {num2} = {division}")
OUTPUT:

Enter the first number: 10


Enter the second number: 5

Results:
Addition: 10 + 5 = 15
Subtraction: 10 - 5 = 5
Multiplication: 10 × 5 = 50
Division: 10 ÷ 5 = 2.0

3. Write a program that swaps the values of two variables without using a third variable.

AIM: To write a program that swaps the values of two variables without using the third variable.

SOURCE CODE:

# Accept two numbers from the user


a = int(input("Enter the first number (a): "))
b = int(input("Enter the second number (b): "))

# Swap the values without using a third variable


a, b = b, a

# Display the swapped values


print("\nAfter swapping:")
print(f"a = {a}")
print(f"b = {b}")

OUTPUT:

Enter the first number (a): 5


Enter the second number (b): 10

After swapping:
a = 10
b=5

4. Write a Python script to check whether a given number is even or odd.

AIM: To write a python script to check whether a given number is even or odd.

SOURCE CODE:

# Accept a number from the user


num = int(input("Enter a number: "))

# Check if the number is even or odd


if num % 2 == 0:
print(f"{num} is an even number.")
else:
print(f"{num} is an odd number.")

OUTPUT:

Enter a number: 8
8 is an even number.

Enter a number: 7
7 is an odd number.

5. Take a string as input from the user and count the number of vowels in it.

AIM: To take a string as input from the user and count the number of vowels in it.

SOURCE CODE:

# Accept a string from the user


text = input("Enter a string: ")

# Define vowels
vowels = "aeiouAEIOU"

# Count vowels in the string


vowel_count = sum(1 for char in text if char in vowels)

# Display the result


print(f"The number of vowels in the given string is: {vowel_count}")

OUTPUT:

Enter a string: Hello World


The number of vowels in the given string is: 3

6. Write a program that calculates and prints the area of a circle given the radius as input.

AIM: To write a program that calculates and prints the area of a circle given the radius as input.

SOURCE CODE:

import math # Import math module to use π (pi)

# Accept the radius from the user


radius = float(input("Enter the radius of the circle: "))

# Calculate the area of the circle


area = math.pi * radius ** 2 # πr² formula

# Display the result


print(f"The area of the circle with radius {radius} is: {area:.2f}")

OUTPUT:
Enter the radius of the circle: 5
The area of the circle with radius 5.0 is: 78.54

7. Accept an integer from the user and print its binary, octal, and hexadecimal representations.

AIM: To accept an integer from the user and print it’s binary, octal, and hexadecimal representations.

SOURCE CODE:

# Accept an integer from the user


num = int(input("Enter an integer: "))

# Convert to different number systems


binary_rep = bin(num) # Convert to binary
octal_rep = oct(num) # Convert to octal
hex_rep = hex(num) # Convert to hexadecimal

# Display the results


print(f"\nBinary representation: {binary_rep[2:]}")
print(f"Octal representation: {octal_rep[2:]}")
print(f"Hexadecimal representation: {hex_rep[2:].upper()}")

OUTPUT:

Enter an integer: 25

Binary representation: 11001


Octal representation: 31
Hexadecimal representation: 19

8. Write a program to convert a given temperature from Fahrenheit to Celsius.

AIM: To write a program to convert a given temperature from Fahrenheit to Celsius.

SOURCE CODE:

# Accept temperature in Fahrenheit from the user


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

# Convert Fahrenheit to Celsius using the formula


celsius = (fahrenheit - 32) * 5 / 9

# Display the result


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

OUTPUT:

Enter temperature in Fahrenheit: 98.6


98.6°F is equal to 37.00°C

9. Take two numbers as input and compute the result of a^b using both the ** operator and math.pow().
AIM: To take two numbers as input and compute the result of a^b using the ** operator and
math.pow().

SOURCE CODE:

import math # Import the math module

# Accept two numbers from the user


a = float(input("Enter the base (a): "))
b = float(input("Enter the exponent (b): "))

# Compute power using ** operator


result1 = a ** b

# Compute power using math.pow()


result2 = math.pow(a, b)

# Display the results


print(f"\nUsing '**' operator: {a}^{b} = {result1}")
print(f"Using 'math.pow()' function: {a}^{b} = {result2}")

OUTPUT:

Enter the base (a): 2


Enter the exponent (b): 3

Using '**' operator: 2.0^3.0 = 8.0


Using 'math.pow()' function: 2.0^3.0 = 8.0

10. Write a program to determine whether a given year is a leap year or not.

AIM: To write a program to determine whether a given year is a leap year or not.

SOURCE CODE:

# Accept a year from the user


year = int(input("Enter a year: "))

# Check if the year is a leap year


if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")

OUTPUT:

Enter a year: 2024


2024 is a leap year.

Enter a year: 1900


1900 is not a leap year.
11. Write a Python program to reverse a given string.

AIM: To write a python program to reverse a given string.

SOURCE CODE:

# Accept a string from the user


text = input("Enter a string: ")

# Reverse the string using slicing


reversed_text = text[::-1]

# Display the result


print(f"Reversed string: {reversed_text}")

OUTPUT:

Enter a string: Python


Reversed string: nohtyP

12. Accept a sentence as input and print the number of words in it.

AIM: To accept a sentence as input and print the number of words in it.

SOURCE CODE:

# Accept a sentence from the user


sentence = input("Enter a sentence: ")

# Split the sentence into words and count them


word_count = len(sentence.split())

# Display the result


print(f"The number of words in the sentence is: {word_count}")

OUTPUT:

Enter a sentence: Python programming is fun!


The number of words in the sentence is: 4

13. Write a program to replace all occurrences of 'a' with '@' in a given string.

AIM: To write a program to replace all occurrences of ‘a’ with ‘@’ in a given string.

SOURCE CODE:

# Accept a string from the user


text = input("Enter a string: ")

# Replace all occurrences of 'a' (case-sensitive)


modified_text = text.replace('a', '@')
# Display the modified string
print(f"Modified string: {modified_text}")

OUTPUT:

Enter a string: banana apple avocado


Modified string: b@n@n@ @pple @voc@do

14. Concatenate three user-input strings and print the result.

AIM: To concatenate three user-input strings and print the result.

SOURCE CODE:

# Accept three strings from the user


str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
str3 = input("Enter third string: ")

# Concatenate the strings


result = str1 + str2 + str3

# Display the concatenated result


print(f"Concatenated string: {result}")

OUTPUT:

Enter first string: Hello


Enter second string: World
Enter third string: 2025
Concatenated string: HelloWorld2025

15. Accept a string and check if it is a palindrome.

AIM: To accept a string and check if it is a palindrome.

SOURCE CODE:

# Accept a string from the user


text = input("Enter a string: ")

# Convert to lowercase to make it case-insensitive


text_lower = text.lower()

# Check if the string is equal to its reverse


if text_lower == text_lower[::-1]:
print(f'"{text}" is a palindrome.')
else:
print(f'"{text}" is not a palindrome.')

OUTPUT:
Enter a string: Racecar
"Racecar" is a palindrome.

16. Write a Python function to calculate the factorial of a given number.

AIM: To write a python function to calculate the factorial of a given number.

SOURCE CODE:

def factorial(n):
result = 1
for i in range(2, n + 1):
result *= i
return result

num = int(input("Enter a number: "))

if num < 0:
print("Factorial is not defined for negative numbers.")
else:
print(f"Factorial of {num} is {factorial(num)}")

OUTPUT:

Enter a number: 5
Factorial of 5 is 120

17. Implement a function that returns the Fibonacci sequence up to n terms.

AIM: To implement a function that returns the Fibonacci sequence up to n terms.

SOURCE CODE:

def fibonacci(n):
sequence = []
a, b = 0, 1
for _ in range(n):
sequence.append(a)
a, b = b, a + b
return sequence

# Accept the number of terms from the user


num_terms = int(input("Enter the number of Fibonacci terms: "))

# Check if input is valid


if num_terms <= 0:
print("Please enter a positive integer.")
else:
print(f"Fibonacci sequence up to {num_terms} terms: {fibonacci(num_terms)}")

OUTPUT:
Enter the number of Fibonacci terms: 7
Fibonacci sequence up to 7 terms: [0, 1, 1, 2, 3, 5, 8]
18. Write a Python program that takes a number as input and checks if it is a prime number using a
function.

AIM: To write a python program that takes a number as input and checks if it is a prime number using a
function.

SOURCE CODE:

def is_prime(n):
"""Function to check if a number is prime."""
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True

# Accept a number from the user


num = int(input("Enter a number: "))

# Check and display the result


if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")

OUTPUT:

Enter a number: 29
29 is a prime number.

19. Use the math module to calculate the square root, logarithm, and sine of a given number.

AIM: To use the math module to calculate the square root, logarithm, and sine of a given number.

SOURCE CODE:

import math

# Accept a number from the user


num = float(input("Enter a number: "))

# Calculate square root


square_root = math.sqrt(num)

# Calculate natural logarithm (log base e)


if num > 0:
logarithm = math.log(num)
else:
logarithm = "Undefined (logarithm is only defined for positive numbers)"
# Calculate sine (in radians)
sine_value = math.sin(num)

# Display results
print(f"Square root of {num}: {square_root}")
print(f"Natural logarithm of {num}: {logarithm}")
print(f"Sine of {num} radians: {sine_value}")

OUTPUT:

Enter a number: 25
Square root of 25.0: 5.0
Natural logarithm of 25.0: 3.2188758248682006
Sine of 25.0 radians: -0.13235175009777303

20. Implement a Python program that runs only if executed as the main module and calls a function to
print "Hello from Main!".

AIM: To implement a python program that runs only if executed as the main module and calls a
function to print “Hello from Main!”.

SOURCE CODE:

def greet():
"""Function to print a greeting message."""
print("Hello from Main!")

# Ensure the script runs only when executed directly


if __name__ == "__main__":
greet()

OUTPUT:

$ python script.py
Hello from Main!

import script # This will NOT print "Hello from Main!" automatically

21. Write a program that reads a string and prints the frequency of each character.

AIM: To write a program that reads a string and prints the frequency of each character.

SOURCE CODE:

def char_frequency(s):
"""Function to count character frequencies in a string."""
freq = {} # Dictionary to store character counts
for char in s:
freq[char] = freq.get(char, 0) + 1 # Increment count

return freq
# Accept a string from the user
text = input("Enter a string: ")

# Get character frequency


result = char_frequency(text)

# Display the frequency of each character


print("Character frequencies:")
for char, count in result.items():
print(f"'{char}': {count}")

OUTPUT:

Enter a string: hello world


Character frequencies:
'h': 1
'e': 1
'l': 3
'o': 2
' ': 1
'w': 1
'r': 1
'd': 1

22. Implement a function that finds the greatest common divisor (GCD) of two numbers using recursion.

AIM: To implement a function that finds the greatest common divisor (GCD) of two numbers using
recursion.

SOURCE CODE:

def gcd(a, b):


"""Recursive function to find the GCD of two numbers."""
if b == 0:
return a
else:
return gcd(b, a % b)

# Accept two numbers from the user


num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

# Compute GCD
result = gcd(num1, num2)

# Display the result


print(f"The GCD of {num1} and {num2} is {result}")

OUTPUT:

Enter the first number: 48


Enter the second number: 18
The GCD of 48 and 18 is 6

23. Write a Python script that calculates the sum of digits of a given number.

AIM: To write a python script that calculates the sum of digits of a given number.

SOURCE CODE:

def sum_of_digits(n):
"""Function to calculate the sum of digits of a number."""
total = 0
while n > 0:
total += n % 10 # Extract last digit and add to total
n //= 10 # Remove last digit
return total

# Accept input from the user


num = int(input("Enter a number: "))

# Compute sum of digits


result = sum_of_digits(abs(num)) # Use abs() to handle negative numbers

# Display the result


print(f"The sum of digits of {num} is {result}")

OUTPUT:

Enter a number: 1234


The sum of digits of 1234 is 10

24. Accept a list of numbers from the user and find the second-largest number.

AIM: To accept a list of numbers from the user and find the second-largest number.

SOURCE CODE:

def second_largest(nums):
"""Function to find the second-largest number without sorting."""
first, second = float('-inf'), float('-inf')

for num in nums:


if num > first:
second, first = first, num # Update both first and second
elif first > num > second:
second = num # Update second if it's smaller than first but larger than the previous
second

return second if second != float('-inf') else "No second largest number"

# Accept input from the user


numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
# Find and print the second largest number
print("Second largest number:", second_largest(numbers))

OUTPUT:

Enter numbers separated by spaces: 10 20 5 8 30


Second largest number: 20

25. Create a Python function that checks whether a given string contains only digits (without
using .isdigit()).

AIM: To create a python function that checks whether a given string contains only digits (without
using.isdigit()).

SOURCE CODE:

def is_numeric(s):
"""Function to check if a string contains only digits."""
for char in s:
if char not in "0123456789": # Check if each character is a digit
return False
return True

# Accept user input


text = input("Enter a string: ")

# Check and print result


print(f"Does '{text}' contain only digits? {is_numeric(text)}")

OUTPUT:

Enter a string: 123456


Does '123456' contain only digits? True

Enter a string: 12a45


Does '12a45' contain only digits? False

You might also like