0% found this document useful (0 votes)
2 views

pythone3d3

The document contains a collection of 37 Python programs covering various topics such as tax calculation, lambda functions, error handling, shape area and perimeter calculations, and more. Each program is presented with its logic and functionality, demonstrating practical coding examples. Additionally, there is an offer to provide all codes in a single text file or specific programs upon request.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

pythone3d3

The document contains a collection of 37 Python programs covering various topics such as tax calculation, lambda functions, error handling, shape area and perimeter calculations, and more. Each program is presented with its logic and functionality, demonstrating practical coding examples. Additionally, there is an offer to provide all codes in a single text file or specific programs upon request.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

1.

Bike Price + Tax Calculator


python

Copy
Download
price = float(input("Enter bike price (₹): "))
if price > 100000:
tax = price * 0.15
elif price > 50000:
tax = price * 0.10
else:
tax = price * 0.05
print(f"Tax: ₹{tax} | Total: ₹{price + tax}")

Logic:

 Tax rates: 15% (>1L), 10% (50K-1L), 5% (≤50K).


 f-string formats the output neatly.

2. Square & Cube (Lambda)


python

Copy
Download
numbers = [1, 2, 3]
square = list(map(lambda x: x**2, numbers))
cube = list(map(lambda x: x**3, numbers))
print("Squares:", square, "Cubes:", cube)

Logic:

 lambda x: x**2 is a mini-function to square a number.

 map() applies it to every item in the list.

3. Menu-Driven Calculator (Error Handling)


python

Copy
Download
while True:
print("\n1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Exit")
choice = input("Enter choice (1-5): ")
if choice == '5':
break
try:
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
if choice == '1':
print("Result:", a + b)
elif choice == '2':
print("Result:", a - b)
elif choice == '3':
print("Result:", a * b)
elif choice == '4':
print("Result:", a / b)
except:
print("Invalid input! Try again.")

Logic:

 try-except handles crashes (e.g., division by zero).

 Infinite loop (while True) until user exits.

4. Area/Perimeter of Shapes
python

Copy
Download
def circle(radius):
return 3.14 * radius**2, 2 * 3.14 * radius # Area, Perimeter

def rectangle(length, width):


return length * width, 2 * (length + width)

# Test
print("Circle (r=5): Area =", circle(5)[0], "Perimeter =", circle(5)[1])
print("Rectangle (4x6): Area =", rectangle(4, 6)[0], "Perimeter =", rectang
le(4, 6)[1])

Logic:

 Functions return multiple values as tuples.


 Access results using index ([0] for area, [1] for perimeter).

6. Marks Percentage Calculator


python

Copy
Download
marks = [85, 90, 78, 92, 88]
total = sum(marks)
percentage = (total / 500) * 100
print(f"Total: {total}/500 | Percentage: {percentage:.2f}%")

Logic:

 sum() adds all marks.

 :.2f rounds percentage to 2 decimal places.

Need More?

Tell me which program numbers (1-37) you want, and I’ll paste them here with zero
fluff.

OR

Want all codes in a single text file? Let me know—I’ll organize them and share
a Google Drive/Dropbox link. 🚀

No PDFs, no broken links—just raw, runnable code. 😎


saare de 1 se 37 tkinter wala skip

Here are all 37 Python programs (excluding Tkinter/GUI) in simple, runnable code:

1. Bike Price + Tax Calculator


python

Copy
Download
price = float(input("Enter bike price (₹): "))
if price > 100000:
tax = price * 0.15
elif price > 50000:
tax = price * 0.10
else:
tax = price * 0.05
print(f"Tax: ₹{tax} | Total: ₹{price + tax}")

2. Square & Cube Using Lambda


python

Copy
Download
nums = [1, 2, 3]
square = list(map(lambda x: x**2, nums))
cube = list(map(lambda x: x**3, nums))
print("Squares:", square, "Cubes:", cube)

3. Menu-Driven Calculator
python

Copy
Download
while True:
print("\n1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Exit")
choice = input("Enter choice (1-5): ")
if choice == '5':
break
try:
a = float(input("First number: "))
b = float(input("Second number: "))
if choice == '1':
print("Result:", a + b)
elif choice == '2':
print("Result:", a - b)
elif choice == '3':
print("Result:", a * b)
elif choice == '4':
print("Result:", a / b)
except:
print("Invalid input! Try again.")

