Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
50 views

Python Chit

Uploaded by

zorosenpai056
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Python Chit

Uploaded by

zorosenpai056
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

1.

Python Program to convert USD to INR

dollars = float(input("Please enter dollars:"))


rupees = dollars * 64
print(rupees, " Rupees")

2. Python Program to calculate area volume of cylinder.

import math
radius = float(input("Enter the radius of the cylinder: "))
height = float(input("Enter the height of the cylinder: "))
surface_area = 2 * math.pi * radius * (radius + height)
volume = math.pi * radius**2 * height
print(f"Surface Area of the Cylinder: {surface_area:.2f} square units")
print(f"Volume of the Cylinder: {volume:.2f} cubic units")

3. Python Program to convert Bits to Gigabyte and Megabyte.

bits = int(input("enter bit: "))


byte = bits / 8
kb = byte / 1024
mb = kb / 1024
gb = mb / 1024
tb = gb / 1024
print(bits, "Bits is equal to:\n", mb, "Megabytes:\n", gb, "Gigabytes:\n", tb,
"Terabytes:\n")

4. Python program to check if given year is a leap year or not.

year=int(input("enter year : "))


if year%4==0:
print("year is a leap year")
else:
print("not leap year")

5. Python program to check largest of three numbers

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


b =int ( input ( " enter number b: " ) )
c =int ( input ( " enter number c: " ) )
if ((a > b ) & (a > c ) ) :
print ( " a is greater " )
elif ( ( a < b ) & (c < b ) ) :
print ( " b is greater " )
else:
print ( " c is greater " )
6. Python Program to check given no is even or odd:

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


if n % 2 == 0:
print(n, "is an Even Number")
else:
print(n, "is an Odd Number")

7. Write a program to take input as five subject marks and display the grade.

maths = float(input("Enter marks for Mathematics: "))


physics = float(input("Enter marks for Physics: "))
chemistry = float(input("Enter marks for Chemistry: "))
english = float(input("Enter marks for English: "))
computers = float(input("Enter marks for Computers: "))

total_marks = maths + physics + chemistry + english + computers


percentage = (total_marks / 500) * 100

if percentage >= 90:


grade = 'A'
elif percentage >= 80:
grade = 'B'
elif percentage >= 70:
grade = 'C'
elif percentage >= 60:
grade = 'D'
else:
grade = 'F'

print(f"Total Marks: {total_marks}")


print(f"Percentage: {percentage}%")
print(f"Grade: {grade}")

8. Write a program to print the following patterns using loop:


*
***
*****
***
*

# Pattern 1
for i in range(1, 6):
print(" " * (5 - i) + "*" * (2*i - 1))

# Pattern 2
for i in range(3, 0, -1):
print(" " * (3 - i) + "*" * (2*i - 1))

9. Write a Python program to find the sum of first 10 natural numbers using for loop.

sum = 0
for i in range(1, 11):
sum += i

print(f"Sum of first 10 natural numbers: {sum}")

10. Write a program to print the following patterns using loop:


*
**
***

# Pattern 3
for i in range(1, 4):
print("*" * i)

11. Write a Python program to print all even numbers between 1 to 100 using while loop.

num = 1
while num <= 100:
if num % 2 == 0:
print(num)
num += 1

12. Write a Python program to print Fibonacci series.

def fibonacci(n):
fib_series = [0, 1]
for i in range(2, n):
fib_series.append(fib_series[i-1] + fib_series[i-2])
return fib_series

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


fib = fibonacci(n_terms)
print("Fibonacci Series:", fib)

13. Write a Python program to calculate factorial of a number.

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

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


fact = factorial(number)
print(f"Factorial of {number} is: {fact}")

14. Write a Python Program to Reverse a Given Number.

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


reverse = 0

while number > 0:


digit = number % 10
reverse = reverse * 10 + digit
number //= 10

print ("Reversed Number:", reverse)

15. Write a Python program takes in a number and finds the sum of digits in a number.

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


sum_digits = 0

while number > 0:


digit = number % 10
sum_digits += digit
number //= 10

print("Sum of digits:", sum_digits)

