1.Write a program to demonstrate different number data types in Python.
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 :
num1 = int(input('Enter First number: '))
num2 = int(input('Enter Second number '))
add = num1 + num2
dif = num1 - num2
mul = num1 * num2
div = num1 / num2
floor_div = num1 // num2
power = num1 ** num2
modulus = num1 % num2
print 'Sum of ',num1 ,'and' ,num2 ,'is :',add
print 'Difference of ',num1 ,'and' ,num2 ,'is :',dif
print 'Product of' ,num1 ,'and' ,num2 ,'is :',mul
print 'Division of ',num1 ,'and' ,num2 ,'is :',div
print 'Floor Division of ',num1 ,'and' ,num2 ,'is :',floor_div
print 'Exponent of ',num1 ,'and' ,num2 ,'is :',power
print 'Modulus of ',num1 ,'and' ,num2 ,'is :',modulus
#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.
#To create and print a string
# all of the following are equivalent
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
the world of Python"""
print(my_string)
#String Concatenation
str1 = 'Hello'
str2 ='World!'
# using + operator
print 'str1 + str2 = ', str1 + str2
# using * operator to repeat string
print 'str1 * 3 =', str1 * 3
#to access a string
string = "Hello Agnosticdev, I love Tutorials"
substring = "Agnosticdev"
#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'
# returns first occurrence of Substring
result = word.find('Audi')
print "Substring 'Audi' found at index:", result
result = word.find('da')
print "Substring 'da ' found at index:", result
# How to use find() normally
#For verification only and not for getting the index
# Here -1 returned by the find() function denotes that given substring is
not there at all
#find() has both a start and stop index. Eg find(‘string’,start,stop)
if (word.find('Black Anna') != -1):
print "Contains given substring "
else:
print "Doesn't contains given substring"
4.Write a python script to print the current date in the following format “Sun
May 29 02:26:23 IST 2017”
Source Code:
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 "tuple with mixed datatypes"
my_tuple3 = (1, "Hello", 3.4)
print(my_tuple3) # Output: (1, "Hello", 3.4)
print "Nested Datatypes"
my_tuple4 = ("mouse", [8, 4, 6], (1, 2, 3))
# Output: ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple4)
my_tuple5 = 3, 4.6, "dog"
print(my_tuple) # Output: 3, 4.6, "dog"
# tuple unpacking is also possible
a, b, c = my_tuple5
print(a) # 3
print(b) # 4.6
print(c) # dog
my_tuple6 = ("hello")
print(type(my_tuple)) # <class 'str'>
print "Creating a tuple having one element and finding type"
my_tuple7 = ("hello",)
print(type(my_tuple7)) # <class 'tuple'>
print "Accesing tuple element by element"
my_tuple9 = ('p','e','r','m','i','t')
print(my_tuple9[0]) # 'p'
print(my_tuple9[5]) # 't'
# IndexError: list index out of range
# print(my_tuple[6])
# Index must be an integer
# TypeError: list indices must be integers, not float
# my_tuple[2.0]
print "Nested Tuple"
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print "Nested Index"
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) # 4
my_tuple10 = ('p','e','r','m','i','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')
# elements 2nd to 4th
# Output: ('r', 'o', 'g')
print(my_tuple11[1:4])
# elements beginning to 2nd
# Output: ('p', 'r')
print(my_tuple11[:-7])
# elements 8th to end
# Output: ('i', 'z')
print(my_tuple11[7:])
# elements beginning to end
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple11[:])
my_tuple12 = (4, 2, 3, [6, 5])
# TypeError: 'tuple' object does not support item assignment
# my_tuple[1] = 9
print "Mutable datatypes in immutable tuple"
# However, item of mutable element can be changed
my_tuple12[3][0] = 9 # Output: (4, 2, 3, [9, 5])
print(my_tuple12)
print "Tuple Reassignment"
# Tuples can be reassigned
my_tuple13 = ('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')
# can't delete items
# TypeError: 'tuple' object doesn't support item deletion
# del my_tuple[3]
# Can delete an entire tuple
del my_tuple14
# NameError: name 'my_tuple' is not defined
#print(my_tuple14)
print "Counting elements in Tuple"
my_tuple15 = ('a','p','p','l','e',)
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 = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
my_dict = {'name':'Jack', 'age': 26}
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# Trying to access keys which doesn't exist throws error
# my_dict.get('address')
# my_dict['address']
my_dict = {'name':'Jack', 'age': 26}
# update value
my_dict['age'] = 27
#Output: {'age': 27, 'name': 'Jack'}
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
print(my_dict)
# create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
# remove a particular item
# Output: 16
print(squares.pop(4))
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)
# remove an arbitrary item
# Output: (1, 1)
print(squares.popitem())
# Output: {2: 4, 3: 9, 5: 25}
print(squares)
# delete a particular item
del squares[5]
# Output: {2: 4, 3: 9}
print(squares)
# remove all items
squares.clear()
# Output: {}
print(squares)
# delete the dictionary itself
del squares
# Throws Error
# print(squares)
marks = {}.fromkeys(['Math','English','Science'], 0)
# Output: {'English': 0, 'Math': 0, 'Science': 0}
print(marks)
for item in marks.items():
print(item)
# Output: ['English', 'Math', 'Science']
list(sorted(marks.keys()))
squares = {x: x*x for x in range(6)}
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares)
odd_squares = {x: x*x for x in range(11) if x%2 == 1}
# Output: {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(odd_squares)
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: True
print(1 in squares)
# Output: True
print(2 not in squares)
# membership tests for key only not value
# Output: False
print(49 in squares)
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
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))
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
print(people)
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex'])
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
people[3] = {}
people[3]['name'] = 'Luna'
people[3]['age'] = '24'
people[3]['sex'] = 'Female'
people[3]['married'] = 'No'
print(people[3])
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married':
'No'}}
people[4] = {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married':
'Yes'}
print(people[4])
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married':
'No'},
4: {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married':
'Yes'}}
del people[3]['married']
del people[4]['married']
print(people[3])
print(people[4])
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female'},
4: {'name': 'Peter', 'age': '29', 'sex': 'Male'}}
del people[3], people[4]
print(people)
people = {1: {'Name': 'John', 'Age': '27', 'Sex': 'Male'},
2: {'Name': 'Marie', 'Age': '22', 'Sex': 'Female'}}
for p_id, p_info in people.items():
print("\nPerson ID:", p_id)
for key in p_info:
print(key + ':', p_info[key])
Output
Jack
26
{'age': 27, 'name': 'Jack'}
{'age': 27, 'name': 'Jack', 'address': 'Downtown'}
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}
('Science', 0)
('Math', 0)
('English', 0)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 1, 3: 9, 9: 81, 5: 25, 7: 49}
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
{'age': '24', 'married': 'No', 'name': 'Luna', 'sex': 'Female'}
{'age': '29', 'married': 'Yes', 'name': 'Peter', 'sex': 'Male'}
{'age': '24', 'name': 'Luna', 'sex': 'Female'}
{'age': '29', 'name': 'Peter', 'sex': '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"
print "The temperature in", str(o_convention), "is", str(result),
"degrees."
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::
upper_limit=int(input("Enter upper limit: "))
for a in range(2,upper_limit+1):
k=0 #Setting a counter
for i in range(2,a//2+1):
if(a%i==0):
k=k+1 #incrementing counter if number is divisible wholly
if(k<=0):
print(a)
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):
if(n <= 1):
return 1
else:
return(n*factorial(n-1))
n = int(input("Enter number:"))
print("Factorial:")
print(factorial(n))
Output:
Enter a number: 5
The factorial of 5 is 120
13. Write a program that accepts the lengths of three sides of a triangle as
inputs. The program output should indicate whether or not the triangle is a
right triangle (Recall from the Pythagorean Theorem that in a right triangle,
the square of one side equals the sum of the squares of the other two
sides).
Source Code:
from math import sqrt
print("FORMULA FOR RIGHT ANGLED TRIANGLE IS HYPOTENUSE=
SQRT(SIDE1*SIDE1+SIDE2*SIDE2)")
a = int(input("Length of side 1:"))
b = int(input("Length of side 2:")) #User input
c = int(input("Length of side 3:"))
if c==sqrt((a*a + b*b)): #Determines if it's a right triangle
print("It's a right triangle with side 3 as hypotenuse")
elif b==sqrt((c*c + a*a)): #Determines if it's a right triangle
print("It's a right triangle with side 2 as hypotenuse")
elif a==sqrt((b*b + c*c)): #Determines if it's a right triangle
print("It's a right triangle with side 1 as hypotenuse")
else:
print("It's not a right triangle")
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:
#File Name - fibo.py
# Fibonacci numbers module
import sys
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while a < n:
sys.stdout.write(str(a)+" ")
a, b = b, a+b
print " "
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
if __name__ == "__main__":
fib(int(input("Enter the number upto which you want the fibonacci
numbers \n")))
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
from operations import add
num1 = int(input("Enter your first number \n"))
num2 = int(input("Enter your second number \n"))
result = add(num1,num2)
print "The result is ",result
Input Commands:
#If the operations.py is directly called along with parameters passed
techtariq@skynet:~/Desktop/py_tests$ python python_prog.py 20 30
50
#If mainfile.py is called
Enter your first number
20
Enter your second number
40
The result is 60
16. Write a script named copyfile.py. This script should prompt the user for
the names of two text files. The contents of the first file should be input and
written to the second file.
Source Code:
file1_name = raw_input("Please enter your file name \n")
file2_name = raw_input("Please enter your file name \n")
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)
print "The file contents originally \n"
print the_string_list1
print " \n The file contents after keeping only the unique elements \n"
print the_string_list2
print " \n The file contents after having only the unique elements in
sorted order \n"
the_string_list2.sort()
print the_string_list2
Output:
The file contents originally
['jcb', 'jcb', 'acb', 'dcb', 'ecb', 'ocb', 'ocb', 'paper', 'paper',
'aadvark', 'aadvark']
The file contents after keeping only the unique elements
['jcb', 'acb', 'dcb', 'ecb', 'ocb', 'paper', 'aadvark']
The file contents after having only the ubnique elements in sorted order
['aadvark', 'acb', 'dcb', 'ecb', 'jcb', 'ocb', 'paper']
18. Write a Python class to convert an integer to a roman numeral
Source Code:
class py_solution:
def roman_to_int(self, s):
rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500,
'M': 1000}
int_val = 0
for i in range(len(s)):
if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]:
int_val += rom_val[s[i]] - 2 * rom_val[s[i-1]]
else:
int_val += rom_val[s[i]]
return int_val
print "1-I,5-V,10-X,50-L,100-C,500-D,1000-M"
a = raw_input("Enter your Roman Number \n")
print(py_solution().roman_to_int(a))
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