100% found this document useful (1 vote)
440 views

Enter Your Name Nishigandha Enter Your Age 22 Nishigandha You Will Turn 100 Years Old in 2098

The document contains 26 programming problems and their solutions. Some of the problems include: writing a program to calculate a user's 100th birthday, checking if a number is even or odd, finding numbers divisible by 7 in a range, calculating the factorial of a given number, checking if a list contains common elements between two lists, determining if a number is prime, checking if a number is a palindrome, generating Fibonacci numbers up to a given limit, reversing the words in a string, counting the frequency of words in a text file, and more. For each problem, the code to solve it is provided along with example input/output.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
440 views

Enter Your Name Nishigandha Enter Your Age 22 Nishigandha You Will Turn 100 Years Old in 2098

The document contains 26 programming problems and their solutions. Some of the problems include: writing a program to calculate a user's 100th birthday, checking if a number is even or odd, finding numbers divisible by 7 in a range, calculating the factorial of a given number, checking if a list contains common elements between two lists, determining if a number is prime, checking if a number is a palindrome, generating Fibonacci numbers up to a given limit, reversing the words in a string, counting the frequency of words in a text file, and more. For each problem, the code to solve it is provided along with example input/output.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

1. Create a program that asks the user to enter their name and their age.

Print out a
message addressed to them that tells them the year that they will turn 100 years old

name = input("Enter Your name\n")


age =int(input("Enter Your age\n"))
year = str((2020 - age)+100)
print(name + " You will turn 100 years old in " + year)

Output :-

Enter Your name


Nishigandha
Enter Your age
22
Nishigandha You will turn 100 years old in 2098

2. Write a program to check whether the number is even or odd, print out an
appropriate message to the user

number = int(input("Enter Number "))


number = number % 2
if number > 0:
print("Number is odd")
else:
print("Number is even")

Output:-

Enter Number 8
Number is even
Enter Number 5
Number is odd

3. Write a program which will find all such numbers which are divisible by 7.

n = []
for i in range(1,70):
if (i%7==0):
n.append(i)
print(i)

Output:-

7
14
21
28
35
42
49
56
63
4.Write a program which can compute the factorial of a given numbers.

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


fact = 1
if number==0:
print("Facotrial of 0 is 1")
else:
for i in range(1,number+1):
fact = fact*i
print("factorial of ",number, "is", fact)

Output:-

Enter number 5
factorial of 5 is 120

5. Write a program that prints out all the elements of the list that are less than 10.

a = [2,4,5,67,8,45,20,23,11,5,3]
b = []
for b in a:
if b<10:
print(b)

Output:-

2
4
5
8
5
3

6. Write a program that returns a list that contains only the elements that are
common between the lists (without duplicates). Make sure your program works on
two lists of different sizes.

a = [1,2,3,4,5,4]
b = [1,2,4,7,8,9,4]
mylist = []
for i in a:
if i in b:
mylist.append(i)
mylist = list(dict.fromkeys(mylist))
print(mylist)

Output:-

[1, 2, 4]
7. To determine whether the number is prime or not.

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

if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")

else:
print(num,"is not a prime number")

Output:-

Enter a number: 85
85 is not a prime number

Enter a number: 10
10 is not a prime number

8. To check whether a number is palindrome or not. (using recursion and without


recursion).

Without recursion:-

n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")

Output:-

Enter number:121
The number is a palindrome!
Enter number:123
The number is not a palindrome!

# To check whether a number is palindrome or not. (with recursion).

def rev(n, temp):


if (n == 0):
return temp;
temp = (temp * 10) + (n % 10);

return rev(n / 10, temp);

n = int(input("Enter number"))
temp = rev(n, 0);

if (temp != n):
print("yes its palindrome");
else:
print("its not palindrome");

output:-

Enter number101
yes its palindrome

9. Write a program that asks the user how many Fibonnaci numbers to generate and
then generates them

def fib (a, b):

return a + b

number = int(input("How many Fibonacci numbers should I generate? "))

fibonacci_list = []
for n in range(number):
if n in [0, 1]:
fibonacci_list += [1]
else:
fibonacci_list += [fib(fibonacci_list[n-1], fibonacci_list[n-2])]

