PYTHON PRACTICAL CODES (R-2021)

Support Us Retrieve User Data from Cookies
Profile Picture
Dynamic Time Display


1.A DEVELOPING FLOWCHART FOR ELECTRICITY BILLING

Total Cost Calculation
def calculate_total_cost(units):
    if 0 <= units <= 100:
        total_cost = 0
    elif units <= 200:
        total_cost = (units - 100) * 1.5
    elif 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
        def calculate_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
        def calculate_series(x, terms):
            n = 1
            t = x
            total_sum = x
            while n <= 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
def calculate_weight():
    mass = float(input("Enter the mass of the motorbike (in kg): "))
    weight = mass * 9.8
    print(f"Weight of the motorbike: {weight} N")

calculate_weight()
    

1. E WEIGHT OF STEEL BAR

Steel Bar Weight Calculation
def calculate_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) / 162
    print(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
import math

def calculate_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
def circulate(A, N):
    for i in range(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)
    

2. C DISTANCE BETWEEN TWO POINTS

Distance Between Two Points
import math

x1 = int(input("Enter x1: "))
y1 = int(input("Enter y1: "))
x2 = int(input("Enter x2: "))
y2 = int(input("Enter y2: "))

distance = ((x1 - x2)**2 + (y1 - y2)**2)**0.5
print("Distance =", distance)
    

3. A TO DISPLAY ODD SERIES

Display Odd Series
n = int(input("Enter the value of n: "))

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

3. B NUMBER PATTERN

Number Pattern
N = 5

for i in range(1, N + 1):
    for k in range(N, i, -1):
        print(" ", end="")

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

    for j in range(i - 1, 0, -1):
        print(j, end="")

    print("")
    

3. C PYRAMID PATTERN

Pyramid Pattern
n = int(input("Enter the number of rows: "))

for i in range(0, n):
    for j in range(0, n - i - 1):
        print(" ", end="")

    for j in range(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 * 2
print('After repeating:', Tuple_name1)

print("Total Elements in a tuple:", len(Tuple_name1))
    

5. A OPERATIONS OF SETS AND DICTIONARIES

Operations on Sets and Dictionaries
language1 = {'C', 'C++', 'JAVA'}
language2 = {'VB', 'PYTHON', 'ORACLE', 'JAVA'}

print(language1)
print(language2)

language1.add('SQL')
print(language1)

language1.remove('SQL')
print(language1)

print(language1 | language2)
print(language2.union(language1))

print(language1 & language2)
print(language1.intersection(language2))

print(language1 - language2)
print(language2.difference(language1))

print(language1 ^ language2)
    

5. B OPERATIONS OF SETS AND DICTIONARIES

Operations on Sets and Dictionaries
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
def fact(n):
    if n == 0:
        return 1
    else:
        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
def max(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
def RectangleArea():
    l = int(input("Enter l:"))
    b = int(input("Enter b:"))
    A = l * b
    print("Area of rectangle", A)

def SquareArea():
    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 = 0
for char in word:
    if char == letter:
        count += 1
print("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 = ("")

for char in 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)
    

8. C MATPLOTLIB

Gaussian Histogram
import matplotlib.pyplot as plt
from numpy.random import normal

gaussian_numbers = normal(size=1000)

plt.hist(gaussian_numbers, bins=30)
plt.title("Gaussian Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
    

8. D SCIPY

SciPy Example
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 if len(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 / y
    print("Result =", z)
except ZeroDivisionError:
    print("Divide by zero Error")
    

10. B VOTER'S AGE VALIDITY

Voter's Age Validity Example
def voter():
    try:
        age = int(input("Enter your age: "))
        if age >= 18:
            print("Eligible to vote")
        else:
            print("Not eligible to vote")
    except ValueError:
        print("Age must be a valid number")
    except IOError:
        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:
        raise ValueError("The value is out of range")
    S2 = int(input())
    if S2 < 0 or S2 > 100:
        raise ValueError("The value is out of range")
    S3 = int(input())
    if S3 < 0 or S3 > 100:
        raise ValueError("The value is out of range")
    S4 = int(input())
    if S4 < 0 or S4 > 100:
        raise ValueError("The value is out of range")
    S5 = int(input())
    if S5 < 0 or S5 > 100:
        raise ValueError("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")
    

11 STIMULATE ELLIPTICAL ORBIT USING PYGAME

Simulate Elliptical Orbits using Pygame
import pygame
import math
import sys

pygame.init()

screen = pygame.display.set_mode((600, 300))
pygame.display.set_caption("Elliptical orbit")

clock = pygame.time.Clock()

xradius = 250
yradius = 100

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    screen.fill((0, 0, 0))

    pygame.draw.circle(screen, (255, 69, 0), [300, 150], 40)
    pygame.draw.ellipse(screen, (255, 255, 255), [50, 50, 500, 200], 1)

    for degree in range(0, 360, 10):
        x1 = int(math.cos(degree * 2 * math.pi / 360) * xradius) + 300
        y1 = int(math.sin(degree * 2 * math.pi / 360) * yradius) + 150
        pygame.draw.circle(screen, (0, 255, 0), [x1, y1], 20)

    pygame.display.flip()

    for degree in range(0, 360, 1):
        x1 = int(math.cos(degree * 2 * math.pi / 360) * xradius) + 300
        y1 = int(math.sin(degree * 2 * math.pi / 360) * yradius) + 150

        screen.fill((0, 0, 0))
        pygame.draw.circle(screen, (255, 69, 0), [300, 150], 40)
        pygame.draw.ellipse(screen, (255, 255, 255), [50, 50, 500, 200], 1)
        pygame.draw.circle(screen, (0, 255, 0), [x1, y1], 20)

        pygame.display.flip()

        clock.tick(30)
    

12 BOUNCING BALL

Bouncing Ball Pygame Example
import sys, pygame

pygame.init()

size = width, height = 700, 250
speed = [1, 1]
background = 255, 255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")

ball = pygame.image.load("ball.jpg")
ballrect = ball.get_rect()

while True:
    pygame.time.delay(2)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    ballrect = ballrect.move(speed)

    if ballrect.left < 0 or ballrect.right > width:
        speed[0] = -speed[0]

    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = -speed[1]

    screen.fill(background)
    screen.blit(ball, ballrect)

    pygame.display.flip()
    

No comments:

Post a Comment

APPLICATIONS

Support Us Help us create more useful apps! We've already built a screen recorder(availabe in APPS...