You are on page 1of 23

Practical:2

Aim:- Write a program to read your name, contact number, email, and birthdate and print
those details on the screen.

print("Enter your name: ", end="")


name = input()
print("Enter your contact: ", end="")
contact = input()
print("Enter your email: ", end="")
email = input()
print("Enter your birthday: ", end="")
birthday = input()

print("Name: ", name)


print("Contact: ", contact)
print("Email: ", email)
print("Birthday: ", birthday)

output:-

Or
print("bhavika Patel")
print("1234567890")
print("abc@gmail.com")
print("21-03-2005")

output:-
Practical:4.1
Aim:A year is a Leap year if it is divisible by 4, unless it is a century year that is not
divisible by 400 (1800 and 1900 are not leap years, 1600 and 2000 are leap years). Write a
program that calculates whether a given year is a leap year or not.

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


if (year%4==0 and year%400 != 0 or year%100==0):
print("The year is Leap Year")
else:
print("The year is Non-Leap Year")

output:-

Practical:4.2
Aim:Many companies pay time-and-a-half for any hours worked above 40 hours in a
given week. Write a program to input the number of hours worked and hourly rate and
calculate the total wages for the week.

hours = float(input("Enter the number of hours worked: "))


rate = float(input("Enter the hourly rate: "))
if hours > 40:
total = 40 * rate + (hours - 40) * rate * 1.5
else:
total = hours * rate
print("The total wages for the week is: ", total)

output:-
Practical : 4.3
Aim:The Body Mass Index (BMI) is calculated as a person's weight (in kg), divided by the
square of the person's height (in meters). If the BMI is between 19 and 25, the person is
healthy. If the BMI is below 19, then the person is underweight. If the BMI is above 25,
then the person is overweight. Write a program to get a person's weight (in kgs) and
height (in cms) and display a message whether the person is healthy, underweight or
overweight.

𝐵𝑀𝐼 = 𝑊𝑒𝑖𝑔ℎ𝑡 𝑖𝑛 𝑘𝑔/(𝐻𝑒𝑖𝑔ℎ𝑡 𝑖𝑛 𝑚)2


print("This program will calculate your BMI.")
weight = float(input("Enter your weight in kilograms: "))
height = float(input("Enter your height in meters: "))
bmi = weight / (height ** 2)
if bmi < 19:
print("You are underweight.")
elif bmi > 25:
print("You are overweight.")
else:
print("You are healthy.")
output:-
Practical :- 4.4
Aim:-Write a program to read the marks and assign a grade to a student. Grading system: A
(>=90), B (80-89), C (70-79), D (60-69), E (50-59), F (<50). (Use the Switch case)

marks = float(input("Enter the marks obtained by the student: "))

grade = None

def switch_case(marks):

