Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Module 1 ASSIGNMENTS

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 165

FP5.

0 Module-1 Assignments

Batch Name: Infosys FP5.0 Summer 2018

Enrollment No: R133216020

SAPID: 500055844
Name: ROHIT RAJ
Sem: FIFTH(5th)
Branch: CSE (BFSI)
ASSIGNMENT 1
Create the following using Scratch:
1.
Take a text input from the user as one of the three shape names – "square", "triangle" or
"pentagon". Based on
the input, draw either a red square, yellow triangle or black pentagon
2.
Create the following pattern using Scratch.
Hint: Create 10 squares each with an inclination of 36 degrees from the preceding square
3.
Create or import two Sprites and use your imagination to make them do different actions
simultaneously. For
example: "A bird is flying and a dog is walking at the same time."
ASSIGNMENT2
Create flowcharts for the following problems:
1.
Calculate the average of three numbers. If average is greater than or equal to 75, print
"Pass", else print "Fail".
2.
Calculate and print the factorial of a number.
3.
Accept the lengths of three sides of a triangle as input from the user. Based on the input,
print if the given
triangle is "Equilateral", "Isosceles" or "Scalene".
4.
Accept the values of principal amount, rate of interest and number of years as an input
from the user. Calculate
and print the simple interest.
Hint - Formula for simple interest:
Simple Interest = (principal amount * rate of interest * number of years)/100

ASSIGNMENT 3
In previous section, you have created the flowcharts for the following problems. Now,
use Raptor tool to create and
execute flowcharts for these problems. Observe the output for different set of inputs.
1)
Calculate the average of three numbers. If average is greater than or equal to 75, print
"Pass", else print "Fail".
2)
Calculate and print the factorial of a number.
3)
Accept the lengths of three sides of a triangle as input from the user. Based on the input,
print if the given
triangle is "Equilateral", "Isosceles" or "Scalene".
4)
Accept the values of principal amount, rate of interest and number of years as an input
from the user. Calculate
and print the simple interest.
Hint - Formula for simple interest:
Simple Interest = (principal amount * rate of interest * number of years)/100
ASSIGNMENT 4

Write Pseudo Code:


1.
to check whether a given number is even or odd.
1. START
2. DISPLAY "Enter the Number - "
3. READ number
4. IF number MOD 2 = 0 THEN
5. DISPLAY "Number is Even"
6. ELSE
7. DISPLAY "Number is Odd"
8. END IF
9. STOP
2.
to print the multiples of 3 between 1 to 20.
1. N=1
2. Loop while N <= 20
3. If N mod 3 = 0
4. Print “N”
5. End-if
6. N++
7. End-loop

3.
to find factorial of a given number.
1.fact=1
2. n=input(“Please, Enter a number\n”)
3. c=1
4. while(c<=n):
5. fact=fact*c
6. c=c+1
7. print “The factorial of “, n , “ is “, fact
8. End-while
4.
to calculate ‘x’ to the power of ‘n’ using a while loop.

Assume both ‘x’ and ‘n’ are positive whole numbers
1. Input count,n
2. Input float value x and y
3. Input x and y
4. Assign y=0 and count = 1
5. While count <= n
6. Y = y*x
7. Count ++
8. End-while
9. Print x to power n
10.stop

ASSIGNMENT 5

Open the Python IDLE and execute the following commands. Observe the output.
1)
10 + 15
2)
print("Hello World")
3)
45 - 34
4)
8*2
5)
print("Rahul's age is", 45)
6)
print("I have", 10, "mangoes and", 12, "bananas")
ASSIGNMENT 6

Open Python IDLE and execute the following commands. Observe the output.
1.
emp_number = 1233
2.
print("Employee Number:", emp_number)
3.
emp_salary = 16745.50
4.
emp_name
= "Jerry Squaris"
5.
print("Employee Salary and Name:", emp_salary, emp_name)
6.
emp_salary = 23450.34
7.
print("Updated Employee Salary:", emp_salary)
ASSIGNMENT 7
Execute the following Python statements in IDLE and observe the output:

customer_id = 101

type(customer_id)

customer_name = "John"

type(customer_name)

bill_amount = 675.45

type(bill_amount )

x = 5.3 + 0.9j

type(x)

print(customer_id, customer_name, bill_amount)

print(x.real)
ASSIGNMENT 8

In a retail application, shopkeeper wants to keep a track of following details of a customer.


Sample values are
provided.

bill_id = 101

customer_id = 1001

customer_name = "Rahul"

if_minor = False

bill_amount = 2000.50
Write a python program to store the details and display them
ASSIGNMENT 9

Execute the following commands and observe the usage of different types of commenting
styles.
i
= 10
# creates an integer variable. This is a single line comment.
print("i =", i)
# prints 10
'''
Below code creates a Boolean variable in Python
(This is a multiple line comment)
'''
s = True
print("s =", s)
#prints True, Here, s is a Boolean variable with value True
"""
Below code assigns string data to variable 's'. Data type of variable can change during
execution,
Hence, Python supports Dynamic Semantics.
(This is multi-line comment used for documentation)
"""
s = 24
print("s =", s)
#prints 24, Here, s is changed to integer data type with value 24
ASSIGNMENT 10

Write a Python program for the following requirements:



Prompt the user to input two numbers num1 and num2

Increment num1 by 4 and num2 by 6

