0% found this document useful (0 votes)
54 views24 pages

Solutions

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)
54 views24 pages

Solutions

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/ 24

Code & Debug

Practice Questions Solutions


1. Write a program that takes two numbers as input from the user and then
prints the sum of these numbers.
num1 = int(input("Enter number 1 = "))
num2 = int(input("Enter number 2 = "))

# Calculating Total
total = num1 + num2

# Printing Total
print(f"Total is {total}")

2. Write a Program that takes Length and Breadth as input from user and
print the Area of Rectangle.
length = float(input("Enter length of rectangle = "))
breadth = float(input("Enter breadth of rectangle = "))

# Calculating Area
area = length * breadth

# Printing Area
print(f"Area of rectangle is {area}")

3. Ask 3 numbers from User and Calculate the Average.


num1 = int(input("Enter number 1 = "))
num2 = int(input("Enter number 2 = "))
num3 = int(input("Enter number 3 = "))

# Calculating Average
avg = (num1 + num2 + num3) / 3

# Printing the answer


print(f"Average is {avg}")

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

4. Calculate sum of 5 subjects and Find percentage.


maths = int(input("Enter marks in maths = "))
english = int(input("Enter marks in english = "))
science = int(input("Enter marks in science = "))
sst = int(input("Enter marks in sst = "))
comp = int(input("Enter marks in comp = "))

# Calculating Total of 5 subjects


total = maths + english + science + sst + comp

# Calculating Percentage
percentage = total / 500 * 100

# Printing the answer


print(f"Total is {total} and percentage is {percentage}")

5. Same as above
6. Ask value in Rupees and Convert into Paise.
rupees = float(input("Enter rupees = "))

# Converting rupee into paise


paise = rupees * 100

print(f"{rupees} rupees into paise is {paise}")

7. Calculate Area of Square by taking Side from User.


s = float(input("Enter side of a square = "))
area = s * s

print(f"Area of square with side {s} is {area}")

8. Ask number of games played in a tournament. Ask the user number of


games won and number of games loss. Calculate number of tie and total
Points. (1 win= 4 points, 1 tie =2 points)
total_games = int(input("Total number of games played = "))
games_won = int(input("Total games won = "))
games_loss = int(input("Total games lost = "))

# Calculating number of games tied


games_tied = total_games - (games_won + games_loss)

# Calculating total points


total_points = (games_won * 4) + (games_tied * 2)

print(f"Total points scored is {total_points}")

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

9. Take two numbers as input from User and print which one is greater or
are they equal.
num1 = int(input("Enter number 1 = "))
num2 = int(input("Enter number 2 = "))

if num1 > num2:


print(f"{num1} is greater than {num2}")
elif num2 > num1:
print(f"{num2} is greater than {num1}")
else:
print("Both are equal")

10. Take three numbers as input from User and print which one is greater
or are they equal.
num1 = int(input("Enter number 1 = "))
num2 = int(input("Enter number 2 = "))
num3 = int(input("Enter number 3 = "))

if num1 > num2 and num1 > num3:


print(f"{num1} is greater than {num2}, {num3}")
elif num2 > num1 and num2 > num3:
print(f"{num2} is greater than {num1},{num3}")
elif num3 > num1 and num3 > num1:
print(f"{num3} is greater than {num1},{num2}")
elif num1 == num2 == num3:
print("All are equal")

11. Take Salary as input from User and Update the salary of an employee
a. salary less than 10,000, 5 % increment
b. salary between 10,000 and 20, 000, 10 % increment
c. salary between 20,000 and 50,000, 15 % increment
d. salary more than 50,000, 20 % increment
salary = float(input("Enter your salary = "))

# Conditions for calculating salaries


finalSalary = salary
if salary < 10000:
finalSalary = salary + (5 / 100 * salary)
elif salary <= 20000 and salary >= 10000:
finalSalary = salary + (10 / 100 * salary)
elif salary <= 50000 and salary > 20000:
finalSalary = salary + (15 / 100 * salary)
elif salary > 50000:
finalSalary = salary + (20 / 100 * salary)

print(f"Your final salary is {finalSalary}")

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