4. Area/Perimeter Calculator
python

Copy
Download
def circle(r):
return 3.14*r*r, 2*3.14*r

def rectangle(l, b):


return l*b, 2*(l+b)

print("Circle (r=5): Area =", circle(5)[0], "Perimeter =", circle(5)[1])


print("Rectangle (4x6): Area =", rectangle(4,6)[0], "Perimeter =", rectangl
e(4,6)[1])

5. (Skipped - Tkinter)

6. Marks Percentage Calculator


python

Copy
Download
marks = [85, 90, 78, 92, 88]
total = sum(marks)
percent = (total/500)*100
print(f"Total: {total}/500 | Percentage: {percent:.2f}%")

7. Rectangle Area Class


python

Copy
Download
class Area:
def setDim(self, l, b):
self.l = l
self.b = b
def getArea(self):
return self.l * self.b
rect = Area()
rect.setDim(5, 10)
print("Area:", rect.getArea())

8. Map Lists to Dictionary


python

Copy
Download
keys = ['red', 'blue']
values = ['#ff0000', '#00ff00']
color_dict = dict(zip(keys, values))
print(color_dict)

9. Check Element in Tuple


python

Copy
Download
my_tuple = (1, 2, 3, 4)
element = 3
print(f"{element} exists in tuple: {element in my_tuple}")

10. Max/Min in Set


python

Copy
Download
num_set = {5, 2, 8, 1}
print("Max:", max(num_set), "Min:", min(num_set))

11. Check for Duplicates


python

Copy
Download
my_list = [1, 2, 3, 2]
has_duplicates = len(my_list) != len(set(my_list))
print("Has duplicates:", has_duplicates)

12. Employee Class


python

Copy
Download
class Employee:
def __init__(self, name, year, salary, address):
self.name = name
self.year = year
self.salary = salary
self.address = address

e1 = Employee("John", 2020, 50000, "Delhi")


e2 = Employee("Mike", 2021, 45000, "Mumbai")
print(f"{e1.name} joined in {e1.year}, salary {e1.salary}, address {e1.addr
ess}")

13. Rectangle Area/Perimeter Class


python

Copy
Download
class Rectangle:
def __init__(self, l, b):
self.l = l
self.b = b
def area(self):
return self.l * self.b
def perimeter(self):
return 2*(self.l + self.b)

rect = Rectangle(4, 5)
print("Area:", rect.area(), "Perimeter:", rect.perimeter())

14. Word Frequency Counter


python

Copy
Download
from collections import Counter

def count_words(input_file, output_file):


with open(input_file) as f:
words = f.read().split()
word_count = Counter(words)
with open(output_file, 'w') as f:
for word, count in word_count.items():
f.write(f"{word}: {count}\n")
count_words("input.txt", "output.txt")

15-16. (Skipped - Tkinter)

17. Library Management System


python

Copy
Download
library = {}

def issue_book():
book = input("Enter book name: ")
user = input("Enter user name: ")
library[book] = user
print(f"{book} issued to {user}")

def return_book():
book = input("Enter book name: ")
if book in library:
del library[book]
print(f"{book} returned")
else:
print("Book not found")

while True:
print("\n1. Issue\n2. Return\n3. View\n4. Exit")
choice = input("Enter choice: ")
if choice == '1':
issue_book()
elif choice == '2':
return_book()
elif choice == '3':
print("Issued books:", library)
elif choice == '4':
break

18. String Operations


python

Copy
Download
s = "Hello World"
print("0th character:", s[0])
print("3rd to 6th:", s[3:6])
print("6th onwards:", s[6:])
print("Last character:", s[-1])
print("Twice:", s*2)
print("Concatenated:", s + " Python")

19. Longest Word in String


python

Copy
Download
s = "This is a sample string"
longest = max(s.split(), key=len)
print("Longest word:", longest)

20. Distinct Elements


python

Copy
Download
def distinct(lst):
return list(set(lst))

print(distinct([1, 2, 2, 3]))