16. Write a Python program that takes a number and checks whether it is a palindrome or
not.

def is_palindrome(n):
return str(n) == str(n)[::-1]

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


if is_palindrome(number):
print(f"{number} is a palindrome")
else:
print(f"{number} is not a palindrome")
17. Write a Python program to sum all the items in a list.

numbers = [10, 20, 30, 40, 50]


total = sum(numbers)
print("Sum of all items in the list:", total)

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

numbers = [1, 2, 3, 4, 5]
product = 1

for num in numbers:


product *= num

print("Product of all items in the list:", product)

19. Write a Python program to get the largest number from a list.

numbers = [10, 30, 20, 50, 40]


largest = max(numbers)
print("Largest number in the list:", largest)

20. Write a Python program to get the smallest number from a list.

numbers = [10, 30, 20, 50, 40]


smallest = min(numbers)
print("Smallest number in the list:", smallest)

21. Write a Python program to reverse a list.

numbers = [1, 2, 3, 4, 5]
reversed_list = numbers[::-1]
print("Reversed list:", reversed_list)

22. Write a Python program to find common items from two lists.

list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]

common_items = list(set(list1) & set(list2))


print("Common items between the two lists:", common_items)
23. Write a Python program to select the even items of a list.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


even_numbers = [num for num in numbers if num % 2 == 0]
print("Even items of the list:", even_numbers)

24. Create a tuple and find the minimum and maximum number from it.

my_tuple = (10, 30, 20, 50, 40)


min_number = min(my_tuple)
max_number = max(my_tuple)
print("Minimum number in the tuple:", min_number)
print("Maximum number in the tuple:", max_number)

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

my_tuple = (1, 2, 3, 2, 4, 5, 4, 6)
repeated_items = [item for item in my_tuple if my_tuple.count(item) > 1]
repeated_items = list(set(repeated_items)) # Remove duplicates
print("Repeated items in the tuple:", repeated_items)

26. Print the number in words for Example: 1234 => One Two Three Four.

def number_to_words(num):
num_words = {
'0': 'Zero', '1': 'One', '2': 'Two', '3': 'Three', '4': 'Four',
'5': 'Five', '6': 'Six', '7': 'Seven', '8': 'Eight', '9': 'Nine'
}
return ' '.join([num_words[digit] for digit in str(num)])

number = 1234
print(f"{number} => {number_to_words(number)}")

27. Write a Python program to create a set, add member(s) in a set and remove one item
from set.

my_set = {1, 2, 3, 4, 5}
print("Initial set:", my_set)

my_set.add(6)
print("Set after adding 6:", my_set)

my_set.remove(3)
print("Set after removing 3:", my_set)
28. Write a Python program to perform following operations on set: intersection of sets,
union of sets, set difference, symmetric difference, clear a set.

set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
# Intersection of sets
intersection = set1.intersection(set2)
print("Intersection of sets:", intersection)
# Union of sets
union = set1.union(set2)
print("Union of sets:", union)
# Set difference
difference = set1.difference(set2)
print("Set difference:", difference)
# Symmetric difference
symmetric_difference = set1.symmetric_difference(set2)
print("Symmetric difference:", symmetric_difference)
# Clear a set
set1.clear()
print("Set after clearing:", set1)

29. Write a Python program to find maximum and the minimum value in a set.

my_set = {10, 30, 20, 50, 40}


max_value = max(my_set)
min_value = min(my_set)
print("Maximum value in the set:", max_value)
print("Minimum value in the set:", min_value)

30. Write a Python program to find the length of a set.

my_set = {1, 2, 3, 4, 5,6,7,8,9}


set_length = len(my_set)
print("Length of the set:", set_length)

31. Write a Python script to sort (ascending and descending) a dictionary by value.

my_dict = {'a': 10, 'b': 30, 'c': 20}


sorted_asc = dict(sorted(my_dict.items(), key=lambda x: x[1]))
sorted_desc = dict(sorted(my_dict.items(), key=lambda x: x[1], reverse=True))

print("Dictionary sorted by value (ascending):", sorted_asc)