12. Ask the number from User and print whether the number is Odd or
Even.
number = int(input("Enter any number = "))

if number % 2 == 0:
print(f"The number {number} is even")
else:
print(f"The number {number} is odd")

13. A school has following rules for grading system:


a. Below 25 - F
b. 25 to 45 - E
c. 45 to 50 - D
d. 50 to 60 - C
e. 60 to 80 - B
f. Above 80 – A
Ask user to enter marks and print the corresponding grade.
mark = int(input("Enter your marks = "))

if mark > 80 and mark <= 100:


print("You have scored A.")
elif mark > 60 and mark <= 80:
print("You have scored B.")
elif mark > 50 and mark <= 60:
print("You have scored C.")
elif mark > 45 and mark <= 50:
print("You have scored D.")
elif mark > 25 and mark <= 45:
print("You have scored E.")
elif mark <= 25:
print("You have scored F.")
else:
print("Wrong marks")

# ------------ OR ----------
mark = int(input("Enter your marks = "))

if 80 < mark <= 100:


print("You have scored A.")
elif 60 < mark <= 80:
print("You have scored B.")
elif 50 < mark <= 60:
print("You have scored C.")
elif 45 < mark <= 50:
print("You have scored D.")
elif 25 < mark <= 45:
print("You have scored E.")
elif mark <= 25:
print("You have scored F.")
else:
print("Wrong marks")

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

14. A student will not be allowed to sit in exam if his/her attendance is less
than 75%.
a. Take following input from user
i. Number of classes held
ii. Number of classes attended.
b. Print percentage of class attended
c. Print Is student is allowed to sit in exam or not.
totalClasses = int(input("Total classes conducted = "))
classesAttend = int(input("Total classes attended = "))

# Classes missed with condition


