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

Python lab file

The document contains a series of Python lab exercises covering various programming concepts such as basic arithmetic operations, conditional statements, loops, functions, and data structures. Each lab includes code snippets for tasks like calculating areas, checking for leap years, and implementing algorithms for Fibonacci series and Armstrong numbers. The exercises are designed to help learners practice and understand fundamental programming skills in Python.

Uploaded by

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

Python lab file

The document contains a series of Python lab exercises covering various programming concepts such as basic arithmetic operations, conditional statements, loops, functions, and data structures. Each lab includes code snippets for tasks like calculating areas, checking for leap years, and implementing algorithms for Fibonacci series and Armstrong numbers. The exercises are designed to help learners practice and understand fundamental programming skills in Python.

Uploaded by

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

Python lab files:

Lab 1:
#Print hello
print("Hello")

#Area of circle
pi=3.14
radius=2
area=pi*(radius**2)
print(area)

#Ternary operator
num=10
result="Even"if num%2==0 else "Odd"
print(f"The number is {num} and it is {result}")

Lab 2:
#Amstrong number
input=153
a=input%10
b=input//10
c=b//10
b=b%10
result=(a**3)+(b**3)+(c**3)
print(result)

#Celsius to Fahrenheit
celsius=38
f=(9/5*celsius)+32
print("The fahrenheit is {}".format(f))

#Compound intereset
p=5000
r=5.5
t=3
a=(p*(1+r/100)**t)-p
print("The compound interset is: ",a)

#Distance between two points


import math
x1=10
x2=15
y1=30
y2=20
a=x2-x1
b=math.pow(a,2)
c=y2-y1
d=math.pow(c,2)
e=b+d
distance=math.sqrt(e)
print("The distance between two points is: %3.2f"%distance)

#Fahrenheit to Celsius:
f=77
c=(5/9)*(f-32)
print("The celsius is:",c)

#Leap year (using ternary operator)


year=2000
result="It is a leap year" if((year%400==0) or (year%4==0 and year%100!=0))
else "It is not a leap year"
print(result)
#Odd or even using ternary:
a=10
result="even" if (a%2==0) else "odd"
print("The given number {0} is {1}".format(a,result))