print("Dictionary sorted by value (descending):", sorted_desc)

32. Write a Python script to concatenate following dictionaries to create a new one. Sample
Dictionary: dic1 = {1:10, 2:20} dic2 = {3:30, 4:40} dic3 = {5:50, 6:60}
dic1 = {1: 10, 2: 20}
dic2 = {3: 30, 4: 40}
dic3 = {5: 50, 6: 60}

concatenated_dict = {**dic1, **dic2, **dic3}


print("Concatenated dictionary:", concatenated_dict)

33. Write a Python program to combine two dictionary adding values for common keys.
d1={'a': 100, 'b': 200, 'c':300} d2 ={'a': 300, 'b': 200, 'd':400}

from collections import Counter

d1 = {'a': 100, 'b': 200, 'c': 300}


d2 = {'a': 300, 'b': 200, 'd': 400}

combined_dict = Counter(d1) + Counter(d2)


print("Combined dictionary with added values for common keys:",
dict(combined_dict))

34. Write a Python program to print all unique values in a dictionary. Sample Data:
[{"V":"s001"}, {"V": "$002"}, {"V": "S001"}, {"V": "S005"},{"VII":"S005"}, {"V":"S009"},
{"VIII":"S007"}]

data = [{"V": "s001"}, {"V": "$002"}, {"V": "S001"}, {"V": "S005"}, {"VII":
"S005"}, {"V": "S009"}, {"VIII": "S007"}]

unique_values = set(val for d in data for val in d.values())


print("Unique values in the dictionary:", unique_values)

35. Write a Python program to find the highest 3 values in a dictionary.

my_dict = {'a': 100, 'b': 200, 'c': 300, 'd': 400, 'e': 500}
highest_values = sorted(my_dict.values(), reverse=True)[:3]
print("Highest 3 values in the dictionary:", highest_values)

36. Write a Python function that accepts a string and calculate the number of upper case
letters and lower case letters.

def count_upper_lower(string):
upper_count = sum(1 for char in string if char.isupper())
lower_count = sum(1 for char in string if char.islower())
return upper_count, lower_count

input_string = "Hello World"


upper, lower = count_upper_lower(input_string)
print("Number of uppercase letters:", upper)
print("Number of lowercase letters:", lower)

37. Write a Python program to generate a random float where the value is between 5 and 50
using Python math module

import random
import math

random_float = random.uniform(5, 50)


print("Random float between 5 and 50:", random_float)

38. Write a Python function that takes a number as a parameter and check the number is
prime or not.

def is_prime(number):
if number <= 1:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True

num = int(input("Enter a number to check if it's prime: "))


if is_prime(num):
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")

39. Write a Python function to calculate the factorial of a number (a non-negative integer).
The function accepts the number as an argument.

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

num = int(input("Enter a non-negative integer to calculate factorial: "))


if num < 0:
print("Factorial is not defined for negative numbers.")
else:
fact = factorial(num)
print(f"Factorial of {num} is: {fact}")

40. Write a Python program to create a user defined module that will ask your college name
and will display the name of the college.

# college_module.py

def get_college_name():
college_name = input("Enter your college name: ")
return college_name

# Make a new File main.py and run it


# main.py

import college_module

college = college_module.get_college_name()
print("College name:", college)

41. Write a Python program that will calculate area and circumference of circle using inbuilt
Math Module

import math

radius = float(input("Enter the radius of the circle: "))

area = math.pi * radius**2


circumference = 2 * math.pi * radius

print("Area of the circle:", area)


print("Circumference of the circle:", circumference)

42. Write a Python program that will display Calendar of given month using Calendar
Module.

import calendar

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


month = int(input("Enter the month (1-12): "))

print(calendar.month(year, month))
43. Write a Python program to create two matrices and perform addition, subtraction, and
multiplication and division operation on matrix.

import numpy as np

# Create two matrices


matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])

# Addition
addition = np.add(matrix1, matrix2)
print("Matrix Addition:")
print(addition)

# Subtraction
subtraction = np.subtract(matrix1, matrix2)
print("\nMatrix Subtraction:")
print(subtraction)

