Python Lab Programs (2)
Python Lab Programs (2)
1. Write a program that asks the user how many Fibonacci numbers to generate
and then generates them. Make sure to ask the user to enter the number of
numbers in the sequence to generate.
Method 1:
num = int(input("How many terms? "))
n1, n2 = 0, 1
print("Fibonacci Series:", n1, n2, end=" ")
for i in range(2, num):
n3 = n1 + n2
n1 = n2
n2 = n3
print(n3, end=" ")
print()
Method 2:
nterms = int(input("How many terms? "))
Method 1:
n=int(input('Enter the value of n: '))
print("Divisors of",n,"are:")
for i in range(1,n):
if(n%i==0):
print(i, end=' ')
print("Divisors of",n,"are:",divisors)
print("No. of Divisors:",len(divisors))
3. Write a program to compute distance between two points taking input from the
user (Pythagorean Theorem).
Method 1:
# Reading co-ordinates
x1 = float(input('Enter x1: '))
y1 = float(input('Enter y1: '))
x2 = float(input('Enter x2: '))
y2 = float(input('Enter y2: '))
# Calculating distance
d = ( (x2-x1)**2 + (y2-y1)**2 ) ** 0.5
# Displaying result
print('Distance = %f' %(d))
Method 2:
import math
x1 = float(input('Enter x1: '))
y1 = float(input('Enter y1: '))
x2 = float(input('Enter x2: '))
y2 = float(input('Enter y2: '))
# Calculating distance
d = math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2) )
# Displaying result
print('Distance = %0.6f' %(d))
4. Write a program for checking whether the given number is an even number or
not.
Method 1:
num = int(input("Enter any number to test whether it is odd or even: "))
if (num % 2) == 0:
print ("The number",num,"is even")
else:
print ("The number",num,"is odd")
Method 2:
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
5. Write a program using a while loop that asks the user for a number and prints a
countdown from that number to zero.
print("Countdown complete!")
6. Write a program to find the sum of all primes below twenty thousand.
Method 1:
sum = 0
# Initializing the sum to 0
for number in range(2, 20000):
# Using for loop starting from 2 as it is the first prime number.
i=2
for i in range(2, number):
if (int(number % i) == 0):
i = number
break;
#Only if the number is a prime number, continue to add it.
if i is not number:
sum = sum + number
print("\nThe sum of prime numbers in python from 1 to 20000 is :", sum)
Method 2:
numbers = list(range(2, 20000))
for prime in numbers:
for x in numbers:
if x % prime == 0 and prime != x:
numbers.remove(x)
print(sum(numbers))
7. a) Write a program to count the numbers of characters in the string and store
them in a dictionary data structure.
Method 1:
str=input("Enter a String")
dict = {}
for i in str:
dict[i] = str.count(i)
print (dict)
Method 2:
n=input("Enter the String: ")
s={}
for i in n:
if i in s:
s[i]+=1
else:
s[i]=1
print(s)
b) Write a program to use split and join methods in the string and trace a
birthday with a dictionary data structure.
bdict={}
while True:
print("\nOptions:")
print("1. Add a birthday using split and join method")
print("2. Trace a birthday with a dictionary data structure")
print("3. Exit")
if choice == '1':
str=input(“Enter the name and birthdate in given format name dd mm yyyy: ”)
l1=str.split()
name=l1[0]
birthdate='/'.join(l1[1:])
bdict[name]=birthdate
print(f"Added {name}'s birthday.")
elif choice == '2':
name = input("Enter the name to find: ").strip()
if name in bdict:
birthday = bdict[name]
print(f"{name}'s birthday is on {birthday}.")
else:
print(f"No birthday found for {name}.")
elif choice == '3':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
Output:
Options:
1. Add a birthday using split and join method
2. Trace a birthday with a dictionary data structure
3. Exit
Enter your choice: 1
Enter the name and birthdate in given format name dd mm yyyy: abc 12 09 2004
Added abc's birthday.
Options:
1. Add a birthday using split and join method
2. Trace a birthday with a dictionary data structure
3. Exit
Enter your choice: 1
Enter the name and birthdate in given format name dd mm yyyy: xyz 30 09 2010
Added xyz's birthday.
Options:
1. Add a birthday using split and join method
2. Trace a birthday with a dictionary data structure
3. Exit
Enter your choice: 2
Enter the name to find: abc
abc's birthday is on 12/09/2004.
Options:
1. Add a birthday using split and join method
2. Trace a birthday with a dictionary data structure
3. Exit
Enter your choice: 3
Exiting the program.
8. a) Write a python program that takes list and makes a new list that has only the
even elements of this list in it.
Method 1:
# Initialisation of list
lis = [1, 2, 3, 4, 5]
# checking condition
if num % 2 == 0:
out.append(num)
# printing output
print(out)
Method 2:
# list of numbers
list1 = [10, 21, 4, 45, 66, 93]
# checking condition
if num % 2 == 0:
print(num, end=" ")
Method 3:
# Initializing list and value
list1 = [10, 24, 4, 45, 66, 93]
num = 0
# Checking condition
if list1[num] % 2 == 0:
print(list1[num], end=" ")
# increment num
num += 1
b) Write a function that takes an ordered list of numbers (a list where the
elements are in order from smallest to largest) and another number. The
function decides whether or not the given number is inside the list and returns
(then prints) an appropriate Boolean.
lst = []
n = int(input("Enter number of elements : "))
print("Enter",n,"list elements")
for i in range(0, n):
ele = int(input())
lst.append(ele)
number_to_check = int(input("Enter the number to be searched inlist:"))
result = is_number_in_list(lst, number_to_check)
print(result)
if len(l1) != len(l2):
raise ValueError("Both lists must have the same length.")
combine_lists = {}
for i in range(len(l1)):
combine_lists[l1[i]] = l2[i]
print("Orginal Lists are")
print(l1)
print(l2)
print("\nCombined lists dictionary values are:")
print(combine_lists)
Method 2:
def combine_lists(keys, values):
return dict(zip(keys, values))
print("Original lists:")
print(l1)
print(l2)
Method 3:
l1 = ['a', 'b', 'c', 'd', 'e', 'f']
l2 = [1, 2, 3, 4, 5]
combine_lists=dict(zip(l1, l2))
print("Orginal Lists are")
print(l1)
print(l2)
print("\nCombined lists dictionary values are:")
print(combine_lists)
def print_lines_in_reverse(file_path):
try:
with open(file_path, 'r') as file:
lines = file.readlines()
print_lines_in_reverse(file_path)
def count_character_frequency(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
frequency = {}
file_path = 'your_file.txt'
count_character_frequency(file_path)
Method 1:
number_of_words = 0
number_of_lines = 0
number_of_characters = 0
number_of_lines = 0
number_of_words = 0
number_of_characters = 0
for line in file:
line = line.strip("\n")
words = line.split()
number_of_lines += 1
number_of_words += len(words)
number_of_characters += len(line)
file.close()