print("The first", number, "Fibonacci numbers are:", fibonacci_list)

Output:-

How many Fibonacci numbers should I generate? 7


The first 7 Fibonacci numbers are: [1, 1, 2, 3, 5, 8, 13]

10.Write a program (using functions!) that asks the user for a long string containing
multiple words. Print back to the user the same string, except with the words in
backwards order. E.g “ I am Msc student” is :”student Msc am I”

def stringReverse(string):
list1 = string.split(' ')
list1.reverse()
list1 = ' '.join(list1)
return list1

question = input('Please enter a string: ')


answer = stringReverse(question)
print(answer)
Output:-

Please enter a phrase: I am Msc student


student Msc am I

11.Write a program to implement binary search to search the given element using
function.

12.Given a .txt file that has a list of a bunch of names, count how manyof each name
there are in the file, and print out the results to the screen.

%%writefile sample.txt
abc
xyz
abc
pqr
Uwx

text = open("sample.txt", "r")

d = dict()
for line in text:
line = line.strip()
line = line.lower()
words = line.split(" ")

for word in words:

if word in d:
# Increment count of word by 1
d[word] = d[word] + 1
else:
d[word] = 1

for key in list(d.keys()):


print(key, ":", d[key])
Output:-

abc : 2
xyz : 1
pqr : 1
uwx : 1

13.Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20,
25])and makes a new list of only the first and last elements of the given list.

a = [5,10,15,20,25]
b = [a[0],a[-1]]
print(b)

Output:-

[5, 25]

14.Write a program that accepts sequence of lines as input and prints the lines after
making all characters in the sentence capitalized.

lines = []
while True:
s = input("Enter Lines :")
if s:
lines.append(s.upper())
else:
break
for sentence in lines:
print(sentence)

Output:-

Enter Lines :this is the first line


Enter Lines :this is the second line
Enter Lines :this is the third line
Enter Lines :
THIS IS THE FIRST LINE
THIS IS THE SECOND LINE
THIS IS THE THIRD LINE

15.Write a program that accepts a sentence and calculate the number of letters and
digits

s = input("Input a string ")


d=l=0
for c in s:
if c.isdigit():
d=d+1
elif c.isalpha():
l=l+1
else:
pass
print("Letters", l)
print("Digits", d)
Output:-

Input a string :there are 500 peoples


Letters 15
Digits 3

16.Write a program that accepts a sentence and calculate the number of upper case
letters and lower case letters.

ab = input("Enter string:")
upper= lower= 0
for u in ab:
if u.isupper():
upper=upper+1
elif u.islower():
lower=lower+1
else:
pass
print("Upper letters : ", upper)
print("Lower letters : ", lower)

Output:-

Enter string:This Is THE book


Upper letters : 5
Lower letters : 8

17.Write a Python function to calculate the factorial of a number (a non-negative


integer). The function accepts the number as an argument.

def fact(n):
if n==0:
return 1
else:
return n*fact(n-1)
n = int(input("Enter the number"))
print(fact(n))

Output:-

Enter the number : 5


120

18.Write a Python program of recursion list sum

def list_sum(list):
total=0
for i in list:
if type(i) == type([]):
total = total + list_sum(i)
else:
total = total + i
return total
print(list_sum([1,3,5]))

Output:-
9

19.Write a Python program to solve the Fibonacci sequence using recursion.

def fib (a, b):

return a + b

number = int(input("How many Fibonacci numbers should I generate? "))

fibonacci_list = []
for n in range(number):
if n in [0, 1]:
fibonacci_list += [1]
else:
fibonacci_list += [fib(fibonacci_list[n-1], fibonacci_list[n-2])]

print("The first", number, "Fibonacci numbers are:", fibonacci_list)

Output:-

How many Fibonacci numbers should I generate? 10


The first 10 Fibonacci numbers are: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

20.Write a Python program to get the sum of a non-negative integer

def sumDigits(n):
if n == 0:
return 0
else:
return n % 10 + sumDigits(int(n / 10))
n = int(input("Enter your number: "))
print("sum of number of digits {0} is ".format(n),sumDigits(n))

Output:-