if classesAttend <= totalClasses:
classesMissed = totalClasses - classesAttend
attendancePercent = (classesAttend / totalClasses) * 100
print(f"Percentage of classes attended are
{attendancePercent}%")
if attendancePercent >= 75:
print("You are allowed to sit in exams")
else:
print("You are not allowed to sit in exams")
else:
print("Classes attended cannot be more than classes held")

15. Calculate the purchase amount after deduction criteria on printed price
a. printed price between 500 and 1000, allow 5% discount
b. printed price between 1000 and 5000, allow 10% discount
c. printed price between 5000 and 10000, allow 15% discount
d. printed price more than 10000, allow 20% discount
billAmount = float(input("Enter bill amount = "))

if 0 < billAmount < 500:


print(f"You got no discount. Your final bill is
{billAmount}")
elif 500 <= billAmount < 1000:
discount = 5 / 100 * billAmount
print(f"You got 5% discount. Your final bill is
{billAmount - discount}")
elif 1000 <= billAmount < 5000:
discount = 10 / 100 * billAmount
print(f"You got 10% discount. Your final bill is
{billAmount - discount}")
elif 5000 <= billAmount < 10000:
discount = 15 / 100 * billAmount
print(f"You got 15% discount. Your final bill is
{billAmount - discount}")
elif billAmount >= 10000:
discount = 20 / 100 * billAmount
print(f"You got 20% discount. Your final bill is
{billAmount - discount}")
else:
print("Wrong bill amount")

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

16. Print first 10 Natural numbers


i = 1

while i <= 10:


print(i)
i = i + 1

17. Print all the even numbers from 1 to 100.


i = 1

while i <= 100:


if i % 2 == 0:
print(i)
i = i + 1

18. Find sum of N numbers where N is input from User.


n = int(input("Enter any number = "))
total = 0
i = 1

while i <= n:
total = total + i
i += 1

print(f"Total is {total}")

19. Check whether number entered by User is Prime or Not.


n = int(input("Enter any number = "))
totalFactors = 0
i = 1

# Calculating factors
while i <= n:
if n % i == 0:
totalFactors = totalFactors + 1
i += 1

# If only 2 factors, then it is prime


if totalFactors == 2:
print(f"{n} is a prime number")
else:
print(f"{n} is a not prime number")

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

20. Check whether number entered by User is Armstrong or not.


Armstrong number is a number that is equal to the sum of cubes of its digits. For
example, 0, 1, 153, 370, 371 and 407 are the Armstrong numbers.
n = int(input("Enter any number = "))
m = n
total = 0

while m > 0:
digit = m % 10
total = total + (digit ** 3)
m = m // 10

if n == total:
print("It is an armstrong number")
else:
print("It is not an armstrong number")

21. Find Factorial of a number entered by User.


n = int(input("Enter any number = "))
total = 1

while n > 0:
total = total * n
n = n - 1

print(f"Factorial = {total}")

22. Print the first 10 multiples of a number entered by User.


n = int(input("Enter any number = "))
i = 1

while i <= 10:


print(f"{n} X {i} = {n * i}")
i = i + 1

23. Count the number of digits in a number that is entered by User.


n = int(input("Enter any number = "))
m = n
totalDigits = 0

while m > 0:
digit = m % 10
totalDigits = totalDigits + 1
m = m // 10

print(f"Total digits = {totalDigits}")

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

24. Write a Program to Reverse a number.


n = int(input("Enter any number = "))
m = n

while m > 0:
digit = m % 10
print(digit, end="")
m = m // 10

25. Print first 10 Natural numbers.


for i in range(1, 11):
print(i)

26. Print all the even numbers from 1 to 100.


for i in range(1, 101):
# Checking if i is even or odd
if i % 2 == 0:
print(i)

27. Find sum of N numbers where N is input from User.


number = int(input("Enter any number = "))
total = 0

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


total = total + i

print(f"Total is {total}")

28. Check whether number entered by User is Prime or Not.


number = int(input("Enter any number = "))
totalFactors = 0

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


if number % i == 0:
totalFactors = totalFactors + 1

if totalFactors == 2:
print(f"{number} is a prime number")
else:
print(f"{number} is not a prime number")

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

29. Can skip this question.


30. Print multiplication table of a number entered by user.
number = int(input("Enter any number = "))

for i in range(1, 11):


print(f"{number} X {i} = {number * i}")

31. Program to display all the prime numbers within a range.


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

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


totalFactors = 0
for j in range(1, i + 1):
if i % j == 0:
totalFactors += 1
if totalFactors == 2:
print(f"{i} is a prime number")

32. Make the following Patterns:


*
**
***
****
*****
for i in range(1, 6):
for j in range(1, i + 1):
print("* ", end=" ")
print()

1
12
123
1234
12345
for i in range(1, 6):
for j in range(1, i + 1):
print(f"{j} ", end=" ")
print()

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

5
54
543
5432
54321
for i in range(5, 0, -1):
for j in range(5, i - 1, -1):
print(f"{j} ", end=" ")
print()

55555
4444
333
22
1
for i in range(5, 0, -1):
for j in range(1, i + 1):
print(f"{i} ", end=" ")
print()

1
21
321
4321
54321
for i in range(1, 6):
# To print space on left side
for j in range(5, i, -1):
print(f" ", end=" ")

# To print numbers
for k in range(i, 0, -1):
print(f"{k} ", end="")

print()

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

5
45
345
2345
12345
for i in range(1, 6):
# To print space on left side
for j in range(5, i, -1):
print(f" ", end=" ")

# To print numbers
for k in range(6 - i, 6):
print(f"{k} ", end="")

print()

33. Write a program to display following Output.


a. 1 2 3 4 5 6 7 8 9 10
for i in range(1, 11):
print(i, end=" ")

b. 2 4 6 8 10 12 14 16 18 20
for i in range(1, 21):
if i % 2 == 0:
print(i, end=" ")

c. 3 6 9 12 15 18 21 24 27 30
for i in range(3, 31, 3):
print(i, end=" ")

d. 4 8 12 16 20 24 28 32 36 40
for i in range(4, 41, 4):
print(i, end=" ")

e. 5 10 15 20 25 30 35 40 45 50
for i in range(5, 51, 5):
print(i, end=" ")

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

34. Write a Python program to sum all the items in a list.


myList = [65, 78, 55, 42, 17, 58, 99]

# Solution 1
total = sum(myList)
print(f"Total of {myList} is {total}")

# Solution 2
total = 0
for i in myList:
total = total + i
print(f"Total of {myList} is {total}")

35. Write a Python program to multiply all the items in a list.


myList = [65, 78, 55, 42, 17, 58, 99]

total = 1
for i in myList:
total = total * i
print(f"Total multiplication of {myList} is {total}")

36. Take 10 integer inputs from user and store them in a list and print them
on screen.
myList = []

# Running loop 10 times


for i in range(1, 11):
n = int(input("Enter any number = "))
myList.append(n) # Adding number o the list

print(f"Answer = {myList}")

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

37. Take 20 integer inputs from user and print the following:
a. number of positive numbers
b. number of negative numbers
c. number of odd numbers
d. number of even numbers
e. number of 0s.
myList = []

# Running loop 20 times


for i in range(1, 21):
n = int(input("Enter any number = "))
myList.append(n) # Adding number o the list

positive = 0
negative = 0
odd = 0
even = 0
zero = 0

for i in myList:
if i > 0:
positive += 1
elif i < 0:
negative += 1
else:
zero += 1

if i % 2 == 0:
even += 1
else:
odd += 1

print(f"Positive = {positive}")
print(f"Negative = {negative}")
print(f"Zero = {zero}")
print(f"Even = {even}")
print(f"Odd = {odd}")

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

38. Take 10 integer inputs from user and store them in a list. Again, ask user
to give a number. Now, tell user whether that number is present in list
or not.
myList = []

# Running loop 10 times


for i in range(1, 11):
n = int(input("Enter any number = "))
myList.append(n) # Adding number o the list

number = int(input("Enter the number you want to check = "))

if number in myList:
print("Number is present in the list")
else:
print("Number is not present in the list")

39. Make a list by taking 10 inputs from user. Now delete all repeated
elements of the list.
myList = []

# Running loop 10 times


for i in range(1, 11):
n = int(input("Enter any number = "))
myList.append(n) # Adding number o the list

newList = []

for i in myList:
if i not in newList: # Check if number is present
newList.append(i)

print(f"Old list -> {myList}")


print(f"New list -> {newList}")

40. Ask user to give integer inputs to make a list. Store only even values
given and print the list.
myList = []

# Running loop 10 times


for i in range(1, 11):
n = int(input("Enter any number = "))
if n % 2 == 0:
myList.append(n)

print(myList)

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

41. Calculate the sum of all the numbers in a tuple.


myTuple = (54, 34, 12, 33, 55, 65, 44)

print(f"Total of tuple is {sum(myTuple)}")

42. Create a tuple with some numbers. Ask a random number from user
and add that number to the end of the tuple.
myTuple = (54, 34, 12, 33, 55, 65, 44)

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

myList = list(myTuple) # Converting tuple to list


myList.append(n)

myTuple = tuple(myList) # Again converting list to tuple


print(myTuple)

43. Write a Python program to get the 4th element and 4th element from
last of a tuple.
myTuple = (56, 89, 77, 65, 32, 12, 45, 33)

print(f"4th element from front is {myTuple[3]}")


print(f"4th element from behind is {myTuple[-4]}")

44. Write a Python program to find the repeated items of a tuple.


myTuple = (56, 89, 67, 89, 32, 12, 56, 89, 12, 66, 77, 55, 44)
repeatedElements = []

for i in myTuple:
# Checking if number comes more than 1 time
if myTuple.count(i) > 1:
# Checking if number already in repeatedElements
if i not in repeatedElements:
repeatedElements.append(i)

print("Repeated values are ")


for i in repeatedElements:
print(i)

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

45. Write a Python program to remove a number entered by user from a


tuple.
myTuple = (56, 89, 67, 89, 32, 12, 56, 89, 12, 66, 77, 55, 44)
number = int(input("Enter the number you want to remove = "))

if myTuple.count(number) > 0:
myList = list(myTuple)
myList.remove(number)
myTuple = tuple(myList)
print(myTuple)
else:
print("Number does not exist in tuple")

46. Write a Python program calculate the product, multiplying all the
numbers of a given tuple.
myTuple = (4, 3, 2, 2, -1, 18)
total = 1

for i in myTuple:
total = total * i

print(f"Product of all the numbers = {total}")

47. Merge two Python dictionaries into one.


dict1 = {"name": "Elon", "age": 55, "gender": "M"}
dict2 = {"address": "Unknown", "phone": 45343}

dict1.update(dict2)

print(dict1)

48. Write a python program to find the sum of all items in a dictionary.
myDictionary = {"maths": 77, "science": 90, "english": 34,
"sst": 24, "comp": 99}

total = 0

for i in myDictionary.values():
total = total + i

print(f"Total of all the values = {total}")

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

49. Write a python program to check whether a given key already exists in a
Dictionary.
myDictionary = {"name": "Akshay", "gender": "Male", "age": 66,
"phone": 45454}

a = input("Enter the key you want to check = ")

if myDictionary.get(a) is not None:


print(f"Key exists and its value is
{myDictionary.get(a)}")
else:
print("Key does not exists")

50. Write a Python program to iterate over dictionaries using for loops.
myDictionary = {"name": "Akshay", "gender": "Male", "age": 66,
"phone": 45454}

for k, v in myDictionary.items():
print(f"Key -> {k} and value -> {v}")

51. Write a Python program to generate and print a dictionary that contains
a number (between 1 and n) in the form (x, x*x).
myDictionary = {}
n = int(input("Enter any number = "))

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


myDictionary.update({i: i * i})

print("Final answer")
print(myDictionary)

52. Write a Python program to map two lists into a dictionary.


list1 = ["name", "age", "gender", "totalMarks"]
list2 = ["Ananya", 44, "Female", 10]
myDictionary = {}

for i in range(0, len(list1)):


myDictionary.update({list1[i]: list2[i]})

print(myDictionary)

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

53. Write a Python program to get the maximum and minimum value in a
dictionary.
myDictionary = {"maths": 19, "english": 87, "science": 43,
"sst": 88, "comp": 99}
allMarksList = []

for i in myDictionary.values():
allMarksList.append(i)

print(f"Maximum value is {max(allMarksList)}")


print(f"Minimum value is {min(allMarksList)}")

54. Write a Python program to create a dictionary from a string.


x = input("Enter any string = ")
myDictionary = {}

for i in range(0, len(x)):


myDictionary.update({i: x[i]})

print(myDictionary)

55. Write a Python program to print a dictionary in table format.


myDictionary = {"maths": 19, "english": 87, "science": 43,
"sst": 88, "comp": 99}

print("Dictionary in table format")

for k, v in myDictionary.items():
print("{:10s} {}".format(k, v))

56. A Python Dictionary contains List as value. Write a Python program to


clear the list values in the said dictionary.
myDictionary = {"C1": [54, 66, 77], "C2": [90, 12, 43], "C3":
[67, 45, 89]}

print(myDictionary)

for i in myDictionary.keys():
myDictionary[i] = []

print(myDictionary)

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

57. Write a Python program to convert a given dictionary into a list of lists.
myDictionary = {1: 'red', 2: 'green', 3: 'black', 4: 'white',
5: 'black'}

myList = []

for k, v in myDictionary.items():
myList.append([k, v])

print(myList)

58. Python program to print even length words in a string.


n = input("Enter any string = ")

myList = n.split()

for i in myList:
if len(i) % 2 == 0:
print(i)

59. Write a Python program to calculate the length of a string entered by a


User.
n = input("Enter any string = ")

print(f"Length of string is {len(n)}")

60. Write a Python program to reverse a string entered by User.


n = input("Enter any string = ")

# ---------Solution 1---------
print(n[-1::-1])

# ---------Solution 2---------
myList = []
for i in n:
myList.append(i)

myList.reverse()
for i in myList:
print(i, end='')

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

61. Count the number of vowels in a string entered by User.


n = input("Enter any string = ")

n = n.lower()
total = n.count('a') + n.count('e') + n.count('i') +
n.count('o') + n.count('u')

print(f"Total vowels are {total}")

62. Remove the even index characters from the string entered by User.
n = input("Enter any string = ")

ans = ''
for i in range(0, len(n)):
if i % 2 == 0:
ans += n[i]

print(ans)

63. Write a Python program to reverse a string if its length is a multiple of 4.


n = input("Enter any string = ")

if len(n) % 4 == 0:
print(n[-1::-1])
else:
print(n)

64. Count number of digits in a string entered by user.


n = input("Enter any string = ")
total = 0

for i in n:
if i.isdigit():
total += 1

print(f"Total digits are {total}")

65. Check if the String entered by user is palindrome or not.


n = input("Enter any string = ")

if n == n[-1::-1]:
print("It is a palindrome")
else:
print("It is no a palindrome")

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

66. Find all duplicate characters in string entered by user.


n = input("Enter any string = ")
myList = []

for i in n:
if n.count(i) > 1:
if i not in myList:
myList.append(i)

print("All duplicates character are")


for i in myList:
print(i, end=" ")

67. Reverse Sort a String entered by user.


n = input("Enter any string = ")

myList = list(n)
myList.reverse()

for i in myList:
print(i, end="")

68. Write a Python function to find the Max of three numbers.


def maxOfThreeNumbers(a, b, c):
if a > b and a > c:
print(f"{a} is greater")
elif b > a and b > c:
print(f"{b} is greater")
elif c > a and c > b:
print(f"{c} is greater")
else:
print("All are equal")

maxOfThreeNumbers(56, 44, 67)


maxOfThreeNumbers(87, 89, 88)

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

69. Write a Python function to sum all the numbers in a list.


def sumOfList(myList):
print(f"Sum of all numbers are {sum(myList)}")

sumOfList([56, 43, 36, 76])


sumOfList([12, 78, 63, 66, 55])

70. Write a Python function to reverse a string.


def reverseString():
x = input("Enter your String = ")
print(x[-1::-1])

reverseString()
reverseString()

71. Write a Python function that takes a number as a parameter and check
the number is prime or not.
def checkPrime(n):
totalFactors = 0
for i in range(1, n + 1):
if n % i == 0:
totalFactors += 1
if totalFactors == 2:
print(f"{n} is a prime number")
else:
print(f"{n} is not a prime number")

checkPrime(55)
checkPrime(7)
checkPrime(70)

72. Write a Python program to print the even numbers from a given list.
def evenList(x):
myList = []
for i in x:
if i % 2 == 0:
myList.append(i)
print(myList)

evenList([55, 21, 45, 76, 55])


evenList([67, 55, 11])

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

73. Write a Python function that checks whether a passed string is


palindrome or not.
def checkPalindrome(s):
s = s.lower()
if s == s[-1::-1]:
print(f"{s} is a palindrome")
else:
print(f"{s} is not a palindrome")

checkPalindrome("Noon")
checkPalindrome("moM")
checkPalindrome("abc")

74. Write a Python program to read an entire text file.


f = open("hello.txt", "r")
print(f.read())
f.close()

75. Write a Python program to read a file line by line and store it into a list.
f = open("hello.txt", "r")
myList = f.readlines()
print(myList)
f.close()

76. Write a python program to find the longest words.


f = open("hello.txt", "r")
allWords = f.read().split()

longestWord = ''
for i in allWords:
if len(i) > len(longestWord):
longestWord = i

print(f"Longest word is {longestWord}")

f.close()

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in
Code & Debug

77. Write a Python program to count the number of lines in a text file.
f = open("hello.txt", "r")

print(f"Number of lines are {len(f.readlines())}")

f.close()

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


f = open("hello.txt", "r")
allWords = f.read().split()
myWords = []

for i in allWords:
if i not in myWords:
myWords.append(i)

for i in myWords:
print(f"{i} has repeated {allWords.count(i)} times")

f.close()

79. Write a Python program to copy the contents of a file to another file.
f = open("hello.txt", "r")
content = f.read()
f.close()

f = open("hello1.txt", "w")
f.write(content)
f.close()

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


from random import randint

f = open("hello.txt", "r")
allLines = f.readlines()
f.close()

randomLine = randint(0, len(allLines) - 1)

print(f"Random line = {allLines[randomLine]}")

Contact: +91-9712928220 | Mail: info@codeanddebug.in


Website: codeanddebug.in

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