OneCompiler

ppython practical

128

1. Create a program that asks the user to enter their name and age. Print the year they will turn 100.

name = input("enter Name: ")
age = int(input("enter your Age: "))
year_100 = 2025 + (100 - age)
print(f"{name}, you will turn 100 in {year_100}")

2. Check whether the number is even or odd

n=int(input("enter number "))
if(n%2==0):
print(n,"number is even")
else:
print(n,"number is odd")

3. Find numbers divisible by 7 in a given range

p=int(input("enter starting number "))
q=int(input("enter end number "))
for n in range(p,q):
if n%7==0:
print(n,"number is divisible by 7")
else:
print(n,"number is not divisible by 7")

4. Compute the factorial of a number

import math
num = int(input("Enter a number: "))
print("Factorial:", math.factorial(num))

a=int(input("enter starting number "))
factorial=1
for i in range(1,a+1):
factorial=i*factorial
print("the factorial of",a,"is " ,factorial)

5. Print elements of a list that are less than 10

list=[1,2,3,4,5,6,7,8,9,4,5,6,5,55,5,55,66,44]
for i in list:
if(i<10):
print(i)

6. Find common elements between two lists (without duplicates)

list1 = [1, 2, 3, 4, 5, 6]
list2 = [4, 5, 6, 7, 8, 9]
common = list(set(list1) & set(list2))
print(common)

7. Determine whether a number is prime

n= int(input("enter a number"))
cnt=0
for i in range(2,n+1):
if(n%i==0):
cnt+=1
if(cnt>1):
print(n,"is not prime")
else:
print(n,"is prime")

8. Check whether a number is palindrome (without recursion)

without

num = input("Enter a number: ")
rev = num[::-1]
if num == rev:
print("Palindrome")
else:
print("Not Palindrome")

using rcursion

def is_palindrome(number):
str_number = str(number)
return str_number == str_number[::-1]
n = int(input("Enter a number: "))
if is_palindrome(n):
print(n,"is a palindrome.")
else:
print(n,"is not a palindrome.")

9. Generate Fibonacci sequence

def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
num = int(input("How many Fibonacci numbers? "))
for i in range(num):
print(fibonacci(i), end=" ")

10. Reverse words in a sentence

def reverse_words(sentence):
return " ".join(sentence.split()[::-1])
text = input("Enter a sentence: ")
print(reverse_words(text))

11. Implement binary search

def binary_search(arr, low, high, x):
if low > high:
return -1 # Element not found
mid = (low + high) // 2
if arr[mid] == x:
return mid # Element found
elif arr[mid] > x:
return binary_search(arr, low, mid - 1, x) # Search left
else:
return binary_search(arr, mid + 1, high, x) # Search right

Test

arr = [2, 3, 4, 10, 40]
x = 10
result = binary_search(arr, 0, len(arr)-1, x)

if result != -1:
print("Element found at index", result)
else:
print("Element not found")

12. Count occurrences of names in a file

from collections import Counter
with open("names.txt", "r") as file:
names = file.read().splitlines(
count = Counter(names)
for name, freq in count.items():
print(f"{name}: {freq}")

13. Extract first and last elements from a list

numbers = input("Enter numbers separated by commas: ").split(',') # Get input from the user
numbers = [int(num) for num in numbers] # Convert strings to integers
result = [numbers[0], numbers[-1]] #1st and last number
print("1st and last number is", result)

14. Convert sentence to uppercase and reverse words

text = input("Enter a sentence: ").upper()
print(" ".join(text.split()[::-1]))

15. Count letters and digits in a sentence

text = input("Enter a sentence: ")
letters = sum(c.isalpha() for c in text)
digits = sum(c.isdigit() for c in text)
print("Letters:", letters, "Digits:", digits)

or

def count_letters_digits(sentence):
letters = 0
digits = 0
for char in sentence:
if char.isalpha():
letters += 1
elif char.isdigit():
digits += 1
# Print the results
print(f"Original String: {sentence}")
print(f"Number of letters: {letters}")
print(f"Number of digits: {digits}")

Accept the sentence from the user

sentence = input("Enter a sentence: ")

Call the function

count_letters_digits(sentence)

16. Count uppercase and lowercase letters

text = input("Enter a sentence: ")
upper_case = sum(c.isupper() for c in text)
lower_case = sum(c.islower() for c in text)
print("Upper case:", upper_case, "Lower case:", lower_case)

or

def count_upper_lower(sentence):
upper_case = 0
lower_case = 0
for char in sentence:
if char.isupper():
upper_case += 1
elif char.islower():
lower_case += 1
# Print the results
print(f"Original String: {sentence}")
print(f"Upper case: {upper_case}")
print(f"Lower case: {lower_case}")

Accept the sentence from the user

sentence = input("Enter a sentence: ")

Calling function

count_upper_lower(sentence)

17. Factorial using recursion

def factorial(n):
# Check number is -ve
if n < 0:
return "Factorial is not defined for negative numbers."
# for value 0 nad 1 --> 0! = 1 and 1! = 1
elif n == 0 or n == 1:
return 1
# Recursive case: n! = n * (n-1)!
else:
return n * factorial(n - 1)

Get input from the user

n = int(input("Enter a non-negative integer: "))

Display the factorial

print("The factorial of",n, "is:" ,factorial(n))

18. Fibonacci using recursion

def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)

Get the number from the user

terms = int(input("Enter the number of terms: "))

Display the Fibonacci sequence

print("Fibonacci sequence:")
for i in range(terms):
print(fibonacci(i), end=",")

19. Copy file content to another file

import os

source = r'C:\Users\mahes\Documents\STUDY FOR LANGUAGE\web_answers.txt'
destination = r'C:\Users\mahes\Documents\STUDY FOR LANGUAGE\web_answers_copy.txt'
if os.path.exists(source):
with open(source, 'r', encoding='utf-8') as src, open(destination, 'w', encoding='utf-8') as dest:
dest.write(src.read())
print("File copied successfully.")
else:
print("File not found.")

20. Circle class with area and perimeter calculation

from math import pi
class Circle():
def init(self,r):
self.radius = r

def area(self):
    return pi*self.radius**2
def perimeter(self):
    return 2*pi*self.radius

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