Enter your number: 45


sum of number of digits 45 is 9

21.Write a Python program to find the greatest common divisor (gcd) of two integers

a = int(input("enter first number"))


b = int(input("enter second number"))
i=1
while (i<=a and i<=b):
if (a % i ==0 and b %i ==0):
gcd = i
i=i+1
print("the gcd of {0} and {1} is = {2}" .format(a, b, gcd))
Output:-

enter first number10


enter second number20
the gcd of 10 and 20 is = 10

22.Write a Python function that takes a list and returns a new list with unique
elements of the first list.

def unique_list(l):
x = []
for a in l:
if a not in x:
x.append(a)
return x

print(unique_list([1,2,3,3,3,3,4,5]))

Output:-

[1, 2, 3, 4, 5]

23.Write a Python function to check whether a number is perfect or not

def perfect_number(n):
sum = 0
for x in range(1, n):
if n % x == 0:
sum += x
return sum == n
n = int(input("Enter your number "))
if perfect_number(n):
print("{0} is perfect number" .format(n))
else:
print("{0} is not perfect number".format(n))

Output:-

Enter your number 28


28 is perfect number
Enter your number 8
8 is not perfect number

24.Write a Python program to read a file line by line store it into an array.

Txt file: - text3.txt


This is the first line
And this is second line

file = open("test3.txt" , "r")


file_array = []
for line in file:
file_array.append(line)
print(file_array)
file.close()

Output:-
['this is the first line \n', 'and this is second line']

25.Write a Python program to count the number of lines in a text file.

Txt file:- test.txt

This is the first line


This is the second line
This is the third line
This is the fourth line
This is the last line

file = open("test.txt","r")
count = 0
content = file.read()
count_list = content.split("\n")

for i in count_list:
if i:
count+=1
print("Number of lines in file")
print(count)
file.close()

Output:-

Number of lines in file


5

26.Write a Python program to count the frequency of words in a file.

Txt file:- test.txt

one two three four


five one two three
six one ten seven
file = open("test1.txt", "r")
d = dict()
for line in file:
line = line.strip()
line = line.lower()
words = line.split()

for word in words:


if word in d:
d[word] = d[word] + 1
else:
d[word] = 1
for key in list(d.keys()):
print(key,":",d[key])

file.close()

Output:-

one : 3
two : 2
three : 2
four : 1
five : 1
six : 1
ten : 1
seven : 1

27.Write a Python program to copy the contents of a file to another file

Txt file 1:- file.txt

this is file one and copythis content in file two

Txt file 2:- file2.txt

file1 = open("file1.txt" ,"r")


file2 = open("file2.txt","w")
for line in file1:
file2.write(line)
print("Copy content successfully..!")
file1.close()
file2.close()

Output:
Copy content successfully..!

File2.txt: -

this is file one and copythis content in file two


28.Write a Python program to read a random line from a file

Txt file :- test.txt

this the first line


this is the second line
this is the third line
this is the fourth line
end of file

import random
file = open("test.txt", "r")
lines = file.readlines()
print(random.choice(lines))
file.close()

Output:-

this is the third line


this the first line

29.Write a Python class to reverse a string word by word.


Input string : 'hello.py' Expected Output : '.py hello'

class py_solution:
def reverse_words(self, s):
return ' '.join(reversed(s.split()))

print(py_solution().reverse_words('hello .py'))

Output:-

.py hello

30.Write a Python class named Rectangle constructed by a length and width and a
method which will compute the area and perimeter of a rectangle. –

class rectangle():
def __init__(self,l,w):
self.length=l
self.width=w

def rectangle_area(self):
return self.length*self.width
newRectangle = rectangle(5, 5)
print(newRectangle.rectangle_area())

Output:-

25
31.Write a Python class named Circle constructed by a radius and two methods
which will compute the area and the perimeter of a circle

class Circle():
def __init__(self, r):
self.radius = r

def area(self):
return self.radius**2*3.14

def perimeter(self):
return 2*self.radius*3.14

NewCircle = Circle(5)
print(NewCircle.area())
print(NewCircle.perimeter())

Output:-

area of circle 78.5


perimeter of circle 31.400000000000002

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy