Help us create more useful apps! We've already built a screen recorder(availabe in APPS section), and we're planning even more practical and developer-friendly applications.
Help us create more useful apps! We've already built a screen recorder(availabe in APPS section), and we're planning even more practical and developer-friendly applications.
defcalculate_total_cost(units):
if 0 <= units <= 100:
total_cost = 0elif units <= 200:
total_cost = (units - 100) * 1.5elif units <= 500:
total_cost = (100 * 0) + (100 * 2) + ((units - 200) * 3)
else:
total_cost = (100 * 0) + (100 * 3.5) + (300 * 4.60) + ((units - 500) * 6.60)
print(f"Total Cost: {total_cost}")
units = int(input("Enter the number of units: "))
calculate_total_cost(units)
1. B RETAIL SHOP BILLING
Retail Shop Billing Code
defcalculate_amount(n, fixed_price):
rate = (n * fixed_price) + n
if rate >= 500:
amount = rate + (0.02 * rate)
else:
amount = rate
print(f"Amount: {amount}")
n = int(input("Enter the number of products: "))
fixed_price = float(input("Enter the fixed price of each product: "))
calculate_amount(n, fixed_price)
1. C SINE SERIES
Sine Series Example
defcalculate_series(x, terms):
n = 1
t = x
total_sum = x
whilen <= terms:
t = (t * (-1) * x * x) / (2 * n * (2 * n + 1))
total_sum += t
n += 1
print(f"Sum: {total_sum}")
x = float(input("Enter the value of x: "))
terms = int(input("Enter the number of terms: "))
calculate_series(x, terms)
1. D WEIGHT OF MOTOR BIKE
Motorbike Weight Calculation
defcalculate_weight():
mass = float(input("Enter the mass of the motorbike (in kg): "))
weight = mass * 9.8print(f"Weight of the motorbike: {weight} N")
calculate_weight()
1. E WEIGHT OF STEEL BAR
Steel Bar Weight Calculation
defcalculate_steel_bar_weight():
diameter = float(input("Enter the diameter of the steel bar (in mm): "))
length = float(input("Enter the length of the steel bar (in meters): "))
weight = (diameter * diameter * length) / 162print(f"Weight of the steel bar: {weight} kg")
calculate_steel_bar_weight()
1. F COMPUTE ELECTRICAL CURRENT IN THREE PHASE AC CIRCUIT
Compute Electrical Current in Three-Phase AC Circuit
importmathdefcalculate_power():
pf = float(input("Enter the power factor (pf): "))
V = float(input("Enter the voltage (V): "))
I = float(input("Enter the current (I): "))
power = math.sqrt(3) * pf * V * I
print(f"Power: {power} W")
calculate_power()
2. A EXCHANGE THE VALUE OF TWO VARIABLES
Exchange the Value of Two Variables
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Before Swapping")
print("a =", a)
print("b =", b)
# Swap the values of a and b
a, b = b, a
print("After Swapping")
print("a =", a)
print("b =", b)
2. B CIRCULATE THE VALUES OF N VARIABLES
Circulate Values of N Variables
defcirculate(A, N):
foriinrange(1, N+1):
B = A[i:] + A[:i]
print("Circulation", i, "=", B)
A = [91, 92, 93, 94, 95]
N = int(input("Enter n: "))
circulate(A, N)
n = int(input("Enter the value of n: "))
foriinrange(1, n+1, 2):
print(i)
3. B NUMBER PATTERN
Number Pattern
N = 5foriinrange(1, N + 1):
forkinrange(N, i, -1):
print(" ", end="")
forjinrange(1, i + 1):
print(j, end="")
forjinrange(i - 1, 0, -1):
print(j, end="")
print("")
3. C PYRAMID PATTERN
Pyramid Pattern
n = int(input("Enter the number of rows: "))
foriinrange(0, n):
forjinrange(0, n - i - 1):
print(" ", end="")
forjinrange(0, 2 * i + 1):
print("*", end="")
print("")
4. A OPERATIONS OF LISTS
Operations on Lists
List_name = ['Brick', 'Cement', 'Wooden frame', 'gravel', 'tiles']
print('positive index- index 0:', List_name[0])
print('Negative indexing index -5:', List_name[-5])
print('items from index 2 to index 4:', List_name[2:5])
print("Before Append:", List_name)
List_name.append('wires')
print("After Append:", List_name)
List_name1 = ['sand', 'glass']
List_name.extend(List_name1)
print("After Extend:", List_name)
List_name[2] = 'ironframe'print("changing the third item to ironframe:", List_name)
del List_name[0:2]
print('After deleting first two items:', List_name)
List_name.remove('ironframe')
print('After removing ironframe:', List_name)
print("Total Elements in a list:", len(List_name))
4. B OPERATIONS OF TUPLE
Operations on Tuples
Tuple_name = ('gear', 'break', 'power steering', 'AC', 'Tyre')
print('positive index- index 0:', Tuple_name[0])
print('Negative indexing index -5:', Tuple_name[-5])
print('items from index 2 to index 4:', Tuple_name[2:5])
print("Before Append:", Tuple_name)
Tuple_name1 = ('wires', 'wiper')
print("After Append:", Tuple_name + Tuple_name1)
Tuple_name1 = Tuple_name * 2print('After repeating:', Tuple_name1)
print("Total Elements in a tuple:", len(Tuple_name1))
components = {"Brake": 2, "Tyre": 4, "Steering": 1}
print(components)
x = components.copy()
print(x)
x = components.get("Tyre")
print(x)
x = components.items()
print(x)
components.update({"color": "White"})
print(components)
x = components.pop("Brake")
print(x)
print(components)
x = components.setdefault("Brake", "Tyre")
print(x)
print(components)
x = components.values()
print(x)
y = 1
thisdict = dict.fromkeys(components, y)
print(thisdict)
x = components.keys()
print(x)
components.clear()
print(components)
6. A FACTORIAL OF A NUMBER
Factorial of a Number
deffact(n):
if n == 0:
return1else:
x = n * fact(n - 1)
return x
n = int(input("Enter a value:"))
y = fact(n)
print(y)
6. B LARGEST NUMBER IN A LIST
Largest Number in a List
defmax(N):
max_num = N[0]
for i in N:
if i > max_num:
max_num = i
return max_num
N = [99, 76, 43, 56, 34]
print("Maximum number =", max(N))
6. C FIND AREA OF CIRCLE
Find Area of Shape
defRectangleArea():
l = int(input("Enter l:"))
b = int(input("Enter b:"))
A = l * b
print("Area of rectangle", A)
defSquareArea():
a = int(input("Enter a:"))
A = a * a
print("Area of square", A)
choice = int(input("Enter a choice:"))
if choice == 1:
RectangleArea()
elif choice == 2:
SquareArea()
else:
print("No shape found")
7. A TO REVERSE A STRING
Reverse a Given String
word = input("Enter a word:")
rev_word = word[::-1]print(rev_word)
7. B PALINDROME OR NOT
Palindrome or Not
word = input("Enter a word:")
rev_word = word[::-1]if word == rev_word:
print("It is a palindrome")
else:
print("It is not a palindrome")
7. C COUNT CHARACTERS IN STRING
Count Characters in a String
word = input("Enter a word:")
letter = input("Enter the character:")
count = 0for char in word:
if char == letter:
count +=1print("The letter", letter, "appears", count, "times in the word")
7. D REPLACE A CHARACTER IN A STRING
Code Snippet with Copy Feature
word = ("Enter a word: ")old_char = ("Enter the character you want to replace: ")new_char = ("Enter the new character: ")new_str = ("")forcharin word:
if char == old_char:
new_str += new_char
else:
new_str += char
print(new_str)
8. A PANDAS
Pandas Example
import pandas as pd
a = []
b = []
d = int(input('Enter the number of employees:'))
for i in range(0, d):
y = int(input('Enter employee id:'))
a.append(y)
x = input('Enter name of employee: ')
b.append(x)
e = {'Employee_id': a, 'Employee_name': b}
df1 = pd.DataFrame(e, columns=['Employee_id', 'Employee_name'])
print(df1)
8. B NUMPY
NumPy Example
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[4, 3], [2, 1]])
print("Array sum:\n", a + b)
print("Array multiplication:\n", a * b)
print("Matrix multiplication:\n", a.dot(b))
print("Array division:\n", a / b)
from scipy import special
from scipy import linalg
import numpy as np
cb = special.cbrt([27, 64])
print(cb)
a = special.exp10(3)
print(a)
b = special.exp2(3)
print(b)
c = special.sindg(90)
print(c)
d = special.cosdg(45)
print(d)
two_d_array = np.array([[4, 5], [3, 2]])
determinant = linalg.det(two_d_array)
print("Determinant:", determinant)
inverse = linalg.inv(two_d_array)
print("Inverse:\n", inverse)
9. A COPY CHARACTERS FROM ONE FILE TO ANOTHER
Copy Character from One File to Another
print("Enter the name of Source file:")
sFile = input()
print("Enter the name of Target file:")
tFile = input()
fileHandle = open(sFile, "r")
texts = fileHandle.readlines()
fileHandle.close()
fileHandle = open(tFile, "w")
for s in texts:
fileHandle.write(s)
fileHandle.close()
print("\nFile copied successfully!")
9. B WORD COUNT
Word Count Example
from collections import Counter
def word_count(fname):
with open(fname, 'r') as f:
return Counter(f.read().split())
fname = input('Enter the file name: ')
num_words = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_words += len(words)
print("Number of words:", num_words)
print("Number of each word count in the file:\n", word_count(fname))
9. C LONGEST WORD
Longest Word Example
def longest_words(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words iflen(word) == max_len]
filename = input('Enter the name of file: ')print(longest_words(filename))
10. A DIVIDE BY ZERO ERROR
Divide by Zero Error Example
x = int(input("Enter the value of x = "))
y = int(input("Enter the value of y = "))
try:
z = x / yprint("Result =", z)
exceptZeroDivisionError:
print("Divide by zero Error")
10. B VOTER'S AGE VALIDITY
Voter's Age Validity Example
defvoter():
try:
age = int(input("Enter your age: "))
ifage >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
exceptValueError:
print("Age must be a valid number")
exceptIOError:
print("Enter correct value")
except:
print("An error occurred")
voter()
10. C STUDENT'S MARK RANGE VALIDATION
Student's Mark Range Validation Example
try:
print("Enter marks obtained in 5 subjects:")
S1 = int(input())
if S1 < 0 or S1 > 100:
raiseValueError("The value is out of range")
S2 = int(input())
if S2 < 0 or S2 > 100:
raiseValueError("The value is out of range")
S3 = int(input())
if S3 < 0 or S3 > 100:
raiseValueError("The value is out of range")
S4 = int(input())
if S4 < 0 or S4 > 100:
raiseValueError("The value is out of range")
S5 = int(input())
if S5 < 0 or S5 > 100:
raiseValueError("The value is out of range")
finally:
print("This is always executed")
tot = S1 + S2 + S3 + S4 + S5
avg = tot / 5
if avg >= 91 and avg <= 100:
print("Your Grade is A")
elif avg >= 81 and avg < 91:
print("Your Grade is B")
elif avg >= 71 and avg < 81:
print("Your Grade is C")
elif avg >= 61 and avg < 71:
print("Your Grade is D")
else:
print("Your Grade is F")