Find and print the sum of new values of num1 and num2
Hint – Use type casting for converting the input into an integer
ASSIGNMENT 11

1) Consider two variables 'a' and 'b' in Python such that a = 4 and b = 5. Swap the values
of 'a' and 'b' without
using a temporary variable. Print the values of 'a' and 'b' before and after swapping.
SOLUTION:
>>> a=4
>>> b=5
>>> print(a,b)
45
>>> a=a+b
>>> b=a-b
>>> a=a-b
>>> print(a,b)
54

2)
Consider the scenario of processing marks of a student in ABC Training Institute. John,
the student of fifth grade
takes exams in three different subjects. Create three variables to store the marks obtained
by John in three
subjects. Find and display the average marks scored by John.
Now change the marks in one of the subjects and observe the output. Did the value of
average change?
SOLUTION:
>>> name="JOHN"
>>> sub1= 70
>>> sub2= 80
>>> sub3= 60
>>> AVG= (sub1+sub2+sub3)/3
>>> print(name,AVG)
JOHN 70.0
>>>
>>> #Now change the marks in one of the subjects and observe the output,Did the value
of average change?
>>>
>>> sub3 = 80
>>> print(name,AVG)
JOHN 70.0
>>> sub3= 100
>>> print(AVG)
70.0
>>> # No, the value of AVG is not changing
>>>
>>>

3) Given the value of radius of a circle, write a Python program to calculate the area and
perimeter of the circle.
Display both the values.

SOLUTION:
>>> pi = 3.14
>>> radius = 4
>>> area= pi*radius*radius
>>> preimeter= 2*pi*radius
>>> print(area,perimeter)

>>> print(area,preimeter)
50.24 25.12
>>>
>>>
4) The finance department of a company wants to compute the monthly pay of its
employees. Monthly pay should
be calculated as mentioned in the formula below. Display all the employee details.
Monthly Pay = Number of hours worked in a week * Pay rate per hour * No. of weeks in a
month

The number of hours worked by the employee in a week should be considered as 40

Pay rate per hour should be considered as Rs.400

Number of weeks in a month should be considered as 4
Write a Python program to implement the above real world problem

>>>
>>>
>>> hours_worked=40
>>> rate_per_hour=400
>>> num_of_weeks=4
>>> monthly_pay= hours_worked*rate_per_hour*num_of_weeks

>>> print(hours_worked, rate_per_hour, num_of_weeks, monthly_pay)


40 400 4 64000
x
>>>
print(hours_worked, rate_per_hour, num_of_weeks, monthly_pay)
40 400 4 64000
ASSIGNMENT 12

Identify the sections of the given program where the coding standards are not followed
and correct them.
itemNo=1005
unitprice = 250
quantity = 2
amount=quantity*unitprice
print("Item No:", itemNo)
print("Bill Amount:", amount)
SOLUTION:
>>> itemNo = 1005 # space on the either side of equal sign
>>> unitprice = 250 # correct standard
>>> quantity = 2 # correct standard(henco no change)
>>> amount = quantity * unitprice # space on the either side of equal sign and operand
>>> print("Item No:", itemNo)
Item No: 1005
>>> print("Bill Amount:", amount)
Bill Amount: 500
>>>
ASSIGNMENT 13


Create a new file in Python IDLE as "triangle.py"

Write a Python program to calculate and print the area of the triangle. Prompt the user to
input
the values for
base and height of the triangle.

Execute the program(use 'Run Module' under 'Run' tab) and observe the output.

Close the file, open it again and execute it once more with different values. Observe the
output.
Hint – Use type casting for converting the input into an integer.
Area of a triangle = ½ * base * height
SOLUTION:
bill_amt = int(input("Enter the Bill Amount:"))
cust_id = int(input("Enter your valid Customer ID:"))
if((cust_id>100) and (cust_id<=1000)):
if(bill_amt>=1000):
discount = 0.05 * bill_amt
net_bill_amt = bill_amt - discount
print("Net Bill Amount after Discount:",net_bill_amt)
elif((bill_amt >= 500) and (bill_amt < 1000)):
discount = 0.02 * bill_amt
net_bill_amt = bill_amt - discount
print("Net Bill Amount afetr Discount:",net_bill_amt)
elif((bill_amt>0) and (bill_amt<500)):
discount = 0.01 * bill_amt
net_bill_amt = bill_amt - discount
print("Net Bill Amount afetr Discount:",net_bill_amt)
else:
print("#ERROR : You are not a valid Customer:")
ASSIGNMENT 14

Implement the following in Python:


a.
Display all even numbers between 50 and 80 (both inclusive) using "for" loop.

SOLUTION :
for value in range(50,81,2):
print(value)
b.
Add natural numbers up to n where n is taken as an input from user. Print the sum.

SOLUTION:
n=int(input("Enter a number: "))
sum1 = 0
while(n > 0):
sum1=sum1+n
n=n-1
print("The sum of first n natural numbers is",sum1)
c.
Prompt the user to enter a number. Print whether the number is prime or not.

SOLUTION:
num = int(input("Enter value for n"))
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")

break
else:
print(num,"is a prime number")

# if input number is less than


# or equal to 1, it is not prime
else:
print(num,"is not a prime number")
d.
Print Fibonacci series till nth term where n is taken as an input from user.
Hint – Fibonacci series is a series of numbers in which each number is the sum of the two
preceding
numbers.
Series start from 1 and goes like : 1, 1, 2, 3, 5, 8, 13 ….
Google it for further information