#Palindrome:
num=45654
x=num%10
y=num//10000
z=(num//10)%10
a=(num//1000)%10
result="palindrome" if(x==y and z==a) else "Not a palindrome"
print(result)

#Positive or negative
num=-15
result="positive" if (num>=0) else "Negative"
print("The result is:{}".format(result))

#Area of circle:
pi=3.14159
radius=2
area=pi*(radius**2)
print(area)

# using library function


import math
r=4
area=math.pi*(r**2)
print("area o fthe circle: %2i"%area)
print("Area of the circle is %3.2f"%area)

# consider a incandescent lamp 230v nad 100w determine the lamp resistance
lamp current energy consumed by the lamp in 8hrs
import math
voltage=230
power=100
time=8
current=power/voltage
resistance=(math.pow(voltage,2))/power
energy=power*time
print("lamp current is: %5.2f"%current,"A")
print("lamp resistance is:",resistance,"ohms")
print("Energy consumed by lamp in 8hrs is:",energy,"wh")
#Quadratic equations:
'''import math
a=1
b=-3
c=2
e=(b**2)-4*a*c
d=math.sqrt(e)
root_1=(-b+d)/2*a
root_2=(-b-d)/2*a
print("root 1 is:{}".format(root_1))
print("root 2 is:{}".format(root_2))'''

import cmath
a=1
b=-3
c=2
e=(b**2)-4*a*c
d=cmath.sqrt(e)
root_1=(-b+d)/2*a
root_2=(-b-d)/2*a
print("root 1 is:{}".format(root_1))
print("root 2 is:{}".format(root_2))
#Simple interest
p=150
r=17
t=8
si=(p*r*t)/100
print("The simple interest is %4.2f"%si)

#Swapping with third variable


a=5
b=10
c=b
b=a
a=c
print("The value of a after swapping {}".format(a))
print("THe value of b after swapping {}".format(b))

#Swapping without third variable


a=14
b=7
a=b+a
b=a-b
a=a-b
print("Value of a after swapping {}".format(a))
print("Value of b after swapping {}".format(b))

# other method
a=5
b=10
print("The value of a before swapping:",a)
print("THe value of b before swapping:",b)
a,b=b,a
print("The value of a after swapping:",a)
print("The value of b after swapping:",b)

#Triangles side checking


s1=10
s2=5
s3=10
equi=(s1==s2 and s1==s3 and s2==s3)
print("the given side {} {} {} belongs to equilateral triangle:
{}".format(s1,s2,s3,equi))
iso=(s1==s2 or s1==s3 or s2==s3)
print("The given triangle is an isosceles triangle:{}".format(iso))
scalene=(s1!=s2 and s1!=s3 and s2!=s3)
print("The given triangle is an scalene triangle:{}".format(scalene))

#Volume of cylinder
import math
radius=5
height=10
pi=3.14
area=(pi*math.pow(radius,2))*height
print("Area of the cylinder is {}".format(area))

#Grading
sub1=int(input("Enter the mark of Electromagentic theory:"))
sub2=int(input("Enter the mark of Analog integrtaed circuit:"))
sub3=int(input("Enter the mark of signals and systems:"))
sub4=int(input("Enter the mark of Digital electronis:"))
sub5=int(input("Enter the mark of Statistucs and datascience:"))
sub6=int(input("Enetr the mark of python programming:"))
average=(sub1+sub2+sub3+sub4+sub5+sub6)/6
if(average>=90):
print("your grade is O")
elif(average<90 and average>=80):
print("Your grade is A")
elif(average<80 and average>=70):
print("Your grade is B")
elif(average<70 and average>=60):
print("Your grade is C")
else:
print("sorry you are fail!!")

#Graing with given average


marks=int(input("Enter the average og all your marks:"))
if(marks>=90):
print("your grade is A")
elif(marks<90 and marks>=80):
print("Your grade is B")
elif(marks<80 and marks>=70):
print("Your grade is C")
elif(marks<70 and marks>=60):
print("Your grade is D")
else:
print("sorry you are fail!!")

#Greatest of three numbers


num1=int(input("enter a number:"))
num2=int(input("enter a number:"))
num3=int(input("enter a number:"))
if(num1>=num2 and num1>=num3):
print("The greatest of the three number is {}".format(num1))
elif(num2>=num3):
print("the greatest of three numbers is {}".format(num2))
else:
print("the greates of three numbers is {}".format(num3))

#Greatest of three numbers


num1=int(input("Enter a number1:"))
num2=int(input("Enter a number2:"))
num3=int(input("Enter a number3:"))
if(num1<num2 and num1<num3):
if(num2<num3):
print("{} is the greatest".format(num3))
else:
print("{} is the greatest".format(num2))
else:
print("{} is the greatest".format(num1))

#Leap year
year=int(input("enter a year:"))
if((year%4==0)and (year%400==0 or year%100!=0)):
print("It is a leap year")
else:
print("It is not a leap year")

#positive or negative using if-elif-else


num=int(input("Enter a number:"))
if(num>0):
print("The given number {} is a positive number".format(num))
elif(num==0):
print("The given number {} is zero".format(num))
else:
print("The given number {} is a negative number".format(num))

#odd or even
input=int(input("Enter a number:"))
if(input%2==0):
print("The given number {} is an even number!!".format(input))
else:
print("The given number {} is a odd number!!".format(input))

#user credentials
org_username="ponabirami"
org_password="123@"
name=input("Enter your username:")
if(name==org_username):
password=input("Enter your passsword")
if(password==org_password):
print("welcome!! Login successful")
else:
print("wrong password!! access denied")
else:
print("retry!! invalid username")

#Voting eligibility
age=int(input("Enter your age:"))
if(age>=18):
print("Congrats!!you are eligible to vote")
else:
print("Sorry!! yor are not eligible to vote")
#Voting eligibility using nested if
age=int(input("Enter your age:"))
if(age>0):
if(age>=18):
print("You are eligible to vote!!")
else:
print("Sorry!! you are not eligible to vote!!")
else:
print("Sorry make sure your input age is correct")

#Weekdays
day=int(input("Enter the number of the day:"))
if(day==1):
print("the day is monday")
elif(day==2):
print("The day is tuesday")
elif(day==3):
print("The day is wednesday")
elif(day==4):
print("The day is thursday")
elif(day==5):
print("The day is friday")
elif(day==6):
print("The day is saturday")
elif(day==7):
print("The day is sunday")
else:
print("enter a number between 1-7")

#while loop program:


n=input("You're in a lost forest.Go left or right?(right/left)")
while n=="right":
n=input("You're in alost forest.Go left or right?")
print("You got out of the lost forest")

#While and for loop:


mysum=0
for i in range(5,11,2):
mysum+=i
print(mysum)

i=7
sum=0
while i<10:
sum=sum+i
i+=1
print(sum)
i=5
sum=0
while i<11:
sum=sum+i
i+=2
print(sum)

#Odd numbers from 1-50


i=1
while(i<=50):
if(i%2==0):
i=i+1
continue
else:
print(i)
i=i+1
#Continue:
i=1
while i<=10:
if(i==7):
i=i+1
continue
else:
print(i)
i=i+1
#Leap year from 1896-200
for i in range(1896,2000):
if(i%4==0 and(i%400==0 or i%100!=0)):
print("{} is a leap year".format(i))
#Factorial:
factorial=1
for i in range(1,6):
factorial*=i
print(factorial)

#Fibonacci series:
a=0
b=1
print(a)
for c in range(1,10):
c=a+b
a=b
b=c
print(a)

#Reverse order:
for i in range(10,0,-1):
print(i)
#Multipication table from 1-5
for i in range(1,6):
for j in range(1,11):
m=i*j
print("{}X{}={}".format(i,j,m))
#Right triangle star:
for i in range(1,6):
for j in range(1,6):
if(i==j):
print(i*"*")
#Sum of n natural numbers:
sum=0
for i in range(1,101):
sum+=i
print(sum)

n=100
sum1=(n*(n+1))/2
print(sum1)

result="True" if (sum==sum1) else "False"


print(result)

#Armstrong number:
for i in range (100,1000):
a=i%10
b=i//10
b=b%10
c=i//100
num = ((a*3)+(b*3)+(c*3))
if (num == i):
print("{} is a amstrong number".format(num))
#KVL
r1=int(input("Enter the value of R1:"))
r2=int(input("Enter the value of R2:"))
voltage=int(input("Enter the source voltage:"))
Req=r1+r2
print("The equivalent resistance is: {}".format(Req))
I=(voltage)/(Req)
kvl=(-10)+(r1*I)+(r2*I)
if (kvl==0):
print("The given kvl equation is correct")
print("the sum of voltage in a closed loop is zero ")
else:
print("The given kvl equation is false")
print("The sum of voltages in a closed loop is not zero")

#KCL:
sum1=0
sum2=0
n=input("Is there any entering current:(y/n)")
while n!="n":
I1=int(input("Enter the entering current:"))
i=input("Is there any other current:(y/n)")
if (i=="n"):
break
sum1+=I1
m=input("Is ther any leaving current:(y/n)")
while m!="n":
I2=int(input("Entering the leaving current:"))
j=input("Is there any other current:(y/n)")
if (j=="n"):
break
sum2+=I2
if (sum1==sum2):
print("The sum of entering current is equal to sum of leaving current")
else:
print("The sum of entering current is not equal to sum of leaving current")

#Superposition theorem:
v1=int(input("Enter the voltage 1:"))
v2=int(input("Enter the voltage source 2:"))
R1=int(input("Enter the resistor value 1:"))
R2=int(input("Enter the resistor value 2:"))
R3=int(input("Enter the resistor value 3:"))
print("----When voltage source 1 is activated----")
r1=(R3*R2)/(R3+R2)
Req1=r1+R1
I1=v1/Req1
current1=(I1*R2)/(R3+R2)
print("The value of current when V1 is activated: {}A".format(current1))
print("----When voltage source 2 is activated----")
r2=(R1*R2)/(R1+R2)
Req2=r2+R3
I2=v2/Req2
current2=(I2*R2)/(R2+R1)
print("The value of current when V2 is activated: {}A".format(current2))
total=current1+current2
print("The total current is: {}A".format(total))

#Permutation and combinations:


n=int(input("Enter a number : "))
r=int(input("Enter value of r: "))
i=j=k=1
fact1=fact2=fact3=1
while i<=n:
fact1*=i
i+=1
nfact=fact1
while j<=(n-r):
fact2*=j
j+=1
nrfact=fact2
p=nfact/nrfact
print("Permutations = {}".format(p))
while k<=r:
fact3*=k
k+=1
rfact=fact3
c=nfact/(nrfact*rfact)
print("Combination: ",c)

#Sum of the two digit number


sum=0
n=int(input("Enter a two digit number:"))
while n/10!=0:
a=n%10
sum+=a
n=n//10
print("The sum of the given digit number is:{}".format(sum))
August 8:
#Adding elements to list
L=[2,'a',4,[1,2]]
print(len(L))
print(L[0])
print(L[1])
print(L[2])
print(L[3])
print(L[2]+1)

i=2
print(L[i-1])

L[1]=5
print(L)

#Merging two lists:


L1=[]
n=int(input("No of elements to be added:"))
i=0
while i<n:
a=int(input("Enter the element to be added in the list:"))
L1.append(a)
i=i+1
L2=[]
m=int(input("No of elements to be added:"))
j=0
while j<m:
b=int(input("Enter the element to be added in the list:"))
L2.append(b)
j=j+1
L3=L1+L2
print("The new merged list is:{}".format(L3))
L3.sort()
print("The sorted list is: {}".format(L3))
#Greatest number in a list:
l=[]
for i in range(5):
n=int(input("Enter a number to be appended:"))
l.append(n)
print(l)
greatest=0
for j in l:
if (j>greatest):
greatest=j
print("greatest number is:",greatest)
# List operations
a=[1,2,3,4,5]
a.append(6)
print(a)

a.insert(0,0)
print(a)

b=[7,8,9]
a.extend(b)
print(a)

print(a.index(5))

a.sort()
print(a)

a.reverse()
print(a)

a.pop()
print(a)
#print(a.pop())

print(a.pop(0))
a.remove(1)
print(a)

print(a.count(6))

c=a.copy()
print(c)

print(len(a))

print(min(a))
print(max(a))

a.clear()
print(a)

'''del(a)
print(a)'''

L=[9,6,0,3]
print(sorted(L))
print(L)
L.sort()
print(L)
L.reverse()
print(L)

# Tuple + list:
T=(1,2,3,4)
L=[5,6,7]
N=tuple(L)
print(N)
T1=T+N
print(T1)

# List + Tuple:
L=[1,2,3]
T=(4,5,6)
L.append(T)
print(L)

#Cloning:
cool=['blue','green','grey']
chill=cool[:]
chill.append('black')
print(chill)
print(cool)

#Alias:
hot=['red','yellow','orange']
warm=hot
warm.append('pink')
print(warm)
print(hot)

#Total of elements in a list:


total=0
L=[2,5,3]
for i in range(len(L)):
total+=L[i]
print(total)
total=0
for i in L:
total+=i
print(total)

#Nested list:
warm=['yellow','orange']
hot=['red']
brightcolors=[warm]
brightcolors.append(hot)
print(brightcolors)
hot.append('pink')
print(hot)
print(brightcolors)

August 22

#Dictionary operations:
grades={'Ana':'B','John':'A+','Denis':'A','Katy':'A'}

# to get keys from the dictionary


print("Keys:",grades.keys())

# to get values from the dictionary


print("Values:",grades.values())

# to print the respective value of the given key


print("John's grade is:",grades.get('John'))
print("Mike's grade is:",grades.get('Mike','Not found'))

# to print key value in a dictionary as tuple pair


print("Items:",grades.items())

#removes the key from the dictionary and the removed value is printed
removed_grade=grades.pop('Denis')
print("Removed key:",removed_grade)
print(grades)

# removes the last item from the dictionary


last_item=grades.popitem()
print("Removed last element:",last_item)
print("Updated dictionary:",grades)

'''#print(grades.popitem())
#a=grades.pop('Nivetha')
last_item=grades.popitem()
print("Removed last element:",last_item)
print("Updated dictionary:",grades)

last_item=grades.popitem()
print("Removed last element:",last_item)
print("Updated dictionary:",grades)

ast_item=grades.popitem()
print("Removed last element:",last_item)
print("Updated dictionary:",grades)'''

# returns value of a key if it is in the dictionary if not inserts the jkey with the
specified value and returns the value
default_grade=grades.setdefault('Mike','B')
print("Mike's grade:",default_grade)
print("Updated dictionary",grades)

# allocated values for key


new_dict=dict.fromkeys(['Tom','Jerry'],'Unknown')
print("Updated dictionary:",new_dict)

# to update dictionary and add another dictionary with the old one
grades={'Ana':'B','John':'A+','Mike':'B'}
grades.update({'Lisa':'A','Mark':'B+'})
print("Updated dictionary:",grades)

# copies dictionary with another variable


grades={'Ana': 'B', 'John': 'A+', 'Mike': 'B', 'Lisa': 'A', 'Mark': 'B+'}
copied_dict=grades.copy()
print("Copied dictionary:",copied_dict)
# to clear all the key-value pair
grades.clear()
print("Cleared dictionary:",grades)

# del is used to delete the memory


del grades
#print(grades)

grades={'Ana': 'B', 'John': 'A+', 'Mike': 'B', 'Lisa': 'A', 'Mark': 'B+'}
sorted_keys=sorted(grades.keys())
print(sorted_keys)

sorted_items=dict(sorted(grades.items()))
print(sorted_items)

sorted_values=sorted(grades.values())
print(sorted_values)
my_dict={} #empty dictionary
print(my_dict)

grades={'Ana':'B','John':'A+','Denise':'A','Katy':'A','Ana':'C'}
print(grades)
print(grades['John'])
#print(grades['Sylvan']) #produces an error because no such key is available

# to add an entry
grades['Sylvan']='A'
print(grades)

# if the key is in the dictionary returs true or false


print('John' in grades)
print('Daniel' in grades)
print(len(grades))

# deleteing entry in dictionary


del(grades['Ana'])
print(grades)
print(len(grades))

# to get only keys from the given dictionary


print(grades.keys())

# to get values from the dictionary


print(grades.values())

# Sorting dictionary using values:


grades={3:98.4,1:90.7,2:99.8,4:92.5,7:100}
dict_sort={}
value=sorted(grades.values(),reverse=True)
for i in value:
for k,v in grades.items():
if i==v:
dict_sort.update({k:i})
print(dict_sort)

Other method:
grades={3:98.4,1:90.7,2:99.8,4:92.5}
print('input dict',grades)
sorted_g=dict(sorted(grades.items(),key=lambda item:item[1],reverse=True))
print('sorted as per values',sorted_g)

August 29
Apply and prove KVL and KCL:
# Apply and prove KCL and KVL for the given circuit
voltage_source=int(input("Enter the value of voltage source:"))
R1=int(input("enter the value of R1:"))
R2=int(input("Enter the value of R2:"))
R3=int(input("enter the value of R3:"))
Req1=((R2*R3)/(R2+R3))
Req2=R1+Req1
print(Req2)
#KCL
I1=(voltage_source)/Req2
I2=(I1*R3)/(R2+R3)
I3=(I1*R2)/(R2+R3)
i1=format(I1,"3.2f")
i2=format(I2,"3.2f")
i3=format(I3,"3.2f")

print("I1=",format(I1,"3.2f"),"I2=",format(I2,"3.2f"),"I3=",format(I3,"3.2f"))
if (I1==I2+I3):
print("---KCL is verified---")

else:
print("---It does not satisfy KCL law--")

#KVL
v1=R1*I1
print("V1",format(v1,"3.2f"))
v2=R2*I2
print("V2",format(v2,"3.2f"))
v3=R3*I3
print("V3",format(v3,"3.2f"))

loop1=voltage_source-v1-v3
loop2=v2-v3
print("Sum of voltages in loop1",loop1)
print("Sum of voltages in loop2",loop2)
if (loop1==loop2==0):
print("---KVL is satisfied---")
else:
print("---KVL is not satisfied---")

my_dict={}
my_dict.update({R1:i1,R2:i2,R3:i3})
print(my_dict)

#OP-AMP:
R1=220
R2=220
V1=10.3
V2=10.4
IB1=V1/R1
IB2=V2/R2
input_bias=(IB1+IB2)/2
input_offset=(IB2-IB1)
print("Input bias current=",format(input_bias,"3.2f"),"mA")
print("Input offset current=",format(input_offset,"3.4f"),"mA")

You might also like