# Multiplication
multiplication = np.dot(matrix1, matrix2)
print("\nMatrix Multiplication:")
print(multiplication)

# Division (element-wise)
division = np.divide(matrix1, matrix2)
print("\nMatrix Division:")
print(division)

44. Write a Python program to concatenate two strings.

str1 = "Hello"
str2 = "World"

concatenated_str = str1 + " " + str2


print("Concatenated string:", concatenated_str)

45. Write a NumPy program to generate six random integers between 10 and 30.

import numpy as np

random_integers = np.random.randint(10, 31, size=6)


print("Random integers between 10 and 30:", random_integers)
46. Write a Python program to create a class to print an integer and a character with two
methods having the same name but different sequence of the integer and the character
parameters. For example, if the parameters of the first method are of the form (int n,
char c), then that of the second method will be of the form (char c, int n).

class MyClass:
def method1(self, n, c):
print(f"Integer: {n}, Character: {c}")

def method2(self, c, n):


print(f"Character: {c}, Integer: {n}")

obj = MyClass()
obj.method1(10, 'A')
obj.method2('B', 20)

47. Write a Python program to create a class to print the area of a square and a rectangle.
The class has two methods with the same name but different number of parameters.
The method for printing area of rectangle has two parameters which are length and
breadth respectively while the other method for printing area of square has one
parameter which is side of square.

class AreaCalculator:
def area_rectangle(self, length, breadth):
print(f"Area of Rectangle: {length * breadth}")

def area_square(self, side):


print(f"Area of Square: {side * side}")

obj = AreaCalculator()
obj.area_rectangle(5, 10)
obj.area_square(5)

48. Write a Python program to create a class 'Degree' having a method 'getDegree' that
prints "I got a degree". It has two subclasses namely 'Undergraduate' and 'Postgraduate'
each having a method with the same name that prints "I am an Undergraduate" and "I
am a Postgraduate" respectively. Call the method by creating an object of each of the
three classes.

class Degree:
def getDegree(self):
print("I got a degree")

class Undergraduate(Degree):
def getDegree(self):
print("I am an Undergraduate")

class Postgraduate(Degree):
def getDegree(self):
print("I am a Postgraduate")

degree_obj = Degree()
ug_obj = Undergraduate()
pg_obj = Postgraduate()

degree_obj.getDegree()
ug_obj.getDegree()
pg_obj.getDegree()

49. Create a class Employee with data members: name, department and salary. Create
suitable methods for reading and printing employee information.

class Employee:
def __init__(self, name, department, salary):
self.name = name
self.department = department
self.salary = salary

def read_info(self):
self.name = input("Enter employee name: ")
self.department = input("Enter department: ")
self.salary = float(input("Enter salary: "))

def display_info(self):
print(f"Name: {self.name}, Department: {self.department}, Salary:
{self.salary}")

emp = Employee("", "", 0)


emp.read_info()
emp.display_info()

50. Python program to read and print student's information using two classes using simple
inheritance.

class Person:
def __init__(self, name):
self.name = name

class Student(Person):
def __init__(self, name, roll_number):
super().__init__(name)
self.roll_number = roll_number

def display_info(self):
print(f"Name: {self.name}, Roll Number: {self.roll_number}")

student = Student("John", 123)


student.display_info()

51. Write a Python program to implement multiple inheritances.

class Parent1:
def method1(self):
print("Method 1 from Parent 1")

class Parent2:
def method2(self):
print("Method 2 from Parent 2")

class Child(Parent1, Parent2):


def method3(self):
print("Method 3 from Child")

obj = Child()
obj.method1()
obj.method2()
obj.method3()

52. Write a Python program to Check for ZeroDivisionError Exception.

try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero!")

53. Write a Python program to create user defined exception that will check whether the
password is correct or not?

class PasswordError(Exception):
pass

def check_password(password):
correct_password = "Rudra"
if password != correct_password:
raise PasswordError("Incorrect password!")
try:
user_password = input("Enter password: ")
check_password(user_password)
print("Password is correct!")
except PasswordError as e:
print(f"Error: {e}")

You might also like