SOLUTION :
nterms = int(input("Enter any number"))

# uncomment to take input from the user


#nterms = int(input("How many terms? "))

# first two terms


n1 = 0
n2 = 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count < nterms:
print(n1,end=' , ')
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
ASSIGNMENT 15

Create four string variables a, b, c, d


to store the following values and display them:

My city is Mexico

Raghu is my friend's brother

My favorite programming language is "Python"

Python is a widely used high-level, general-purpose, interpreted, dynamic programming
language. It's design
philosophy emphasizes code readability, and it's syntax allows programmers to express
concepts in fewer
lines of code than possible in languages such as "C++" or "Java"
SOLUTION:
a="My city is Mexico"
b="Raghu is my friend's brother"
c='My favourite programming language is"Python"'
d='''Python is a widely used high-level, general-purpose, interpreted, dynamic
programming language. It's design
philosophy emphasizes code readability, and it's syntax allows programmers to express
concepts in fewer
lines of code than possible in languages such as "C++" or "Java".
'''
print(a)
print(b)
print(c)
print(d)
ASSIGNMENT 16
Accept a string as an input from the user. Check if the accepted string is palindrome or not.

If the string is palindrome, print "String is palindrome", otherwise print "String is not
palindrome".

Also print the actual and the reversed strings.
Note – Ignore the case of characters.
Hint – A palindrome string remains the same if the characters of the string are reversed
SOLUTION:
string= input("Enter string:")
if(string==string[::-1]):
print("The string is a palindrome",string)
else:
print("The string isn't a palindrome",string[::-1])
ASSIGNMENT 17

Accept two strings 'string1' and 'string2' as an input from the user. Generate a resultant
string, such that it is a
concatenated string of all upper case alphabets from both the strings in the order they
appear. Print the actual and
the resultant strings.
Note: Each character should be checked if it is a upper case alphabet and then it should
be concatenated to the
resultant string.
Sample Input:
string1:
I Like C
string2:
Mary Likes Python
Output:
ILCMLP

SOLUTION:
string1= "I Like C"
string2= "Mary Likes Python"
count1=""
count2=""
for i in string1:
if(i.isupper()):
count1+=i

for i in string2:
if(i.isupper()):
count2+=i

count=count1+count2
print(count)
ASSIGNMENT 18

Given a string containing both upper and lower case alphabets. Write a Python program
to count the number of
occurrences of each alphabet(case insensitive) and display the same.
Sample Input: ABaBCbGc
Sample Output:
2A
3B
2C
1G

SOLUTION:
from collections import Counter
print(Counter(input("Enter a sentence: ")))
ASSIGNMENT 19

Write a Python program to accept a string 'accepted_string'. Generate a resultant string


'resultant_string' such that
'resultant_string' should contain all characters at the even position of
'accepted_string'(ignoring blank spaces).
Display 'resultant_string' in reverse order.
accepted_string: An apple a day keeps the doctor away
resultant_string: Aapedyepteotrwy
expected_output: ywrtoetpeydepaA
Hint: String starts from index 0, hence the starting character is at even position

SOLUTION:
string = "An apple a day keeps the doctor away"
string1 = string.replace(" ","")
count= ""
for i in string1[0:30:2]:
count+=i
print("resultant_string: ",count)
count1=count[::-1]
print("expected_output: ",count1)
ASSIGNMENT 20

Write a Python program to generate first 'n' Fibonacci numbers where 'n' is accepted as an
input from the user.
Store the generated Fibonacci numbers in a list and display the output.
Sample input: 5
Sample output: [0, 1, 1, 2, 3]

SOLUTION:
n = int(input("Enter the value: "))
fibonacci_numbers = [0, 1]
for i in range(2,n):
fibonacci_numbers.append(fibonacci_numbers[i-1]+fibonacci_numbers[i-2])
print(fibonacci_numbers)
ASSIGNMENT 21

The "Variety Retail Store" sells different varieties of Furniture to the customers. The list of
furniture available with its
respective cost is given below:
The furniture and its corresponding cost should be stored as a list. A customer can order
any furniture in any
quantity (the name and quantity of the furniture will be provided). If the required
furniture is available in the
furniture list(given above) and quantity to be purchased is greater than zero, then bill
amount should be calculated.
In case of invalid values for furniture required by the customer and quantity to be
purchased, display appropriate
error message and consider bill amount to be 0. Initialize required furniture and quantity
with different values and
test the results

SOLUTION;
total_cost=0
a = input("Enter the furniture you want to purchase: ")
n = int(input("Enter the quantity of furniture you want to purchase: "))
found = False
furniture = ["Sofa Set","Dining Table","T.V Stand","Cupboard"]
cost = [20000,8500,4599,13920]
for i in range(len(furniture)):
if (furniture[i] == a):
found = True
for j in range(len(cost)):
if(j==i):
total_cost = n*cost[j]
print("Total cost of furniture is: ",total_cost)
break
if(found == False):
print("ERROR")
print("Bill Amount = 0")
ASSIGNMENT 22

Consider the list of courses opted by a Student "John" and available electives at ABC
Training Institute:
courses = ("Python Programming", "RDBMS", "Web Technology", "Software Engg.")
electives = ("Business Intelligence", "Big Data Analytics")
Write a Python Program to satisfy business requirements mentioned below:
1.
List the number of courses opted by John.
2.
List all the courses opted by John.
3.
John is also interested in elective courses mentioned above. Print the updated tuple
including elective

