Python Lab Working Code
Python Lab Working Code
Source Code:
num = 2
print "The number (", num, ") is of type", type(num)
num = 3.0
print "The number (", num, ") is of type", type(num)
num = 3+5j
print "The number ", num, " is of type", type(num)
print "The number ", num, " is complex number?", isinstance(3+5j, complex)
Output:
The number ( 2 ) is of type <type 'int'>
The number ( 3.0 ) is of type <type 'float'>
The number (3+5j) is of type <type 'complex'>
The number (3+5j) is complex number? True
2.Write a program to perform different Arithmetic Operations on numbers in
Python.
Source Code :
#Output
Enter First number: 10
Enter Second number 30
Sum of 10 and 30 is : 40
Difference of 10 and 30 is : -20
Product of 10 and 30 is : 300
Division of 10 and 30 is : 0
Floor Division of 10 and 30 is : 0
Exponent of 10 and 30 is : 1000000000000000000000000000000
Modulus of 10 and 30 is : 10
3.Write a program to create, concatenate and print a string and accessing
sub-string from a given string.
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
#String Concatenation
str1 = 'Hello'
str2 ='World!'
# using + operator
print 'str1 + str2 = ', str1 + str2
#Technique One
# Straight forward approach for Python 2.7 and Python 3.6
# Executes the conditional statement when the substring is found
if substring in string:
print "Your substring was found!"
#TEchnique Two
word = 'Ezio Auditore da Firenze'
result = word.find('da')
print "Substring 'da ' found at index:", result
import time
import datetime
print datetime.date.today().strftime("%A"),
datetime.date.today().strftime("%B"), datetime.datetime.now().strftime("%d
%H:%M:%S"), "IST", datetime.date.today().strftime("%Y")
#Output
Wednesday July 31 23:08:01 IST 2019
5.Write a program to create, append, and remove lists in python.
Source Code:
# Creating list
my_list = [1, 2, 3]
# appending values to a list
my_list.append(4)
print(my_list)
# removing values from a list
my_list.remove(2)
print my_list
Output:
[1, 2, 3, 4]
[1, 3, 4]
6.Write a program to demonstrate working with tuples in python.
Source Code:
print "Empty tuple"
my_tuple = ()
print(my_tuple) # Output: ()
print "Tuple having integers"
my_tuple2 = (1, 2, 3)
print(my_tuple2) # Output: (1, 2, 3)
print(a) # 3
print(b) # 4.6
print(c) # dog
my_tuple6 = ("hello")
print(type(my_tuple)) # <class 'str'>
print(my_tuple9[0]) # 'p'
print(my_tuple9[5]) # 't'
# Output: 't'
print(my_tuple10[-1])
# Output: 'p'
print(my_tuple10[-6])
print "Tuple Slicing"
my_tuple11 = ('p','r','o','g','r','a','m','i','z')
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple13)
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
my_tuple14 = ('p','r','o','g','r','a','m','i','z')
print(my_tuple15.count('p')) # Output: 2
print(my_tuple15.index('l')) # Output: 3
print ""
my_tuple16 = ('a','p','p','l','e',)
# In operation
# Output: True
print('a' in my_tuple16)
# Output: False
print('b' in my_tuple16)
# Not in operation
# Output: True
print('g' not in my_tuple16)
# Output:
# Hello John
# Hello Kate
for name in ('John','Kate'):
print("Hello",name)
Output:
Empty tuple
()
Tuple having integers
(1, 2, 3)
tuple with mixed datatypes
(1, 'Hello', 3.4)
Nested Datatypes
('mouse', [8, 4, 6], (1, 2, 3))
()
3
4.6
dog
<type 'tuple'>
Creating a tuple having one element and finding type
<type 'tuple'>
Accesing tuple element by element
p
t
Nested Tuple
Nested Index
s
4
t
p
Tuple Slicing
('r', 'o', 'g')
('p', 'r')
('i', 'z')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Mutable datatypes in immutable tuple
(4, 2, 3, [9, 5])
Tuple Reassignment
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
(1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')
Counting elements in Tuple
2
3
True
False
True
('Hello', 'John')
('Hello', 'Kate')
7.Write a program to demonstrate working with dictionaries in python.
Source Code:
# empty dictionary
my_dict = {}
# using dict()
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# my_dict.get('address')
# my_dict['address']
# update value
my_dict['age'] = 27
#Output: {'age': 27, 'name': 'Jack'}
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
print(my_dict)
# create a dictionary
# Output: 16
print(squares.pop(4))
print(squares)
# Output: (1, 1)
print(squares.popitem())
print(squares)
del squares[5]
# Output: {2: 4, 3: 9}
print(squares)
squares.clear()
# Output: {}
print(squares)
del squares
# Throws Error
# print(squares)
print(marks)
print(item)
list(sorted(marks.keys()))
print(odd_squares)
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: True
# Output: True
# Output: False
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(squares[i])
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: 5
print(len(squares))
# Output: [1, 3, 5, 7, 9]
print(sorted(squares))
print(people)
print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex'])
people[3] = {}
people[3]['name'] = 'Luna'
people[3]['age'] = '24'
people[3]['sex'] = 'Female'
people[3]['married'] = 'No'
print(people[3])
print(people[4])
del people[3]['married']
del people[4]['married']
print(people[3])
print(people[4])
print(people)
Jack
26
16
{1: 1, 2: 4, 3: 9, 5: 25}
(1, 1)
{2: 4, 3: 9, 5: 25}
{2: 4, 3: 9}
{}
('Science', 0)
('Math', 0)
('English', 0)
True
True
False
81
25
49
[1, 3, 5, 7, 9]
{1: {'age': '27', 'name': 'John', 'sex': 'Male'}, 2: {'age': '22', 'name': 'Marie', 'sex': 'Female'}}
John
27
Male
{1: {'age': '27', 'name': 'John', 'sex': 'Male'}, 2: {'age': '22', 'name': 'Marie', 'sex': 'Female'}}
('\nPerson ID:', 1)
('Age:', '27')
('Name:', 'John')
('Sex:', 'Male')
('\nPerson ID:', 2)
('Age:', '22')
('Name:', 'Marie')
('Sex:', 'Female')
:
8.Write a python program to find largest of three numbers.
Source Code:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
print "The largest number is",largest
Output
Enter first number: 10
Enter second number: 12
Enter third number: 14
The largest number is 14.0
9.Write a Python program to convert temperatures to and from Celsius,
Fahrenheit. [ Formula: c/5 = f-32/9]
Code
temp = input("Input the temperature you like to convert? ")
degree = int(temp)
result = 0
notation = raw_input("Input the notation? ")
i_convention = str(notation)
o_convention =""
print degree,i_convention
if i_convention.upper() == "C":
result = int(round((9 * degree) / 5 + 32))
o_convention = "Fahrenheit"
elif i_convention.upper() == "F":
result = int(round((degree - 32) * 5 / 9))
o_convention = "Celsius"
Output
Input the temperature you like to convert? 30
Input the notation? F
30 F
The temperature in Celsius is -2 degrees.
10.Write a Python program to construct the following pattern, using a
nested for loop
**
***
****
*****
****
***
**
*
Source Code:
import sys
a = '''* '''
print("Program to print start pattern:\n");
for i in range (0, 5):
for j in range(0, i + 1):
sys.stdout.write(a)
print("\r")
for i in range (5, 0, -1):
for j in range(0, i -1):
sys.stdout.write(a)
print("\r")
Output:
*
**
***
****
*****
****
***
**
*
11. Write a Python script that prints prime numbers less than 20.
Source Code::
Output:
Enter upper limit: 30
2
3
5
7
11
13
17
19
23
29
12. Write a python program to find factorial of a number using Recursion.
Source Code:
#Factorial Method
def factorial(n):
return 1
else:
return(n*factorial(n-1))
n = int(input("Enter number:"))
print("Factorial:")
print(factorial(n))
Output:
Enter a number: 5
Output 1:
FORMULA FOR RIGHT ANGLED TRIANGLES HYPOTENUSE=
SQRT(SIDE1*SIDE1+SIDE2*SIDE2)
Length of side 1:3
Length of side 2:4
Length of side 3:5
It's a right triangle with side 3 as hypotenuse
14. Write a python program to define a module to find Fibonacci Numbers
and import the module to another program.
Source Code:
Output:
#If the file is directly executed the output is as below
Enter the number upto which you want the fibonacci numbers
30
0 1 1 2 3 5 8 13 21
But if the file is imported into another module and called.
Source Code:
#Filename - test.py
import fibo
fibo.fib(30) #First function in the module prints all the numbers
a= fibo.fib2(30) # Second function of the module returns all the numbers
as a list
print a
Output:
0 1 1 2 3 5 8 13 21
[0, 1, 1, 2, 3, 5, 8, 13, 21]
15. Write a python program to define a module and import a specific
function in that module to another program.
Source Code:
#FIlename - operations.py
def add(a, b):
result = a + b
return result
if __name__ == "__main__":
import sys
a = add(int(sys.argv[1]),int(sys.argv[2]))
print(a)
#Filename - mainfile.py
Input Commands:
try:
with open(file1_name) as f:
with open(file2_name, "w") as f1:
for line in f:
f1.write(line)
except IOError as e:
print e
Output:
Please enter your file name
test.txt
Please enter your file name
out.txt
Completed Successfully
17. Write a program that inputs a text file. The program should print all of
the unique words in the file in alphabetical order.
Source Code:
file1 = open("random.txt","r")
file1_contents = file1.readline()
the_string_list1 = file1_contents.split(" ")
the_string_list2 = []
for value in the_string_list1:
if(value not in the_string_list2):
the_string_list2.append(value)
Output:
The file contents originally
The file contents after having only the ubnique elements in sorted order
Output:
1-I,5-V,10-X,50-L,100-C,500-D,1000-M
Enter your Roman Number
MM
2000
19. Write a Python class to implement pow(x, n)
Source Code:
class py_solution:
def pow(self, x, n):
if x==0 or x==1 or n==1:
return x
if x==-1:
if n%2 ==0:
return 1
else:
return -1
if n==0:
return 1
if n<0:
return 1/self.pow(x,-n)
val = self.pow(x,n/2)
if n%2 ==0:
return val*val
return val*val*x
base_val =float(raw_input("Enter your base value: \n"))
power_val = int(raw_input("Enter your power value: \n"))
print py_solution().pow(base_val,power_val)
base_val2 =float(raw_input("Enter your base value: \n"))
power_val2 = int(raw_input("Enter your power value: \n"))
print py_solution().pow(base_val2,power_val2)
base_val3 =float(raw_input("Enter your base value: \n"))
power_val3 = int(raw_input("Enter your power value: \n"))
print py_solution().pow(base_val3,power_val3)
Output:
Enter your base value:
2
Enter your power value:
-3
0.125
Enter your base value:
3
Enter your power value:
5
243.0
Enter your base value:
100
Enter your power value:
0
1
20. Write a Python class to reverse a string word by word.
Source Code:
class py_solution:
def reverse_words(self, s):
return ' '.join(reversed(s.split()))
some_string = raw_input("Enter the string you want to reverse: \n")
print(py_solution().reverse_words(some_string))
Output:
Enter the string you want to reverse:
This is a python program for reversal
reversal for program python a is This