Record Programs Till Functions
Record Programs Till Functions
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
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
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
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
print("Before swapping:")
print("First number:", num1)
print("Second number:", num2)
Record Programs DS, CS&IT
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
print("Before swapping:")
print("num1 =", num1)
print("num2 =", num2)
print("After swapping:")
print("num1 =", num1)
print("num2 =", num2)
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
10. Generate two 4 digit random numbers and print the sum of them
Program:
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): "))
Output:
Test case 1:
Test case 2:
Test case 3:
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
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 gender== 'male':
bonus_percentage += 0.05
elif gender== 'female':
bonus_percentage += 0.1
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
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”.
#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)
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
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
Output:
Iterative Statements
20. Write a program to enter a decimal number. Calculate and display the binary
Record Programs DS, CS&IT
21. Write a program to find the sum of n natural numbers without using formula.
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
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
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
Output:
Enter a number: 6
6 is not a Strong number
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: "))
Output:
Output:
Enter the number of terms: 5
Sum of the series: 30
29. Write a program to print a multiplication table of a given number till m times.
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
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
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 : !
# 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()
# Last 3 characters
print("Last 3 characters:", text[-3:])
print()
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
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
# 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()
Output:
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
Output:
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: ")
# Find the letters in the first string but not in the second
result = set1 - set2
Output:
# 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.")
else:
print("string1 is not greater 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.
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
# 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
# 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)
Output:
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."
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 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:
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
return result
# Ask the user for input and convert to int in one line
num = int(input("Enter an integer to compute its factorial: "))
fs = [0, 1]
return fs
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
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]
fs.append(next_fib)
return fs
File: f.py
# Importing only the fact() function from the fact_fib module
from fact_fib import fact
# 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"
inner_function()
if a == 0:
return b
elif b == 0:
return a
elif a < b:
Record Programs DS, CS&IT
# 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)
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)
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