Solution :

courses = ("Python Programming", "RDBMS", "Web Technology", "Software Engg.")


electives = ("Business Intelligence", "Big Data Analytics")
print("Number of courses opted by JOHN is: ", len(courses))
print("Selected Courses by JOHN are: ",courses)
print("After selecting electives by john :"courses+electives)
ASSIGNMENT 23

Given below is a dictionary 'customer_details' representing customer details from a Retail


Application. Customer Id
is the key and Customer Name is the value.
customer_details = { 1001 : "John", 1004 : "Jill", 1005: "Joe", 1003 : "Jack" }
Write Python code to perform the operations mentioned below:
a)
Print details of customers.
b)
Print number of customers.
c)
Print customer names in ascending order.
d)
Delete the details of customer with customer id = 1005 and print updated dictionary.
e)
Update the name of customer with customer id = 1003 to "Mary" and print updated
dictionary.
f)
Check whether details of customer with customer id = 1002 exists in the dictionary.
SOLUTION:
customer_details = { 1001 : "John", 1004 : "Jill", 1005: "Joe", 1003 : "Jack" }
print("Customer details are: ",customer_details)
print("Number of Customers are:", len(customer_details))
print("Customer names are: ",sorted(customer_details.values()))
del customer_details[1005]
print("Customer details after updation: ",customer_details)
customer_details[1003]="Mary"
print("Customer details after updation: ",customer_details)
cust_id = int(input("Customer id: "))
for i in customer_details:
if(i==cust_id):
print("Exist")
break
else:
print("Not Exist")
break
ASSIGNMENT 24

Consider a scenario from ABC Training Institute. The given table shows the marks scored
by students of grade XI in
Python Programming course.
Write a Python program to meet the requirements mentioned below:
a. Display the name and marks for every student.
b. Display the top two scorers for the course

SOLUTION:

marks = {"John":86.5,"Jack":91.2,"jill":84.5,"Harry":72.1,"Joe":80.5}
print("Name is: ",marks.keys(),'\n',"marks is: ",marks.values())

d=float(sum(marks.values()))/len(marks)
print("Average marks of class is: ",d)

var=sorted(marks.values());
i = var[-1]
j = var[-2]
for key in marks.keys():
if marks[key]==i:
print ("Hightest marks is :", i,"of student", key);

if marks[key]==j:
print ("Second Hightest marks is :", j,"of student", key);
ASSIGNMENT 25

Consider the scenario from "Variety Retail Store" discussed in 'List' section. The list of
furniture available with its
respective cost is given below:
A customer can order any furniture in any quantity. If the required furniture is available in
the furniture list(given
above) and quantity to be purchased is greater than zero, then bill amount should be
calculated. In case of invalid
values for furniture required by the customer and quantity to be purchased, display
appropriate error message and
consider bill amount to be 0. Initialize required furniture and quantity with different
values and test the results.
Calculate and display the bill amount to be paid by the customer based on the furniture
bought and quantity
purchased. Implement the given scenario using:
1)
List of tuples

SOLUTION:
total_cost=0
a = input("Enter the furniture you want to purchase: ")
n = int(input("Enter the quantity of furniture you want to purchase: "))
found = False
furniture = ("Sofa Set","Dining Table","T.V Stand","Cupboard")
cost = (20000,8500,4599,13920)
for i in range(len(furniture)):
if (furniture[i] == a):
found = True
for j in range(len(cost)):
if(j==i):
total_cost = n*cost[j]
print("Total cost of furniture is: ",total_cost)
break
if(found == False):
print("ERROR")
print("Bill Amount = 0")
2)
Dictionary

SOLUTION:
total_cost=0
a = input("Enter the furniture you want to purchase: ")
n = int(input("Enter the quantity of furniture you want to purchase: "))
found = False
furniture = {"Sofa Set":20000,"Dining Table":8500,"T.V
Stand":4599,"Cupboard":13920}
for key, i in furniture.items():
if(key==a):
found=True
total_cost=n*furniture[key]
print(total_cost)
break

found==False
print("ERROR")
print("Bill Amount is: 0")
ASSIGNMENT 26
Consider a scenario from ABC Training Institute. Given below are two Sets representing
the names of students
enrolled for a particular course:
java_course = {"John", "Jack", "Jill", "Joe"}
python_course = {"Jake", "John", "Eric", "Jill"}
Write a Python program to list the number of students enrolled for:
1)
Python course
2)
Java course only
3)
Python course only
4)
Both Java and Python courses
5)
Either Java or Python courses but not both
6)
Either Java or Python courses