21. Filter Even/Odd


python

Copy
Download
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x%2==0, nums))
odds = list(filter(lambda x: x%2!=0, nums))
print("Evens:", evens, "Odds:", odds)

22. NumPy Array Operations


python

Copy
Download
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("Subset:", arr[0, 1:3])
reshaped = arr.reshape(3, 2)
print("Reshaped:\n", reshaped)
print("Dimensions:", arr.shape, "Elements:", arr.size)
23. Starts With Character (Lambda)
python

Copy
Download
starts_with = lambda s, char: s.startswith(char)
print(starts_with("Python", "P")) # True

24. Character Count Dictionary


python

Copy
Download
s = "vcetresource"
count = {char: s.count(char) for char in set(s)}
print(count)

25. Max/Min in Set


python

Copy
Download
nums = {5, 2, 8, 1}
print("Max:", max(nums), "Min:", min(nums))

26. Disjoint Sets Check


python

Copy
Download
set1 = {1, 2, 3}
set2 = {4, 5, 6}
print("No common elements:", set1.isdisjoint(set2))

27. Remove Duplicates


python

Copy
Download
lst = [1, 2, 2, 3]
unique = list(set(lst))
print(unique)

28. Separate Even/Odd


python
Copy
Download
nums = [1, 2, 3, 4, 5, 6]
evens = [x for x in nums if x%2==0]
odds = [x for x in nums if x%2!=0]
print("Evens:", evens, "Odds:", odds)

29. Second Largest Number


python

Copy
Download
nums = [5, 2, 8, 1]
sorted_nums = sorted(nums, reverse=True)
print("Second largest:", sorted_nums[1])

30. Electricity Bill Calculator


python

Copy
Download
def calc_bill(units):
if units <= 100:
return 0
elif units <= 200:
return (units-100)*5
else:
return 500 + (units-200)*10

print("Bill for 350 units:", calc_bill(350))

31. String Operations


python

Copy
Download
text = """Ants are found everywhere...""" # Your full text here

# a. Words starting with 's'


s_words = [word for word in text.split() if word.lower().startswith('s')]
print("Starting with 's':", s_words)

# b. Words starting/ending with 's'


s_s_words = [word for word in text.split() if word.lower().startswith('s')
and word.lower().endswith('s')]
print("Starting/ending with 's':", s_s_words)

# c. Words containing 'i'


i_words = [word for word in text.split() if 'i' in word.lower()]
print("Containing 'i':", i_words)

# d. Capitalize each word


capitalized = ' '.join([word.capitalize() for word in text.split()])
print("Capitalized:", capitalized[:50] + "...")

# e. Word frequency
freq = {}
for word in text.split():
freq[word] = freq.get(word, 0) + 1
print("Word frequency:", dict(list(freq.items())[:5]))

32. Custom Module


python

Copy
Download
# Save as mymodule.py
def greet(name):
return f"Hello, {name}!"

# In main.py
import mymodule
print(mymodule.greet("John"))

33. Matrix Addition


python

Copy
Download
matrix1 = [[1, 2], [3, 4]]
matrix2 = [[5, 6], [7, 8]]
result = [[matrix1[i][j] + matrix2[i][j] for j in range(len(matrix1[0]))] f
or i in range(len(matrix1))]
print("Result:", result)

34. Matplotlib Plots


python

Copy
Download
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Plot')
plt.show()

35. Pandas Operations


python

Copy
Download
import pandas as pd
data = {'Name': ['John', 'Mike'], 'Age': [25, 30]}
df = pd.DataFrame(data)
print(df)

36. Sort Dictionary by Value


d = {'a': 5, 'b': 2, 'c': 8}
ascending = dict(sorted(d.items(), key=lambda x: x[1]))
descending = dict(sorted(d.items(), key=lambda x: x[1], reverse=True))
print("Ascending:", ascending)
print("Descending:", descending)

37. Top 3 Shop Items


python

Copy
Download
items = {'item1': 45.50, 'item2': 35, 'item3': 41.30, 'item4': 55, 'item5':
24}
top3 = dict(sorted(items.items(), key=lambda x: x[1], reverse=True)[:3])
print("Top 3:", top3)

You might also like