[go: up one dir, main page]

0% found this document useful (0 votes)
29 views53 pages

Record Programs Till Functions

The document discusses various Python programming concepts like data types, operators, functions, input/output etc. It provides examples to demonstrate arithmetic, relational, logical, assignment operators and functions like print(), type conversion etc. It also discusses control flow statements, functions and methods in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views53 pages

Record Programs Till Functions

The document discusses various Python programming concepts like data types, operators, functions, input/output etc. It provides examples to demonstrate arithmetic, relational, logical, assignment operators and functions like print(), type conversion etc. It also discusses control flow statements, functions and methods in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Record Programs DS, CS&IT

Basic Data Types


1. Print all the keywords in Python

import keyword
# Get the list of all Python keywords
python_keywords = keyword.kwlist`
# Print the list of keywords
print("List of Python keywords:")
print(', '.join(python_keywords))
Output:
List of Python keywords:
False, None, True, and, as, assert, async, await, break, class, continue, def, del,
elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not,
or, pass, raise, return, try, while, with, yield

2. Demonstrate the following Operators in Python with suitable examples. i)


Arithmetic Operators ii) Relational Operators iii) Assignment Operator iv)
Logical Operators v) Bit wise Operators vi) TernaryOperator vii)
Membership Operators viii) Identity Operators
Arithmetic Operators
print(15+15) #30
print(45-75) #-30
print(3*5) #15
print(20//5) #4
print(2**3) #8
print(5%2) #2
print(5/2) #2.5
Relational Operators
print(20>20) #False
print(2<10) #True
print(11<=9) #False
print(10>=10) #True
print(10!=100) #True
Record Programs DS, CS&IT

print(101==10) #False
Assignment Operators
a=2
print(a) #2
a+=10
print(a) #12
a-=2
print(a) #10
a*=2
print(a) #20
a/=5
print(a) #4.0
a%=5
print(a) #4.0
a**=3
print(a) #64.0
a//=3
print(a) #21.0

Bit wise Operators


a = 10
b=4
# Bitwise AND
print("Bitwise AND:", a & b)
# Bitwise OR
print("Bitwise OR:", a | b)
# Bitwise XOR
print("Bitwise XOR:", a ^ b)
# Bitwise NOT
print("Bitwise NOT of a:", ~a)
# Bitwise left shift
print("Bitwise left shift:", a << 1)
Record Programs DS, CS&IT

# Bitwise right shift


print("Bitwise right shift:", a >> 1)
#output:
Bitwise AND: 0
Bitwise OR: 14
Bitwise XOR: 14
Bitwise NOT of a: -11
Bitwise left shift: 20
Bitwise right shift: 5
Logical Operators
x=10
y=3
z=8
#logical operator using and
if x>y and x>z:
print("x is greater than y and z")
#logical operator using or
if x==y or x==z:
print("x is equal to either y or z")
#logical operator using not
if not(y>z):
print("y is not greater than z")
#output:
x is greater than y and z
y is not greater than z

Ternary Operator
a=17
b=15
print(b, "is greater") if b>a else print(a,"is greater")
#output:
17 is greater
Record Programs DS, CS&IT

Membership Operators
a=[1,2,5,7]
#membership operator using not in
print(4 not in a)
#membership operator using in
print(2 in a)
#output:
True
True

identity Operators
a=256
b=256
#identity operator using is
print(a is b)
#identity operator using is not
print(a is not b)
#output:
True
False

3. Python Program to Read a number n and Compute n+nn+nnn

# Read the number n from the user


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

# Compute nn and nnn


nn = int(str(n) + str(n)) # Concatenate n with itself to form nn
nnn = int(str(n) + str(n) + str(n)) # Concatenate n with itself twice to form nnn

# Compute the result


result = n + nn + nnn

# Display the result


Record Programs DS, CS&IT

print(f"The result of {n} + {nn} + nnn} is {result}.")

Output:
Enter a number: 5
The result of 5 + 55 + 555 is 615.

4. Python program to read a decimal number and print the binary, octal,
hexadecimal for the decimal equivalent value

# Read the decimal number from


decimal_number = int(input(" please tell me a decimal number: "))

# Convert decimal number to binary, octal, and hexadecimal


binary_number = bin(decimal_number)
octal_number = oct(decimal_number)
hexadecimal_number = hex(decimal_number)

# Display the conversions


print("Decimal:", decimal_number)
print("Binary:", binary_number)
print("Octal:", octal_number)
print("Hexadecimal:", hexadecimal_number)
Output:
please tell me a decimal number: 45
Decimal: 45
Binary: 0b101101
Octal: 0o55
Hexadecimal: 0x2d
5. Python program to swap two numbers with temp variable
Program:
# Taking input from user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

print("Before swapping:")
print("First number:", num1)
print("Second number:", num2)
Record Programs DS, CS&IT

# Swapping using a temporary variable


temp = num1
num1 = num2
num2 = temp

print("\nAfter swapping:")
print("First number:", num1)
print("Second number:", num2)
Output:
Enter first number: 10
Enter second number: 20
Before swapping:
First number: 10.0
Second number: 20.0

After swapping:
First number: 20.0
Second number: 10.0
6. Python program to swap two numbers without temp variable or any
arithmetic, bitwise operations

# Read two integers from the user


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

print("Before swapping:")
print("num1 =", num1)
print("num2 =", num2)

# Swap using tuple unpacking


(num1, num2) = (num2, num1)
Record Programs DS, CS&IT

print("After swapping:")
print("num1 =", num1)
print("num2 =", num2)

7. Python program to display calendar YYYY & MMs


Program:
import calendar

# Taking input from user for year and month


year = int(input("Enter the year (YYYY): "))
month = int(input("Enter the month (MM): "))

# Displaying the calendar for the specified year and month


print(f"\nCalendar for {year}-{month}:")
print(calendar.month(year, month))
Output:
Enter the year (YYYY): 1986 2022
Enter the month (MM): 12

Calendar for 2022-12:


December 2022
Mo Tu We Th Fr Sa Su
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

8. Write a program that asks the user to enter the width and length of a room.
Once the values have been read, your program should compute and display
the area of the room. (Formula = length*width
Program:
# Asking the user to enter the width and length of the room
Record Programs DS, CS&IT

width = float(input("Enter the width of the room (in meters): "))


length = float(input("Enter the length of the room (in meters): "))

# Computing the area of the room


area = length * width

# Displaying the area of the room


print("The area of the room is:", area, "square meters.")
Output:
Enter the width of the room (in meters): 50
Enter the length of the room (in meters): 25
The area of the room is: 1250.0 square meters.
9. Demonstrate print() function
a. Basic print statement
b. Printing multiple values separated by a space
c. Printing with end parameter
d. Printing with sep parameter
e. Formatting using string interpolation (f-strings)
f. Formatting using % operator
g. Formatting using format() method ( String format() Method)
h. Using positional arguments with format() method
i. Using keyword arguments with format() method
j. Using formatted string literals with expressions
k. Printing raw strings
l. Printing with escape characters
m. Printing multiple lines using triple quotes
Solution:
# Basic print statement
print("1. Basic print statement")
# Printing multiple values separated by a space
print("2.", "Printing", "multiple", "values", "separated", "by", "a", "space")

# Printing with end parameter


Record Programs DS, CS&IT

print("3. Printing with end parameter:", end=" ")


print("This will be printed on the same line.")

# Printing with sep parameter


print("4.", "Printing", "with", "sep", "parameter", sep="-")

# Formatting using string interpolation (f-strings)


name = "John"
age = 30
print(f"5. My name is {name} and I am {age} years old.")

# Formatting using % operator


num1 = 10
num2 = 3.14159
print("6. Value of num1 is %d and num2 is %.2f" % (num1, num2))

# Formatting using format() method


fruit = "apple"
quantity = 5
print("7. I have {} {}s.".format(quantity, fruit))

# Using positional arguments with format() method


print("8. I have {1} {0}s.".format(fruit, quantity))

# Using keyword arguments with format() method


print("9. I have {quantity} {fruit}s.".format(quantity=quantity, fruit=fruit))

# Using formatted string literals with expressions


print(f"10. The sum of {num1} and {num2} is {num1 + num2:.2f}")

# Printing raw strings


print(r"11. This is a raw string \n") # \n will be treated as characters, not a new line
Record Programs DS, CS&IT

# Printing with escape characters


print("12. This is an example of escape characters: \n\t- New line \n\t- Tab")

# Printing with Unicode characters


print("13. This is a Unicode character: \u2713")

# Printing with emojis (requires support for Unicode characters)


print("14. This is a smiley face emoji: \U0001F600")

# Printing with end-of-line


print("15. End-of-line will print automatically")

#Printing multiple lines using triple quotes


print('''This is line 1.
This is line 2.
And this is line 3.''')
Output:
1. Basic print statement
2. Printing multiple values separated by a space
3. Printing with end parameter: This will be printed on the same line.
4.-Printing-with-sep-parameter
5. My name is John and I am 30 years old.
6. Value of num1 is 10 and num2 is 3.14
7. I have 5 apples.
8. I have 5 apples.
9. I have 5 apples.
10. The sum of 10 and 3.14159 is 13.14
11. This is a raw string \n
12. This is an example of escape characters:
- New line
- Tab
13. This is a Unicode character: ✓
14. This is a smiley face emoji: 😀
Record Programs DS, CS&IT

15. End-of-line will print automatically


This is line 1.
This is line 2.
And this is line 3.

10. Generate two 4 digit random numbers and print the sum of them
Program:

# Generate two random 4-digit numbers


num1 = random.randint(1000, 9999)
num2 = random.randint(1000, 9999)

# Print the generated numbers


print("First random number:", num1)
print("Second random number:", num2)

# Calculate and print the sum of the two numbers


sum_of_numbers = num1 + num2
print("Sum of the two numbers:", sum_of_numbers)
Output:
First random number: 5837
Second random number: 8156
Sum of the two numbers: 13993

11.Python program to find the factorial of a number using a built in function.


Program:
import math

# Input a number from the user


num = int(input("Enter a number to find its factorial: "))

# Calculate factorial using math.factorial() function


factorial = math.factorial(num)
Record Programs DS, CS&IT

# Display the result


print(f"The factorial of {num} is: {factorial}")

Output:
Enter a number to find its factorial: 5
The factorial of 5 is: 120

Conditional Statements
12. Write a program to calculate roots of quadratic equation
Program:
import math
# Input coefficients
a = float(input("Enter the coefficient of x^2 (a): "))
b = float(input("Enter the coefficient of x (b): "))
c = float(input("Enter the constant term (c): "))

# Calculate the discriminant


discriminant = b**2 - 4*a*c

# Check if discriminant is zero


if discriminant == 0:
# Calculate equal roots
root = -b / (2*a)
print("Roots are equal:")
print("Root 1:", root)
print("Root 2:", root)
elif discriminant > 0:
# Calculate two real and distinct roots
root1 = (-b + math.sqrt(discriminant)) / (2*a)
root2 = (-b - math.sqrt(discriminant)) / (2*a)
print("Root 1:", root1)
print("Root 2:", root2)
else:
# Calculate two complex roots
real_part = -b / (2*a)
imaginary_part = math.sqrt(abs(discriminant)) / (2*a)
Record Programs DS, CS&IT

root1 = complex(real_part, imaginary_part)


root2 = complex(real_part, -imaginary_part)
print("Root 1:", root1)
print("Root 2:", root2)

Output:

Test case 1:

Enter the coefficient of x^2 (a): 1


Enter the coefficient of x (b): -2
Enter the constant term (c): 3
Root 1: (1+1.4142135623730951j)
Root 2: (1-1.4142135623730951j)

Test case 2:

Enter the coefficient of x^2 (a): 1


Enter the coefficient of x (b): -2
Enter the constant term (c): 1
Roots are equal:
Root 1: 1.0
Root 2: 1.0

Test case 3:

Enter the coefficient of x^2 (a): 1


Enter the coefficient of x (b): 2
Enter the constant term (c): 5
Root 1: (-1+2j)
Root 2: (-1-2j)

13. Write a python program to determine whether a given year is leap year or
not
Program:
# Input the year from the user
year = int(input("Enter a year: "))
Record Programs DS, CS&IT

# Check if the year is a leap year


if year % 4 == 0 and year % 100 != 0:
print(year, "is a leap year.")
elif year % 400 == 0:
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")

Output:

Test case 1:
Enter a year: 1990
1990 is not a leap year.

Test case 2:
Enter a year: 2000
2000 is a leap year.

14. Company decides to give bonus to all its employees on Diwali. a 5% bonus on
salary is given to the male workers and a 10% bonus on salary to the female
workers. Write a program to enter the salary and gender of the employee. If the
salary of the employee is less than Rs..10000, then the employee gets an extra
2% bonus on salary. Calculate the bonus that has to be given to the employee
and display the salary that the employee will get.
Program:
salary = float(input("Enter the salary of the employee: "))
gender = input("Enter the gender of the employee (Male/Female): ").lower()

bonus_percentage = 0

if salary < 10000:


bonus_percentage = 0.02

if gender== 'male':
bonus_percentage += 0.05
elif gender== 'female':
bonus_percentage += 0.1

bonus = salary * bonus_percentage


Record Programs DS, CS&IT

total_salary = salary + bonus


print("Total Bonus: ",bonus)
print("Total salary with bonus:", total_salary)

Output:

Test Case 1:
Enter the salary of the employee: 9999
Enter the gender of the employee (Male/Female): male
Total Bonus: 699.9300000000001
Total salary with bonus: 10698.93

Test Case 2:
Enter the salary of the employee: 9999
Enter the gender of the employee (Male/Female): M female
Total Bonus: 1199.88
Total salary with bonus: 11198.880000000001

Test Case 3:
Enter the salary of the employee: 12000
Enter the gender of the employee (Male/Female): male
Total Bonus: 600.0
Total salary with bonus: 12600.0

Test Case 4:
Enter the salary of the employee: 12000
Enter the gender of the employee (Male/Female): female3
Total Bonus: 1200.0
Total salary with bonus: 13200.0

15. Write a program that reads the lengths of 3 sides of a triangle from the user,
check whether a given triangle is scalene, equilateral, or isosceles
Program:
# Read lengths of sides from the user
side1 = float(input("Enter the length of the first side: "))
side2 = float(input("Enter the length of the second side: "))
side3 = float(input("Enter the length of the third side: "))
Record Programs DS, CS&IT

# Check if the lengths can form a triangle


if side1 + side2 > side3 and side1 + side3 > side2 and side2 + side3 > side1:
# Check the type of triangle
if side1 == side2 == side3:
print("It is an equilateral triangle.")
elif side1 == side2 or side1 == side3 or side2 == side3:
print("It is an isosceles triangle.")
else:
print("It is a scalene triangle.")
else:
print("The given lengths cannot form a triangle.")
Output:

Test Case 1:
Output:
Enter the length of the first side: 25
Enter the length of the second side: 26
Enter the length of the third side: 23
It is a scalene triangle.

Test Case 2:
Enter the length of the first side: 25
Enter the length of the second side: 25
Enter the length of the third side: 25
It is an equilateral triangle.

Test Case 3:
Enter the length of the first side: 25
Enter the length of the second side: 25
Enter the length of the third side: 30
It is an isosceles triangle.

Test Case 4:
Enter the length of the first side: 25
Enter the length of the second side: 25
Enter the length of the third side: 56
The given lengths cannot form a triangle.
Record Programs DS, CS&IT

16. Read a date and check whether the date is valid or not, if it is valid print
incremented date.. Otherwise, print “Invalid date”.

date = input("Enter date in dd/mm/yyyy format:\n")


count = date.count("/")

# Check if the given date has exactly 2 slash symbols


if count != 2:
print("Invalid date format, enter date as dd/mm/yyyy")
exit(0)

#Notes: The map() function in Python is a built-in function used to apply a given
function to #each item of an iterable (like a list, tuple, or string) and returns an
iterator that yields the #results.
#map(function, iterable)

dd, mm, yy = map(int, date.split('/'))

# Check for the total number of days in each month


if mm in [1, 3, 5, 7, 8, 10, 12]:
maxdays = 31
elif mm in [4, 6, 9, 11]:
maxdays = 30
else:
# Check for leap year to set February days
if yy % 4 == 0 and (yy % 100 != 0 or yy % 400 == 0):
maxdays = 29
else:
maxdays = 28

# Check for date validity


if dd < 1 or dd > 31 or mm < 1 or mm > 12 or yy < 0:
print("Invalid date")
# Increment days and months if months < 12 and days = maxdays
elif dd == maxdays and mm < 12:
dd = 1
mm += 1
print("Incremented date=", dd, "/", mm, "/", yy)
# Update days and months to 1 if months = 12 and days = maxdays
Record Programs DS, CS&IT

elif dd == maxdays and mm == 12:


dd = 1
mm = 1
yy += 1
print("Incremented date=", dd, "/", mm, "/", yy)
# Check for leap year if days exceed 29 in February month
elif dd > 29 and mm == 2:
print("Invalid date")
# Check for non-leap year if days exceed 28 in February month
elif dd > maxdays and mm == 2:
print("Invalid date")
# Check if days exceed 30 for months with maxdays = 30
elif dd > maxdays and mm in [4, 6, 9, 11]:
print("Invalid date")
else:
dd += 1
print("Incremented date=", dd, "/", mm, "/", yy)

Output:
Test Case 1:
Enter date in dd/mm/yyyy format:
18/12/2022
Incremented date= 19 / 12 / 2022

Test Case 2:
Enter date in dd/mm/yyyy format:
31/11/1992
Invalid date

17. Write a program that asks the user for two numbers and prints Close if the
numbers are within .001 of each other and Not close otherwise

# Input two numbers from the user


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

# Calculate the absolute difference between the two numbers


diff = round(abs(num1 - num2), 3)
Record Programs DS, CS&IT

# Check if the absolute difference is less than or equal to 0.001


if diff <= 0.001:
print("Close")
else:
print("Not close")

18. Write a program for simple calculator using if-elif-else statement


print("Simple Calculator")
print("Operations:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")

choice = input("Enter operation number (1/2/3/4): ")

#if choice in ('1', '2', '3', '4'):


if choice == '1' or choice == '2' or choice == '3' or choice == '4':
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
result = num1 + num2
print("Result:", result)
elif choice == '2':
result = num1 - num2
print("Result:", result)
elif choice == '3':
result = num1 * num2
print("Result:", result)
elif choice == '4':
if num2 != 0:
result = num1 / num2
print("Result:", result)
else:
print("Error! Division by zero.")
Record Programs DS, CS&IT

else:
print("Invalid input! Please enter a valid operation number (1/2/3/4).")

Output:
Test Case 1:
Simple Calculator
Operations:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter operation number (1/2/3/4): 1
Enter first number: 10
Enter second number: 20
Result: 30.0

Test Case 2:
Simple Calculator
Operations:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter operation number (1/2/3/4): 3
Enter first number: 20
Enter second number: 30
Result: 600.0

19. The year is divided into four seasons: spring, summer, fall and winter. While the
exact dates that the seasons change vary a little bit from year to year because of
the way that the calendar is constructed, we will use the following dates for this
exercise:
Season First day
Summer March 20
Spring June 21
Fall September 22
Winter December 21
Create a program that reads a month and day from the user. The user will enter
the name of the month as a string, followed by the day within the month as an
integer.
Then your program should display the season associated with the date that was
Record Programs DS, CS&IT

entered.
Note: Enter First three letter for month example: Jan for january, Feb for
February and so on....and first letter of the month should be capital

# Read month and day from the user


month = input("Enter the month (e.g., Jan, Feb, Mar, etc.): ")
day = int(input("Enter the day: "))

# Ensure only the first letter of the month is capitalized


month = month[:3].capitalize()

# Check the season based on the month and day


if (month == "Mar" and day >= 20) or (month == "Apr") or (month == "May") or
(month == "Jun" and day < 21):
season = "Spring"
elif (month == "Jun" and day >= 21) or (month == "Jul") or (month == "Aug") or
(month == "Sep" and day < 22):
season = "Summer"
elif (month == "Sep" and day >= 22) or (month == "Oct") or (month == "Nov") or
(month == "Dec" and day < 21):
season = "Fall"
elif (month == "Dec" and day >= 21) or (month == "Jan") or (month == "Feb") or
(month == "Mar" and day < 20):
season = "Winter"
else:
season = None

# Print the season if it's valid, otherwise print an error message


if season:
print(f"The season for {month} {day} is {season}.")
else:
print("Invalid input. Please enter a valid month abbreviation and day.")

Output:

Enter the month (e.g., Jan, Feb, Mar, etc.): dec


Enter the day: 12 8
The season for Dec 18 is Fall.

Iterative Statements

20. Write a program to enter a decimal number. Calculate and display the binary
Record Programs DS, CS&IT

equivalent of this number using iteration

dn = int(input("Enter a decimal number: "))


bn = ""
if dn == 0:
bn = "0"
else:
while dn> 0:
# Get the remainder when dividing by 2
remainder = dn % 2
# Prepend the remainder to the binary number string
bn = str(remainder) + bn
# Update the decimal number by integer division by 2
dn //= 2

print("The binary equivalent of", dn, "is:", bn)


Output:
Enter a decimal number: 36
The binary equivalent of 0 is: 100100

21. Write a program to find the sum of n natural numbers without using formula.

n = int(input("Enter the value of n: "))


sum_nn= 0

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


sum_nn += i

print("The sum of the first", n, "natural numbers is:", sum_nn)

Output:
Enter the value of n: 10
The sum of the first 10 natural numbers is: 55

22. Write a program to check whether the given two numbers is are“amicable”
numbers
#program to check whether two numbers are amicable or not
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
Record Programs DS, CS&IT

# Calculate the sum of proper divisors for num1


sum_div_num1 = 0
for i in range(1, num1):
if num1 % i == 0:
sum_div_num1 += i

# Calculate the sum of proper divisors for num2


sum_div_num2 = 0
for i in range(1, num2):
if num2 % i == 0:
sum_div_num2 += i

# Check if the numbers are amicable


if sum_div_num1 == num2 and sum_div_num2 == num1:
print("The numbers", num1, "and", num2, "are amicable.")
else:
print("The numbers", num1, "and", num2, "are not amicable.")

Output:

23. Write a program to check whether the given number is an “Armstrong number” or
not
#Amstrong or not
n=input("Enter n : ")
l=len(n)
n=int(n)
sum=0
ams=n
while n!=0:
r=n%10
sum=sum+r**l
n=n//10
if sum==ams:
print(f"The given number {ams} is Armstrong")
else:
Record Programs DS, CS&IT

print(f"The given number {ams} is not Armstrong")

24. Write a program to check whether the given number is an Strong number or not
import math
# Input number from user
number = int(input("Enter a number: "))
temp = number
s=0

# Calculate the sum of factorials of digits


while temp > 0:
digit = temp % 10
s += math.factorial(digit)
temp //= 10

# Check if the number is a strong number or not


if s == number:
print(number, "is a Strong number")
else:
print(number, "is not a Strong number")

Output:
Enter a number: 6
6 is not a Strong number

25. Write a program to check whether a given number is palindrome


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

# Read the number from user input


number = input("Enter a number: ")

# Convert the number to a string


num_str = str(number)
Record Programs DS, CS&IT

# Check if the string is equal to its reverse


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

Output:
Test Case 1:
Enter a number: 12221
12221 is a palindrome.

Test Case 2:
Enter a number: 123456
123456 is not a palindrome.

26. Write a program using a for loop to calculate the value of an investment. Input an
initial value of investment and annual interest, and calculate the value of
investment over time
initial_investment = float(input("Enter the initial investment amount: "))
annual_interest_rate = float(input("Enter the annual interest rate (in percentage):
"))
years = int(input("Enter the number of years: "))

# Convert annual interest rate from percentage to decimal


annual_interest_rate /= 100

# Calculate the value of the investment over time


for year in range(1, years + 1):
investment_value = initial_investment * (1 + annual_interest_rate) ** year
print(f"Year {year}: ${investment_value:.2f}")
Record Programs DS, CS&IT

Output:

27. Write a program to find sum of series 2+4+6+8+....n

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


total_sum = 0

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


total_sum += 2 * i

print("Sum of the series:", total_sum)

Output:
Enter the number of terms: 5
Sum of the series: 30

28. Write a program to calculate X power Y


Output:
Enter the base (X): 5
Enter the exponent (Y): 3
5.0 raised to the power of 3 is: 125.0
Record Programs DS, CS&IT

29. Write a program to print a multiplication table of a given number till m times.

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


limit = int(input("Enter the limit for the multiplication table: "))

print(f"Multiplication table for {number} up to {limit} times:")


for i in range(1, limit + 1):
print(f"{number} x {i} = {number * i}")

Output:
Enter a number: 5
Enter the limit for the multiplication table: 10
Multiplication table for 5 up to 10 times:
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

30. Read numbers until the user types “done”. Find the largest of the entered
numbers and sum of them.[ Note: Don’t use list]
l=0
s=0
done=False
while not done:
ip=input("Enter a number : ")
if ip.lower()=='done':
done=True
else:
n=int(ip)
l=max(l,n)
s=s+n
if s!=0:
Record Programs DS, CS&IT

print("largest..",l)
print("sum....",s)
else:
print("no numbers entered")

Output:
Enter a number : 1
Enter a number : 2
Enter a number : 3
Enter a number : done
largest.. 3
sum.... 6
31. Generate a random number between 1 and 10. Ask the user to guess the
number and print a message based on whether they get it right or not. Ask the
user to keep guessing till they get it right
import random
r=random.randint(1,10)
uans=int(input("Guess the random number generated between 1,10 : "))
while True:
if r==uans:
print("Congratulations.. your guess is right")
break
else:
print("Wrong guess..!")
uans=int(input("Enter a number between 1,10 to Guess again...! "))

32. Read x, y and print all prime numbers between x and y where x<=y

# Read x and y from user input


Record Programs DS, CS&IT

x = int(input("Enter the starting number (x): "))


y = int(input("Enter the ending number (y): "))

print(f"Prime numbers between {x} and {y}:")

# Iterate through the range between x and y


for num in range(x, y + 1):
# Prime numbers are greater than 1
if num > 1:
is_prime = True
# Check if num is divisible by any number from 2 to num-1
for i in range(2, num):
if num % i == 0:
is_prime = False
break
# If the number is prime, print it
if is_prime:
print(num)
Output:
Enter the starting number (x): 50
Enter the ending number (y): 100
Prime numbers between 50 and 100:
53
59
61
67
71
73
79
83
89
97

Strings and Regular Expressions

33. Write a Python program to demonstrate various ways of accessing the string.
a. By using Indexing (Both Positive and Negative)
# Define a sample string
text = "Hello, World!"
Record Programs DS, CS&IT

# Accessing using positive indexing


print("Accessing using positive indexing:")
for i in range(len(text)):
print("Character at index", i, ":", text[i])

# Accessing using negative indexing


print("\nAccessing using negative indexing:")
for i in range(-1, -len(text) - 1, -1):
print("Character at index", i, ":", text[i])

Outputs:
Accessing using positive indexing:
Character at index 0 : H
Character at index 1 : e
Character at index 2 : l
Character at index 3 : l
Character at index 4 : o
Character at index 5 : ,
Character at index 6 :
Character at index 7 : W
Character at index 8 : o
Character at index 9 : r
Character at index 10 : l
Character at index 11 : d
Character at index 12 : !

Accessing using negative indexing:


Character at index -1 : !
Character at index -2 : d
Character at index -3 : l
Character at index -4 : r
Character at index -5 : o
Character at index -6 : W
Character at index -7 :
Character at index -8 : ,
Character at index -9 : o
Character at index -10 : l
Character at index -11 : l
Record Programs DS, CS&IT

Character at index -12 : e


Character at index -13 : H

b. By using slicing operation


# Define a sample string
text = "Python is awesome!"

# All possible examples of slicing


# Whole string
print("Whole string:", text[:])
print()

# Reverse string
print("Reverse string:", text[::-1])
print()

# First 5 characters
print("First 5 characters:", text[:5])
print()

# Last 7 characters
print("Last 7 characters:", text[-7:])
print()

# Substring "is aw"


print("Substring 'is aw':", text[6:11])
print()

# All except last 3 characters


print("All except last 3 characters:", text[:-3])
print()

# From index 7 to end


print("From index 7 to end:", text[7:])
print()

# From beginning to index 6


print("From beginning to index 6:", text[:7])
print()
Record Programs DS, CS&IT

# Last 3 characters
print("Last 3 characters:", text[-3:])
print()

# Substring "is a"


print("Substring 'is a':", text[-7:-3])
print()

# Substring "is awe"


print("Substring 'is awe':", text[7:13])
print()

# Every third character


print("Every third character:", text[::3])
print()

# Characters at even indices up to index 5


print("Characters at even indices up to index 5:", text[:6:2])
print()

# Reverse every second character


print("Reverse every second character:", text[-1::-2])
print()

# Characters from index 7 onwards, every second character


print("Characters from index 7 onwards, every second character:",
text[7::2])
print()

# Characters at indices 0, 3, and 6


print("Characters at indices 0, 3, and 6:", text[:7:3])
print()

# Reverse all except the last 3 characters


print("Reverse all except the last 3 characters:", text[-3::-1])
Output:

Whole string: Python is awesome!


Record Programs DS, CS&IT

Reverse string: !emosewa si nohtyP

First 5 characters: Pytho

Last 7 characters: wesome!

Substring 'is aw': is a

All except last 3 characters: Python is aweso

From index 7 to end: is awesome!

From beginning to index 6: Python

Last 3 characters: me!

Substring 'is a': weso

Substring 'is awe': is awe

Every third character: Ph em

Characters at even indices up to index 5: Pto

Reverse every second character: !msw inhy

Characters from index 7 onwards, every second character: i wsm!

Characters at indices 0, 3, and 6: Ph

Reverse all except the last 3 characters: mosewa si nohtyP

34. Demonstrate the following functions/methods which operates on strings in


Python with suitable examples:
i) len( )
s1 = ‘Python Programming’
print(len(s1)) #18
Record Programs DS, CS&IT

ii) strip( )
s1=' Python '
print(s1.strip()) #Python
iii) rstrip( )
s1=' Python '
print(s1.rstrip()) #( Python)
iv) lstrip( )
s1=' Python '
print(s1.lstrip()) #(Python )

v) find( )
s1='Print Hello World in Python'
print(s1.find('Hello',0,len(s1))) #6

vi) rfind( )
s1 = 'Print Hello World in Python'
print(s1.rfind('o')) # Output: 25
vii) index( )
s1='Print Hello World in Python'
print(s1.index('in',0,len(s1)))
Output: 3
print(s1.index('of',0,len(s1)))
Output: ValueError: substring not found

viii) rindex()
s1='Print Hello World in Python'
print(s1.rindex(‘o’,0,len(s1)))
#Output - 25
(finds the index of last occurrence of the character ‘o’ in string s1)
ix) count( )
s1=' Print Hello World in Python'
Record Programs DS, CS&IT

print(s1.count(‘o’))
#Output: 3
(returns number of time ‘o’ occurred in string s1)

x) replace( )
s1=' Print Hello World in Python'
print(s1.replace(‘Hello’, ‘Hi’,1))
#Print Hi World in Python
(replaces Hello with Hi)

xi) split( )
s1 = 'Print Hello World in Python'
# Splitting s1 into individual variables using whitespace as delimiter
word1, word2, word3, word4, word5 = s1.split(sep=’ ‘,maxsplit=4)
# Printing each variable separately
print(word1) # Output: Print
print(word2) # Output: Hello
print(word3) # Output: World
print(word4) # Output: in
print(word5) # Output: Python

xii) join( )
s1 = 'Print Hello World in Python'
word1, word2, word3, word4, word5 = s1.split(maxsplit=4)
# Printing each variable separately
print(word1) # Output: Print
print(word2) # Output: Hello
print(word3) # Output: World
print(word4) # Output: in
print(word5) # Output: Python
# Joining the words back together using space as separator
new_s1 = ' '.join([word1, word2, word3, word4, word5])
Record Programs DS, CS&IT

print(new_s1) # Output: Print Hello World in Python


# Joining the words back together using hyphen as separator
new2_s1 = '-'.join([word1, word2, word3, word4, word5])
print(new2_s1) # Output: Print-Hello-World-in-Python
xiii) upper( )
str=’python programming’
print(str.upper()) #PYTHON PROGRAMMING
xiv) lower( )
str=’pyTHon’
print(str.lower()) #python
xv) swapcase( )
str=’Data Science’
print(str.swapcase()) #dATA sCIENCE
xvi) title( )
str=”python programming
print(str.title()) #Python Programming
xvii) capitalize( )
str=”hello world”
print(str.capitalize()) #Hello world

xviii) startswith()
str = 'PNR sir is good'
# Check if the string starts with "PNR" starting from index 0 to the end of
str
print(str.startswith("PNR", 0, len(str))) # Output: True

xix) endswith()
str=’DS students are good’
print(str.endswith(“DS”,0,len(str))) #False

35. Write a program that counts the occurrences of a character in a string. Do not
Record Programs DS, CS&IT

use built-in count functions.

# Input string
s = input("Enter a string: ")
# Character to count (convert to lowercase for case-insensitive comparison)
c = input("Enter a character to count: ").lower()
# Convert the input string to lowercase for case-insensitive comparison
s_lower = s.lower()

# Count variable to store the occurrences


count = 0

# Iterate through each character in the lowercase string


for char in s_lower:
# Check if the character matches the one we're counting (also converted to
lowercase)
if char == c:
# Increment the count if it matches
count += 1

# Print the result


print(f"The character '{c}' appears {count} times in the string.")

Output:

Enter a string: Python Programming


Enter a character to count: p
The character 'p' appears 2 times in the string.

36. Count the number of alphabets, consonants, vowels, digits, special characters in
a sentence
Program:
# Input sentence
sentence = input("Enter a sentence: ")

# Initialize counts
alphabets = 0
Record Programs DS, CS&IT

vowels = 0
consonants = 0
digits = 0
special_characters = 0

# Iterate through each character in the sentence


for char in sentence:
# Check if the character is an alphabet
if char.isalpha():
alphabets += 1
# Check if the alphabet is a vowel
if char.lower() in 'aeiou':
vowels += 1
else:
consonants += 1
# Check if the character is a digit
elif char.isdigit():
digits += 1
# Otherwise, it's a special character
else:
special_characters += 1

# Print the counts


print("Number of alphabets:", alphabets)
print("Number of vowels:", vowels)
print("Number of consonants:", consonants)
print("Number of digits:", digits)
print("Number of special characters:", special_characters)

Output:

Enter a sentence: Python Programming


Number of alphabets: 17
Number of vowels: 4
Number of consonants: 13
Number of digits: 0
Number of special characters: 1
Record Programs DS, CS&IT

37. To display which Letters are in the First String but not in the Second.
Program:
# Input strings
s1 = input("Enter the first string: ")
s2 = input("Enter the second string: ")

# Convert both strings to sets to easily find the difference


set1 = set(s1)
set2 = set(s2)

# Find the letters in the first string but not in the second
result = set1 - set2

# Print the result


print(f"Letters in the first string but not in the second: {result}")

Output:

Enter the first string: Python


Enter the second string: Programming
Letters in the first string but not in the second: {'h', 't', 'y'}

38. Python program to demonstrate the comparison of strings


# Define two strings
string1 = "hello"
string2 = "world"
string3 = "hello"

# Equality
print("Equality:")
if string1 == string3:
print("The strings are equal.")
else:
print("The strings are not equal.")

# Inequality
print("\nInequality:")
Record Programs DS, CS&IT

if string1 != string2:
print("The strings are not equal.")
else:
print("The strings are equal.")

# Greater than
print("\nGreater than:")
if string1 > string2:
print("string1 is greater than string2.")

else:
print("string1 is not greater than string2.")

# Less than
print("\nLess than:")
if string1 < string2:
print("string1 is less than string2.")

else:
print("string1 is not less than string2.")

# Greater than or equal to


print("\nGreater than or equal to:")
if string1 >= string2:
print("string1 is greater than or equal to string2.")

else:
print("string1 is not greater than or equal to string2.")

# Less than or equal to


print("\nLess than or equal to:")
if string1 <= string2:
print("string1 is less than or equal to string2.")

else:
print("string1 is not less than or equal to string2.")

Output:
Record Programs DS, CS&IT

Equality:
The strings are equal.

Inequality:
The strings are not equal.

Greater than:
string1 is not greater than string2.

Less than:
string1 is less than string2.

Greater than or equal to:


string1 is not greater than or equal to string2.

Less than or equal to:


string1 is less than or equal to string2.

Notes:
These comparisons are based on the lexicographical order of the strings, which
is determined by comparing their characters' Unicode values from left to right. If a
character in string1 has a greater Unicode value than the corresponding
character in string2, string1 is considered greater. If all characters match but one
string is longer, the longer string is considered greater.

39. Program to create a regular expression to search for strings starting with m and
having total 3 characters using search(), match()
Program:
import re

# Define the regular expression pattern


pattern = r'\bm\w{2}\b'

# Single string to search through


string = 'tap mat mop mango man bat batman'

# Search for strings starting with 'm' and having a total of 3 characters using
search()
Record Programs DS, CS&IT

print("Using search():")
result = re.search(pattern, string)
print(result)

# Match for strings starting with 'm' and having a total of 3 characters using
match()
print("\nUsing match():")
result = re.match(pattern, string)
print(result)

Output:
Using search():
<re.Match object; span=(4, 7), match='mat'>

Using match():
None

40. Program to create a regular expression to split a string into pieces where one or
more non
alphanumeric characters are found
Program:
import re

# Define the regular expression pattern to match one or more non-alphanumeric


characters
pattern = r'\W+'

# Input string
string = "Hello! How are you? I'm fine, thank you @."

# Split the string into pieces using the regular expression pattern
pieces = re.split(pattern, string)

# Print the pieces


print("Pieces after splitting the string:")
for i in pieces:
print(i)
Record Programs DS, CS&IT

Output:

Pieces after splitting the string:


Hello
How
are
you
I
m
fine
thank
you

41. Python program to create a regular expression to replace a string with a new
string -Demonstration of re.sub()
Program:
import re

# Original string
original_string = "The quick brown fox jumps over the lazy dog."

# Define the regular expression pattern to match 'fox'


pattern = r'fox'

# Define the new string to replace 'fox' with


new_string = "cat"

# Replace 'fox' with 'cat' using re.sub()


result_string = re.sub(pattern, new_string, original_string)

# Print the result


print("Original string:", original_string)
print("After replacement:", result_string)
Output:

Original string: The quick brown fox jumps over the lazy dog.
After replacement: The quick brown cat jumps over the lazy dog.
Record Programs DS, CS&IT

42. Write a Python program that uses regular expressions to retrieve all words
starting with "a" in a given string using re.findall() and re.finditer(). Additionally,
demonstrate the use of capturing groups while using the re.finditer() method.
import re

# Input string
s = "apple and banana are fruits, while avocado is a vegetable."

# Define the regular expression pattern to match words starting with 'a'
p = r'\b(a\w+)'

print("Retrieve all words starting with 'a' using re.findall()")


m = re.findall(p, s)
print(m)

print("Retrieve all words starting with 'a' using re.finditer()")


m = re.finditer(p, s)

# Print words found using re.finditer() along with other match object methods
print("Words starting with 'a' (using re.finditer()):")
for match in m:
w = match.group() # Get the matched word
print("Matched Word:", w)
print("Matched Word Index (start):", match.start())
print("Matched Word Index (end):", match.end())
print("Matched Word Index (start, end):", match.span())
print("Matched Word (full match):", match.group(0)) # Same as match.group()
print("Captured groups (if any):", match.groups())
print()

Output:

Retrieve all words starting with 'a' using re.findall()


['apple', 'and', 'are', 'avocado']
Retrieve all words starting with 'a' using re.finditer()
Words starting with 'a' (using re.finditer()):
Matched Word: apple
Matched Word Index (start): 0
Record Programs DS, CS&IT

Matched Word Index (end): 5


Matched Word Index (start, end): (0, 5)
Matched Word (full match): apple
Captured groups (if any): ('apple',)

Matched Word: and


Matched Word Index (start): 6
Matched Word Index (end): 9
Matched Word Index (start, end): (6, 9)
Matched Word (full match): and
Captured groups (if any): ('and',)

Matched Word: are


Matched Word Index (start): 17
Matched Word Index (end): 20
Matched Word Index (start, end): (17, 20)
Matched Word (full match): are
Captured groups (if any): ('are',)

Matched Word: avocado


Matched Word Index (start): 35
Matched Word Index (end): 42
Matched Word Index (start, end): (35, 42)
Matched Word (full match): avocado
Captured groups (if any): ('avocado',)

Functions and Modules:

43. Write a function to compute gcd of 2 numbers

def gcd(a, b):


#Compute the greatest common divisor (gcd) of two numbers using the
Euclidean algorithm.

# Handle edge cases where either a or b is zero


if a == 0:
Record Programs DS, CS&IT

return b
if b == 0:
return a

# Ensure a >= b
if b > a:
a, b = b, a

# Euclidean algorithm
while b:
a, b = b, a % b
return a

# Read num1 and num2 from user input


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

# Print the gcd of num1 and num2 using the function


print("The gcd of", num1, "and", num2, "is:", gcd(num1, num2))
Output:
Enter the first number: 10
Enter the second number: 55
The gcd of 10 and 55 is: 5

44. Write a function to find the Factorial of a given integer


# Function to compute factorial
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
Record Programs DS, CS&IT

return result

# Ask the user for input and convert to int in one line
num = int(input("Enter an integer to compute its factorial: "))

# Check if the input is non-negative


if num < 0:
print("Factorial is not defined for negative numbers.")
else:
# Compute and print factorial
result = factorial(num)
print("Factorial of", num, "is:", result)
Output:
Enter an integer to compute its factorial: 5
Factorial of 5 is: 120
45. Write a function to generate Fibonacci series till n terms
def fib(n):

fs = [0, 1]

for i in range(2, n):


next_fib = fs[-1] + fs[-2]
fs.append(next_fib)

return fs

# Read the value of n from the user


n = int(input("Enter the number of terms for the Fibonacci series: "))
# Generate and print the Fibonacci series up to n terms
fib_series = fib(n)
Record Programs DS, CS&IT

print(f"The Fibonacci series up to {n} terms is:", fib_series)


Output:
Enter the number of terms for the Fibonacci series: 8
The Fibonacci series up to 8 terms is: [0, 1, 1, 2, 3, 5, 8, 13]
46. Write a function that reads a integer and displays the sum of its individual digits
#Function that reads a integer and displays the sum of its individual digits
def sum_of_digits(n):
# Convert the integer to a string to iterate over its digits
n_str = str(n)

sum = 0

# Iterate over each character (digit) in the string representation of the integer
for dc in n_str:
# Convert the character (digit) back to an integer and add it to the sum
sum += int(dc)
return sum

# Ask the user for input


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

# Calculate and display the sum of digits


print("Sum of digits:", sum_of_digits(n))
Output:
Enter an integer: 5986
Sum of digits: 28

47. Write a program to double a given number using lambda()


# Define the lambda function to double a number
n = lambda x: x * 2
Record Programs DS, CS&IT

# Input the number from the user


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

# Double the number using the lambda function


result = n(number)

# Print the result


print("The doubled number is:", result)
Output:
Enter a number: 6
The doubled number is: 12

48. Assume you have a module called fact_fib, consisting of two functions called
fact() and fib(). Write a program to calculate the factorial of a given number by
importing only fact() from the above module.
File: fact_fib.py
def fact(n):
factorial = 1
for i in range(1, n + 1):
factorial *= i
return factorial

def fib(n):

fs = [0, 1]

for i in range(2, n):


next_fib = fs[-1] + fs[-2]
Record Programs DS, CS&IT

fs.append(next_fib)
return fs
File: f.py
# Importing only the fact() function from the fact_fib module
from fact_fib import fact

# Read the number from the user


n = int(input("Enter a number to calculate its factorial: "))

# Calculate and print the factorial of the number using the imported fact() function
factorial = fact(n)
print("The factorial of", n, "is:", factorial)
Output:
Enter a number to calculate its factorial: 5
The factorial of 5 is: 120
49. Write a program to demonstrate local, enclosing, global, built-in scopes
#example program to demonstrate local, enclosing, global, built-in scopes
# Global scope
global_variable = "I am in the global scope"

def outer_function():
# Enclosing scope
enclosing_variable = "I am in the enclosing scope"

def inner_function():
# Local scope
local_variable = "I am in the local scope"

# Accessing variables from different scopes


print("Inside inner_function:")
Record Programs DS, CS&IT

print("Local variable:", local_variable)


print("Enclosing variable:", enclosing_variable)
print("Global variable:", global_variable)
print("Built-in function:", len("built-in"))

inner_function()

# Calling the outer function


outer_function()

# Accessing global variable outside the function


print("Outside the function:")
print("Global variable:", global_variable)
Output:
Inside inner_function:
Local variable: I am in the local scope
Enclosing variable: I am in the enclosing scope
Global variable: I am in the global scope
Built-in function: 8
Outside the function:
Global variable: I am in the global scope

50. Write a recursive function to compute gcd of two numbers


def gcd(a, b):

if a == 0:
return b
elif b == 0:
return a
elif a < b:
Record Programs DS, CS&IT

return gcd(b, a) # Swap a and b if a is smaller than b


else:
return gcd(b, a % b) # Continue with the remainder as b

# Read num1 and num2 from user input


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

# Compute and print the gcd of num1 and num2 using the function
print("The gcd of", num1, "and", num2, "is:", gcd(num1, num2))
Output:
Enter the first number: 55
Enter the second number: 50
The gcd of 55 and 50 is: 5
51. Write a recursive function to find the Factorial of a given integer

def fact(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case: factorial of n is n multiplied by factorial of (n-1)
else:
return n * fact(n - 1)

# Take input from the user


number = int(input("Enter a non-negative integer: "))

# Check if the input is a non-negative integer


if number < 0:
print("Please enter a non-negative integer.")
Record Programs DS, CS&IT

else:
print("Factorial of", number, "is", fact(number))
Output:
Enter a non-negative integer: 5
Factorial of 5 is 120
52. Write a recursive function to generate Fibonacci series till n terms
def fb(n):
if n <= 0:
return 0
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fb(n - 1) + fb(n - 2)

num = int(input("Enter the number of terms for Fibonacci series: "))


print("Fibonacci series up to", num, "terms:")
for i in range(1, num + 1):
print(fb(i), end=" ")

Output:
Enter the number of terms for Fibonacci series: 9
Fibonacci series up to 9 terms:
0 1 1 2 3 5 8 13 21

You might also like