SOLUTION:
java_course = {"John", "Jack", "Jill", "Joe"}
python_course = {"Jake", "John", "Eric", "Jill"}
print("Number of students enrolled for PYTHON course are: ",len(python_course))
print("Number of students enrolled for JAVA course only are: ",len((java_course)-
(python_course)))
print("Number of students enrolled for PYTHON course only are:
",len((python_course)-(java_course)))
print("Number of students enrolled for JAVA & PYTHON course are:
",len((java_course)&(python_course)))
print("Number of students enrolled for either JAVA & PYTHON but not both course
are: ",len((java_course)^(python_course)))
print("Number of students enrolled for either JAVA & PYTHON course are:
",len((java_course)|(python_course)))
ASSIGNMENT 27

Using functions, re-write and execute Python program to:


1.
Add natural numbers upto n where n is taken as an input from user.
SOLUTION:

def sum(num):

if num <= 1:
return num
else:
return num + sum(num-1)

n = int(input("Enter any number " ))

if n < 0:
print("Enter a positive number")
else:
print("The sum is",sum(n))
2.
Print Fibonacci series till nth term (Take input from user).
Note: You have implemented these programs using loops earlier

SOLUTION:
def fibonacci(n):
if(n <= 1):
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n = int(input("Enter number of terms:"))
print("Fibonacci sequence:")
for i in range(n):
print(fibonacci(i))
ASSIGNMENT 28

At an airport, a traveler is allowed entry into the flight only if he clears the following
checks:
1.
Baggage Check
2.
Immigration Check
3.
Security Check
The logic for the check methods are given below:
check_baggage (baggage_weight)
•.
returns True if
baggage_weight
is greater than or equal to 0 and less than or equal to 40. Otherwise returns
False.
check_immigration (expiry_year)
•.
returns True if
expiry_year
is greater than or equal to 2001 and less than or equal to 2025. Otherwise returns
False.
check_security(noc_status)
•.
returns True if
noc_status
is 'valid' or 'VALID', for all other values return False.
traveler()
•.
Initialize the traveler Id and traveler name and invoke the functions check_baggage(),
check_immigration() and
check_security() by passing required arguments.
•.
Refer the table below for values of arguments.
•.
If all values of check_baggage(), check_immigration() and check_security() are true,
display traveler_id and traveler_name
display "Allow Traveler to fly!"
Otherwise,
display traveler_id and traveler_name
display "Detain Traveler for Re-checking!“
Invoke the traveler() function. Modify the values of different variables in traveler()
function and observe the output
SOLUTION:
name= ("Jim")
id=("1001")

def check_baggage(x):
if(40>x>=0):
return True
else:
return False

def check_immigration(y):
if(2025>y>=2001):
return True
else:
return False

def noc_status(z):
if(z=="valid" or z=="VALID"):
return True
else:
return False

if(check_baggage(35)==True and check_immigration(2019)==True and


noc_status("VALID")==True):
print("Allow Traveler to fly! ", name,id)

else:
print("Detain Traveler for Re-checking! ",name,id)
ASSIGNMENT 29

Consider the pseudo code for generating Fibonacci series using Recursion:
FIBO (number)
1.
if (number = 0) then
2.
return (0)
3.
else if (number = 1) then
4.
return (1)
5.
else
6.
return FIBO(number - 1) + FIBO(number - 2)
7.
end if
Write a program in Python to implement the same using Recursion and execute it in
Eclipse. Print appropriate error
message if the user enters negative number as input
SOLUTION:
def recur_fibo(n):

if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))

nterms = int(input("Enter any number"))

if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
ASSIGNMENT 30

Write a Python program to implement the following (Use Recursion):


1.
Print first 'n' multiples of 3, where 'n' is taken as an input from the user. The multiples
should be printed from
first to last.
SOLUTION:

def multiple(n):
if(n==0):
print("Enter another value")
else:
for i in range(3,(3*n)+1,3):
print("Multiple of 3 is: ",i)

multiple(int(input("Enter any number: ")))


2.
Reverse a string. Print the original and reversed string.
SOLUTION:
def reverse(x):
x=x[::-1]
return x

s="Palindrome"
print("original string is :",s)
print("reversed string is :",reverse(s))
3.
Check if the given string is palindrome. If yes, print "String is palindrome" otherwise
print "String is not
palindrome"
SOLUTION:

def reverse(x):
x=x[::-1]
return x

s=input("Enter any string to check palindrome: ")


print("original string is :",s)
print("reversed string is :",reverse(s))

if(s==reverse(s)):
print("String is palindrome")
else:
print("String is not palindrome")
ASSIGNMENT 31

Write a Python program to:


1.
read a file.
2.
add backslash (\) before every double quote in the file contents.
3.
write it to another file in the same folder.
4.
print the contents of both the files.
For example:
If the first file is 'TestFile1.txt' with text as:
Jack said, "Hello Pune".
The output of the file 'TestFile2.txt' should be:
Jack said,\"Hello Pune\"
SOLUTION:
file=open("C:\\Users\ROHIT\\Desktop\\Foundation Program 5.0\\TestFile1.txt","r")
r=file.read()
file2=open("C:\\Users\ROHIT\\Desktop\\Foundation Program 5.0\\TestFile2.txt","r+")
file2.write(r.replace('\"','\\\"'))
print("Contents of file1 :",r)
s=file2.read()
print("Contents of file2: ",s)
file.close()
file2.close()
ASSIGNMENT 32

Consider a file 'courses.txt' in D Drive with the following details:


Write a program to read the file and store the courses in Python variables as a:
1)
Dictionary ( Sample - {0: 'Java', 1: 'Python', 2:'Javascript' 3: 'PHP'} )
SOLUTION:
dict={0: 'Java', 1: 'Python', 2:'Javascript', 3: 'PHP'}
file2 =open("C:\\Users\\ROHIT\\Pictures\\Saved Pictures\\courses.txt", "w")
file2.write(str(dict))
print("\n")
file2.close()
2)
List ( Sample -
['Java', 'Python', 'Javascript', 'PHP'] )
SOLUTION:
list=['Java', 'Python', 'Javascript', 'PHP']
file2 =open("C:\\Users\\ROHIT\\Pictures\\Saved Pictures\\courses.txt", "w")
file2.write(str(list))
print("\n")
file2.close()
ASSIGNMENT 33