switcher = {

10: "A",

9: "A",

8: "B",

7: "C",

6: "D",

5: "E",

4: "F",

3: "F",

2: "F",

1: "F",

0: "F"

return switcher.get(marks // 10, "Invalid Marks")

grade = switch_case(marks)

print("The grade assigned to the student is:", grade)


output:-
Practical :-6
Aim:-i. Write a program to perform the below operations on the list:
 Create a list.
 Add/Remove an item to/from a list.
 Get the number of elements in the list.
 Access elements of the list using the index.
 Sort the list.
 Reverse the list.

 Create a list
list1 = [1, 2, "Python", "Program", 15.9]
list2 = ["bhavi", "swara", "gehna", "jigs"]
print(list1)
print(list2)
 Output:-
 Add/Remove an item to/from a list.
# Define the list
list = ['Cake', 'Pizza', 'Juice', 'Pasta', 'Burger']

# Print the list before delete


print("List before delete")
print(list)

# Remove an item
list.remove('Juice')

# Print the list after delete


print("List after delete")
print(list)

output:-

 Get the number of elements in the list.


elem_list = [1, 2, 3, 4]

print(elem_list)

# using the len() which return the number


# of elements in the list
print("No of elements in list are:", len(elem_list))

 output:
Or
a = [1, 0.1,'hello', True]
print("The created list is :")
print(a)

print(len(a))
 output:-

 Access elements of the list using the index.


a = [1, 0.1,'hello', True]

print(a[1])
print(a[1:3])
print(a[-2])

 output:-

 Sort the list.


a = [20, 50, 10, 30, 60]
a.sort()
print(a)
print()

b = ['P', 'Y', 'T', 'H', 'O', 'N']


b.sort()
print(b)

 Output:-

6.2
 NUMBER OF POSITIVE NUMBER AND NUMBER OF NEGATIVE
NUMBER
num = float(input("Enter the number : "))
if num > 0:
print("Positive Number")
elif num == 0:
print("Zero")
else:
print("Negative Number")
OUTPUT:

Write a program to read n numbers from a user and print: Number of even
and odd numbers.
num = float(input("Enter the Number : "))
if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")
Pr 6.2.1
Write a program to read n numbers from a user and print: Number of
positive , negative and zero numbers.
num = float(input("Enter the number : "))
if num > 0:
print("Positive Number")
elif num == 0:
print("Zero")
else:
print("Negative Number")

Output:-
Pr 6.2.2
Aim :- Write a program to read n numbers from a user and print:
Number of even and odd numbers.
num = float(input("Enter the Number : "))
if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")
output:-

Practical 6.2.3
Aim :- Write a program to read n numbers from a user and print:
Average of Number.
num = int(input("How many number to be entered = "))
total_sum = 0
for n in range(num):
numbers = float(input("Enter a Number : "))
total_sum += numbers
avg = total_sum / num
print("Average of ",num, "Number is : ",avg)
output:-
Practical 6.3
Write a program that counts the occurrences of each digit in a string.
The program counts how many times a digit appears in the string. For
example, if the input is "12203AB3", then the output should output 0
(1 time), 1 (1 time), 2 (2 times), 3 (2 times).
a="12203AB3"
for i in range(4):
x=a.count(str(i))
print(i,"is featured for ",x,"number of times in a string")
output:-

Practical 6.4
Aim:- Write a program to eliminate duplicate values in the list.
duplicate=[2,4,10,20,5,2,20,4]
print(list(set(duplicate)))

output:-
Practical 6.5
Aim:- Write a program to randomly fill in 0s and 1s into a 4x4 2-dimension list, print the list and
find the rows and columns with the most number of 1s.

l = []

m = []

x=0

for k in range(4):

for g in range(4):

m.append(int(input('Enter Element')))

l.append(m[x:x+4])

x += 4

for i in l:

print(i)

print()

# Print the list and find the rows and columns with the most number of 1s

max_row = 0

max_col = 0

row_no = 0

col_no = 0
for i in range(4):

row = 0

col = 0

for j in range(4):

if l[i][j] == 1:

row += 1

if l[j][i] == 1:

col += 1

if row > max_row:

max_row = row

row_no = i

if col > max_col:

max_col = col

col_no = i

print("Row with the most number of 1s is row", row_no, "with", max_row, "1s")

print("Column with the most number of 1s is column", col_no, "with", max_col, "1s")
output:-
Practical 8.1
Function
i. Write a program that defines a function (shuffle) to scramble a list into a random order, like
shuffling a deck of cards.

L=[1,4,6,7,9]
print("Original List : ",L)
import random
def shuffle(L):
random.shuffle(L)
print("Shuffled List : ",L)
shuffle(L)
output:-

Practical 8.2
. Write a program that defines a function to return a new list by eliminating the duplicate values
in the list.

L1=[1, 2, 3, 4, 5, 1, 4, 2, 5, 6, 7, 8, 9]
print("Original List : ")
print(L1)
def eliminate(L1):
L2=[]
for i in L1:
if i not in L2:
L2.append(i)
print("Eliminated List : ")
print(L2)
eliminate(L1)

output:-

Or
n = int(input("Enter number of elements: "))
l = []
for i in range(n):
l.append(int(input("Enter element: ")))
print("List before removing duplicates: ", l)
for i in l:
if l.count(i) > 1:
l.remove(i)
print("List after removing duplicates: ", l)

output:-

Practical 8.3
Aim:- . Write a program to print Fibonacci sequence up to n numbers using recursion.
Fibonacci sequence is defined as below:

𝐹𝑖𝑏𝑜𝑛𝑎𝑐𝑐𝑖 𝑆𝑒𝑞𝑢𝑒𝑛𝑐𝑒= 1 1 2 3 5 8 13 21… 𝑤ℎ𝑒𝑟𝑒 𝑛𝑡ℎ𝑡𝑒𝑟𝑚 𝑥n= 𝑥n-1+ 𝑥n-2

# Python program to display the Fibonacci sequence

def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10

# check if the number of terms is valid


if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
output:-

Practical 8.4:-
Aim:- . Write a program that defines a function to determine whether input number n is
prime or not. A positive whole number n > 2 is prime, if no number between 2 and √𝑛
(inclusive) evenly divides n. If n is not prime, the program should quit as soon as it finds a
value that evenly divides n.
import math

def is_prime(n):
if n <= 1:
return False
if n == 2:
return True

for i in range(2, math.isqrt(n) + 1):


if n % i == 0:
return False
return True

# Example usage
num = int(input("Enter a number: "))

if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
output:-
Practical:8.5
Aim:- Write a program that defines a function to find the GCD of two numbers using the
algorithm below. The greatest common divisor (GCD) of two values can be computed
using Euclid's algorithm. Starting with the values m and n, we repeatedly apply the
formula: n, m = m, n%m until m is 0. At that point, n is the GCD of the original m and n
(Use Recursion).

def gcd(a, b):


if b == 0:
return a
else:
return gcd(b, a % b)

if __name__ == "__main__":
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print("The greatest common divisor of", a, "and", b, "is", gcd(a, b))
output:-

Practical: 8.6
Aim:- Write a program that lets the user enter the loan amount, number of years, and interest
rate, and defines a function to calculate monthly EMI, total payment and display the
amortization schedule for the loan.
def emi(loan_amount, no_of_years, interest_rate):
interest_rate = interest_rate / (12 * 100)
no_of_months = no_of_years * 12

# return monthly EMI, total payment and display the amortization schedule for the loan
emi = (loan_amount * interest_rate * (1 + interest_rate) ** no_of_months) / ((1 +
interest_rate) ** no_of_months - 1)
total_payment = emi * no_of_months

# display the amortization


amortization_schedule = []
while no_of_months > 0:
interest = loan_amount * interest_rate
principal = emi - interest
loan_amount = loan_amount - principal
print(f"Interest: {interest:.2f}, Principal: {principal:.2f}, Loan Amount: {loan_amount:.2f}")
no_of_months -= 1

return emi, total_payment

if __name__ == "__main__":
loan_amount = float(input("Enter the loan amount: "))
no_of_years = float(input("Enter the number of years: "))
interest_rate = float(input("Enter the interest rate: "))
emi, total_payment = emi(loan_amount, no_of_years, interest_rate)
print("Monthly EMI: ", emi)
print("Total payment: ", total_payment)
Output:-

Practical:-10.1
Aim:- Write a program to check whether a given string is palindrome or not.

def is_palindrome(s):
# Removing spaces and converting the string to lowercase
s = s.replace(" ", "").lower()
# Checking if the string is equal to its reverse
return s == s[::-1]

# Taking input from the user


input_string = input("Enter a string: ")

# Checking if the input string is a palindrome or not


if is_palindrome(input_string):
print("The entered string is a palindrome.")
else:
print("The entered string is not a palindrome.")
Output:-

Practical:10.2
Aim:- Write a program to read a string containing letters, each of which may be in either
uppercase or lowercase, and return a tuple containing the number of vowels and
consonants in the string.
def count_vowels_and_consonants(s):
vowels = "aeiouAEIOU"
# Count variables for vowels and consonants
num_vowels = 0
num_consonants = 0

# Iterate through the characters in the input string


for char in s:
# Check if the character is a letter
if char.isalpha():
# Check if the letter is a vowel
if char in vowels:
num_vowels += 1
else:
num_consonants += 1

# Return a tuple containing the count of vowels and consonants


return num_vowels, num_consonants

# Taking input from the user


input_string = input("Enter a string: ")

# Calling the function and displaying the result


vowels, consonants = count_vowels_and_consonants(input_string)
print(f"Number of vowels: {vowels}")
print(f"Number of consonants: {consonants}")

Output:-
Practical:10.3

Aim:- Write a program to read a date in the format DD/MM/YYYY and print the same date in
MM-DD-YYYY format.
print("Enter date in format dd/mm/yyyy")
date = input("Enter date: ")
date = date.split("/")
print("Date in format mm-dd-yyyy: %s-%s-%s" % (date[1], date[0], date[2]))

output:-

Or
# Function to convert date format
def convert_date(input_date):
# Split the input date into day, month, and year
day, month, year = input_date.split('/')
# Format the date in MM-DD-YYYY format
formatted_date = f'{month.zfill(2)}-{day.zfill(2)}-{year}'
return formatted_date

# Main function
def main():
# Read input date in DD/MM/YYYY format
input_date = input("Enter a date in DD/MM/YYYY format: ")
try:
# Convert and print the formatted date
formatted_date = convert_date(input_date)
print(f'The date in MM-DD-YYYY format is: {formatted_date}')
except ValueError:
print('Invalid input. Please enter a valid date in DD/MM/YYYY format.')

# Call the main function if the script is run


if __name__ == "__main__":
main()

output:-
Practical:-10.4
Aim:- Write a program that checks whether two words are anagrams. Two words are
anagrams if they
contain the same letters. For example, silent and listen are anagrams
def are_anagrams(word1, word2):
# Remove spaces and convert the words to lowercase
word1 = word1.replace(" ", "").lower()
word2 = word2.replace(" ", "").lower()

# Check if the sorted characters of the words are the same


return sorted(word1) == sorted(word2)

# Main function
def main():
# Read two words from the user
word1 = input("Enter the first word: ")
word2 = input("Enter the second word: ")

# Check if the words are anagrams and print the result


if are_anagrams(word1, word2):
print(f"{word1} and {word2} are anagrams.")
else:
print(f"{word1} and {word2} are not anagrams.")

# Call the main function if the script is run


if __name__ == "__main__":
main()

output:-

Practical:10.5
Aim:- . Write a program that allows users to enter six-digit RGB color codes and converts them
into base 10. In this format, the first two hexadecimal digits represent the amount of red, the
second two the amount of green, and the last two the amount of blue. For example: If a user
enters FF6347, then the output should be Red (255), Green (99) and Blue (71).
def hex_to_rgb(hex):
hex = hex.lstrip('#')
return tuple(int(hex[i:i+2], 16) for i in (0, 2, 4))
if __name__ == "__main__":
hex = input("Enter hex color: ")
print("RGB: %s" % str(hex_to_rgb(hex)))
output:-

or

# Function to convert hexadecimal to decimal


def hex_to_decimal(hex_value):
return int(hex_value, 16)

# Get user input for RGB color code


hex_color_code = input("Enter a six-digit RGB color code: ")

# Extract red, green, and blue values from the input


red_hex = hex_color_code[:2]
green_hex = hex_color_code[2:4]
blue_hex = hex_color_code[4:]

# Convert hexadecimal to decimal


red_decimal = hex_to_decimal(red_hex)
green_decimal = hex_to_decimal(green_hex)
blue_decimal = hex_to_decimal(blue_hex)

# Output the RGB values


print("Red ({})".format(red_decimal))
print("Green ({})".format(green_decimal))
print("Blue ({})".format(blue_decimal))

output:-

Practical:-10.6
Aim:- Numerologists claim to be able to determine a person's character traits based on the
"numeric value" of a name. The value of a name is determined by summing up the values of
the letters of the name, where "a" is 1 "b" is 2 "c" is 3 and so on up to "z" being 26. For
example, the name "Python" would have the value 16 + 25 + 20 + 8 + 15 + 14 = 98. Write a
program that calculates the numeric value of a name provided as input.

def name_value(name):
name = name.lower()
value = 0
for char in name:
value += ord(char) - 96
return value

if __name__ == "__main__":
name = input("Enter name: ")
print("Value of name: %d" % name_value(name))

output:-

You might also like