Python Lab exercises-II
1. Python program to find the area of a triangle whose sides are given
import math
a = float(input("Enter the length of side a: "))
b = float(input("Enter the length of side b: "))
c = float(input("Enter the length of side c: "))
s = (a+b+c)/2
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
print("Area of the triangle is: ", area)
2. Python program to find the largest number in a list without using built-in functions
numbers = [3,8,1,7,2,9,5,4]
big = numbers[0]
position = 0
for i in range(len(numbers)):
if (numbers[i]>big):
big = numbers[i]
position = i
print("The largest element is ",big," which is found at position",position)
3. Python program to insert a number to any position in a list
numbers = [3,4,1,9,6,2,8]
print(numbers)
x = int(input("Enter the number to be inserted: "))
y = int(input("Enter the position: "))
numbers.insert(y,x)
print(numbers)
4. Python program to delete an element from a list by index
numbers = [3,4,1,9,6,2,8]
print(numbers)
x = int(input("Enter the position of the element to be deleted: "))
numbers.pop(x)
print(numbers)
Strings
5. Check if "NIELIT" is present or not in the following text
txt = "NIELIT - National Institute of Electronics and IT!"
if "NIELIT" not in txt:
print("No, 'NIELIT' is NOT present.")
else:
print("Yes, 'NIELIT' is present.")
Python - List
6. To determine if a specified item is present in a list use the in keyword
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
else:
print("No, 'apple' is not in the fruits list")
Python Dictionaries
7. Python program to print all the items in a dictionary
phone_book = {
'Johny' : [ '8592970000', '[email protected]' ],
'Boby': [ '7994880000', '[email protected]' ],
'Tomy' : [ '9749552647' , '[email protected]' ]
}
for k,v in phone_book.items():
print(k, ":", v)
8. Python program to display the sum of n numbers using a list
numbers = []
num = int(input('How many numbers: '))
for n in range(num):
x = int(input('Enter number '))
numbers.append(x)
print("Sum of numbers in the given list is :", sum(numbers))
Python Functions
9. Python program to print full name of 3 persons by passing information as arguments into
functions
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Python Arrays
10. Create an array of car brands names.
cars = ["Ford", "Volvo", "BMW"]
car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"
for x in cars:
print(x)
Python Classes and Objects
11. Create a class named Person, use the __init__() function to assign values for name and age
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)