Consider a file 'student_details.txt' in D Drive with the details of students in ABC


institute – student id and name:
Write a program to read the file and store the student records in Python variable as:
1)
List of lists
SOLUTION:
keys={'Stud_id','Name'}
name1={101,'Rahul'}
name2={102,'Julie'}
name3={103,'Helena'}
name4={104,'Kally'}
dictlist=[]
dictlist.append(dict(zip(keys, name1)))
dictlist.append(dict(zip(keys, name2)))
dictlist.append(dict(zip(keys, name3)))
dictlist.append(dict(zip(keys, name4)))

file2 =open("C:\\Users\\ROHIT\\Pictures\\Saved Pictures\\courses.txt", "w")


file2.write(str(dictlist))
print("\n")
file2.close()

file2 =open("C:\\Users\\ROHIT\\Pictures\\Saved Pictures\\courses.txt", "r")


print(file2.read())
file2.close()
2)
List of dictionaries
SOLUTION:
keys=['Stud_id','Name']
name1=[101,'Rahul']
name2=[102,'Julie']
name3=[103,'Helena']
name4=[104,'Kally']
dictlist=[]
dictlist.append(list(zip(keys, name1)))
dictlist.append(list(zip(keys, name2)))
dictlist.append(list(zip(keys, name3)))
dictlist.append(list(zip(keys, name4)))

file2 =open("C:\\Users\\ROHIT\\Pictures\\Saved Pictures\\courses.txt", "w")


file2.write(str(dictlist))
print("\n")
file2.close()

file2 =open("C:\\Users\\ROHIT\\Pictures\\Saved Pictures\\courses.txt", "r")


print(file2.read())
file2.close()
ASSIGNMENT 34

Consider a file 'rhyme.txt' in D Drive with following text:


Write a Python program to count the words in the file using a dictionary (use space as a
delimiter). Find unique
words and the count of their occurrences(ignoring case). Write the output in another file
"words.txt" at the same
location

SOLUTION:

f=open("F:\\rhyme.txt","r")
f1=open("F:\\words.txt","w")
token=f.read().replace("\n"," ").split(" ")
d={}
i=0
while i<len(token):

if(token[i].lower() in d.keys()):

d[token[i].lower()]+=1
else:
d[token[i].lower()]=1
i+=1

for i in d.keys():
f1.write(i+":"+str(d[i])+"\n")

f.close()
f1.close()
print("Successful!")
ASSIGNMENT 35

Assume the following Python code:


Rewrite the code to handle the exceptions raised. Print appropriate error messages
wherever applicable.
SOLUTION:

mylist=[1,2,3,4,5]
sum=0
for i in mylist:
try:
sum=sum+i
except Exception as e:
print('exception occured: ',e)

print("sum= ",sum)
try:
print("4th integer at mylist= ",mylist[4])
except Exception as e:
print('exception occured: ',e)
ASSIGNMENT 36

You have already created a Python program to implement the following in file handling
section:
1.read a file.
2.add backslash (\) before every double quote in the file contents.
3.write it to another file in the same folder.
4.print the contents of both the files.
Modify your code to implement Exception handling. Print appropriate error messages
wherever applicable
SOLUTION:

file=open("C:\\Users\ROHIT\\Desktop\\Foundation Program 5.0\\TestFile1.txt","r")


r=file.read()
file2=open("C:\\Users\ROHIT\\Desktop\\Foundation Program 5.0\\TestFile2.txt","r+")
try:
file2.write(r.replace('\"','\\\"'))
except Exception as e:
print("Exception occured :",e)
print("Contents of file1 :",r)
s=file2.read()
print("Contents of file2: ",s)
file.close()
file2.close()

ASSIGNMENT 37

You have already executed the Python program given below in Functions section:

Add natural numbers up to n where n is taken as an input from user.
Do appropriate exception handling in the code and observe the output by providing
invalid input values
SOLUTION:
try:
n=int(input("Enter a number: "))
except Exception as e:
print("Exception type :",type(e).__name__)
sum1 = 0
try:
while(n > 0):

try:
sum1=sum1+n
n=n-1
except Exception as e:
print("Exception type :",type(e).__name__)

except Exception as e:
print("Exception type :",type(e).__name__)
print("The sum of first n natural numbers is",sum1)
ASSIGNMENT 38

Refer to the following assignment which you have already executed in Functions section.
Modify your code to
implement Exception Handling and display appropriate error message wherever
applicable.
At an airport, a traveler is allowed entry into the flight only if he clears the following
checks:
1.
Baggage Check
2.
Immigration Check
3.
Security Check
The logic for the check methods are given below:
check_baggage (baggage_weight)

returns True if
baggage_weight
is greater than or equal to 0 and less than or equal to 40. Otherwise returns
False.
check_immigration (expiry_year)

returns True if
expiry_year
is greater than or equal to 2001 and less than or equal to 2025. Otherwise returns
False.
check_security(noc_status)

returns True if
noc_status
is 'valid' or 'VALID', for all other values return False.
traveler()

Initialize the traveler Id and traveler name and invoke the functions check_baggage(),
check_immigration() and
check_security() by passing required arguments.

Refer the table below for values of arguments.

If all values of check_baggage(), check_immigration() and check_security() are true,
display traveler_id and traveler_name
display "Allow Traveler to fly!"
Otherwise,
display traveler_id and traveler_name
display "Detain Traveler for Re-checking!“
Invoke the traveler() function. Modify the values of different variables in traveler()
function and observe the output
SOLUION:

name= ("Jim")
id=("1001")

try:
def check_baggage(x):
if(40>x>=0):
return True
else:
return False
except Exception as e:
print("Exception Type :",type(a).__name__)

try:
def check_immigration(y):
if(2025>y>=2001):
return True
else:
return False
except Exception as e:
print("Exception Type :",type(a).__name__)

try:
def noc_status(z):
if(z=="valid" or z=="VALID"):
return True
else:
return False
except Exception as e:
print("Exception Type :",type(a).__name__)

try:
if(check_baggage(35)==True and check_immigration(2019)==True and
noc_status("VALID")==True):
print("Allow Traveler to fly! ", name,id)

else:
print("Detain Traveler for Re-checking! ",name,id)

except Exception as e:
print("Exception Type :",type(a).__name__)
ASSIGNMENT 39

Create a module "number_checker.py" which has following 2 functions:



is_prime(num) : this function returns true if the input number is prime

is_even(num): this function returns true if the input number is even

Create another Python module "test_module.py".

Invoke the functions "is_prime(num)" and "is_even(num)" in "test_module.py".

Observe the results.
Hint: Import
"number_checker.py" module in "test_module.py" before using it's functions
SOLUTION:
def is_prime(num):
if(num%num==0 or num%1==0):
print("It is prime")
elif(num==1):
print("It is not prime")
else:
print("It is not prime")

def is_even(num):
if(num%2==0):
print("It is even number")
else:
print("It is not an even number")
import ASSIGNMENT_39
fact=ASSIGNMENT_39.is_even(int(input("Enter any number: ")))
fact2=ASSIGNMENT_39.is_prime(int(input("Enter any number: ")))
ASSIGNMENT 40

Write a Python program to randomly print any of the below numbers:


100,200,300,400,500,600,700,800,900,1000
Execute the program 10 times and verify if the number generated in every output is one
out of the numbers
given in the list above.

Write a Python program to print a random odd numbers between 10 and 50
SOLUTION:

import random
list=[100,200,300,400,500,600,700,800,900,1000]
x=random.randrange(0,1001,100)
for y in list:
if (y==x):
print("Is one of the number of the list",x)
y=random.randrange(9,51,2)
print("Odd number is: ",y)
ASSIGNMENT 41

Write a Python program for rolling a dice on clicking enter key. The program should run
infinitely until user enters
'q'.
Hint:

To implement a dice, you can randomly print a number in the range 1-6

SOLUTION:

quit = 0
while quit != "q":
import random

print("This is a dice rolling program")


print("Press Enter to roll a dice")

input()
number = random.randint(1,6)
if number==1:
print("You got 1: ")
print ("Type q to quit")
quit=input()

elif number==2:
print("You got 2:")
print ("Type q to quit")
quit=input()
elif number==3:
print("You got 3:")
print ("Type q to quit")
quit=input()
elif number==4:
print("You got 4:")
print ("Type q to quit")
quit=input()
elif number==5:
print("You got 5:")
print ("Type q to quit")
quit=input()
elif number==6:
print("You got 6:")
print ("Type q to quit")
quit=input()
else:
print("#ERROR")
ASSIGNMENT 42

If area of one wall of a cubical wooden box is 16 units, write a Python program to display
the volume of the box.
Note:
Area of a cube with side 'a' is 'a**2'.
Volume of the cube can be computed as 'a**3'.
Hint: Make use of 'sqrt' and 'pow' functions from math module
SOLUTION:

import math
area=16
a=math.sqrt(16)
print("Side of the cubical wooden box is: ",a)

vol_of_cube=math.pow(a,3)
print("Volume of cube is: ",vol_of_cube)
ASSIGNMENT 43

The ABC Institute offers vocational courses to students in multiple areas e.g. theatre,
classical singing, traditional
dance forms, Bollywood dance, literature and so on. A student can enroll for zero to all
courses.
Write a Python function that takes the number of courses as an input and returns the total
number of different
course combinations, a student can opt for. (Make use of functions available in math
module)
Hint:
if no_of_courses = 2, possible number of combinations are 2! i.e. 2
if no_of_courses = 3, possible number of combinations are
3! i.e. 6 and so on
SOLUTION:

print("This is ABC institute offers vocational courses")


import math
courses=int(input("Enter Number of courses to enroll in: "))
a=math.factorial(courses)
print("Possible number of combinations are: ",a)
ASSIGNMENT 44

Execute the following code and observe the output.


1.
import time
2.
print(time.time())
3.
print(time.localtime())
4.
print(time.localtime(time.time()))
5.
print(time.asctime())
6.
mytime = (2016,7,27,15,45,23,0,0,0)
7.
print(time.localtime(time.mktime(mytime)))

SOLUTION:
import time
a=print(time.time())
b=print(time.localtime())
c=print(time.localtime(time.time()))
d=print(time.asctime())
mytime = (2016,7,27,15,45,23,0,0,0)
print(time.localtime(time.mktime(mytime)))
ASSIGNMENT 45

Consider a Python string:


cust_details = "Hello John, your customer id is j181"
1)
Find, if the name of the customer is preceded by a pattern "Hello " or "hello " (Observe a
space after the word)?
If pattern is found, print the searched result.
2)
Find, if the given string ends with a pattern containing only one alphabet followed by three
numbers? If pattern
is found, print the searched result.
3)
Replace the word starting with "j" followed by three numbers to only the number(remove
the alphabet).
4)
Replace the word "id" with "ID".
The output of the above code is "
Hello John, your customer ID is 181
"
Hint:
In questions 1 and 2 use search() function. The matched object can be returned using
group() function of match
object.
Use sub() function in question 3 and 4
SOLUTION:

import re
cust_details = input("Enter the statement: ")
matched=(re.search('hello|Hello',cust_details))
if(matched!=None):
print("Patten is matched to: ",matched.group())
else:
print("Pattern is not matched")

import re
cust_details = "Hello John, your customer id is j181"
matched=(re.search('.\d{3}',cust_details))
if(matched!=None):
print("Patten is matched to: ",matched.group())
else:
print("Pattern is not matched")
import re
cust_details = "Hello John, your customer id is j181"
replaced=re.sub('\D','',cust_details)
if(replaced!=None):
print("Replaced to: ",replaced)
replaced2=re.sub('id','ID',cust_details)
replaced3=re.sub('j181',replaced,replaced2)
print(replaced3)
ASSIGNMENT 46
Consider a scenario of managing student details in ABC Training Institute. Write a Python
program to implement the
business requirements mentioned below:
a)
Accept student_id and validate whether it contains only digits.
b)
If student _id is valid, accept student_name from the user and validate whether it
contains only alphabets.
c)
If student_name is valid, accept fees_amount paid by the student:
1.
Decimal point is optional in fees_amount(can have maximum one decimal point)
2.
Only two digits are allowed after decimal point
d)
If invalid data is entered in any of the above steps, display appropriate error messages.
Else, create an email_id
for student as
student_name@ABC.com
. Assume there are no duplicate names.
e)
Perform above validations using Regular Expressions and print details of the student:
student_id,
student_name, fees_amount, email_id

SOLUTION:
import re
stud_id = (input("Enter the student id : "))
matched=(re.search('\d+',stud_id))
if(matched!=None):
print("Patten is matched to: ",matched.group())
print("It is valid ID")
stud_name=input("Enter student name: ")
matched_2=(re.search('^[a-zA-Z]+$',stud_name))
if(matched_2!=None):
print("Pattern is matched to: ",matched_2.group())
print("It is a valid Name")
fee_amt=input("Enter fee amount: ")
matched_3=(re.search('^\d+\.\d{0,2}$',fee_amt))
if(matched_3!=None):
print("Patten is matched to: ",matched_3.group())
print("It is valid")
else:
print("Enter fee amount at exact 2 decimal places.")

else:
print("It is not Valid")
else:
print("It is not valid")

email=stud_name+"@ABC.com"
print("Congrats! Yur e.mail id is: "email)

print("Students Details are:\n",stud_id,stud_name,fee_amt,email)


ASSIGNMENT 47

Consider a string:
my_string = “””Strings are amongst the most popular data types in Python. We can create
the strings by enclosing
characters in quotes. Python treats single quotes the same as double quotes.”””
1) Write a Python program to count the number of occurrences of word "String" in the
given string ignoring the
case.
2) Write a function "count_words" to print the count of occurrences of a word:
a) which end with "on". (e.g. Python)
b) which have "on" in between the first and last characters (e.g. amongst)

SOLUTION:
my_string = """Strings are amongst the most popular data types in Python
We can create the strings by enclosing characters in quotes
Python treats single quotes the same as double quotes"""
string=my_string.lower()
counts=string.count('string')

def word_count(str):
count=0
words=str.split()
for i in words:
if(i.endswith('on')):
count=count+1
print("occurence of words ends with 'on': ",count)

print(word_count(string))
ASSIGNMENT 48

Consider the price list of various items in the Retail Store:


item_price = [1050, 2200, 8575, 485, 234, 150, 399]
Customer John wants to know the:
1.
Price of costliest item sold in retail store
2.
Number of items in the Retail store
3.
Prices of items in increasing order
4.
Prices of items in descending order
Implement the above mentioned business requirements using built-in List functions.
Hint –
1) Use max, len, sort functions of math module.
2) For question 3 and 4, display the list in increasing/decreasing order

SOLUTION:

item_price = [1050, 2200, 8575, 485, 234, 150, 399]


max_cost=max(item_price)
print("Price of costliest item sold in retail storem :",max_cost)
no_of_items=len(item_price)
print("Number of items sold in retail storem :",no_of_items)
print("Price in Ascending order :",sorted(item_price))
print("Price in Descending order :",sorted(item_price,reverse=True))

ASSIGNMENT 49
Built-in function in Python which accepts any data structure (list, string, tuple, dictionary
and set) and returns a
sorted list

SOLUTION:
sample_list=[10,20,30,40,50]
student_tuple=('Kayan','Jack','Sparrow','Benedict','Tom')
student_dict={105:'Rahul',106:'Raushan',107:'Sanjeet',108:'Kishu',109:'Anshal'}
print("Sorted list is: ",sorted(sample_list))
print("Sorted tuple is: ",sorted(student_tuple))
print("Sorted dictionary is: ",sorted(student_dict))

You might also like