Module 1 ASSIGNMENTS
Module 1 ASSIGNMENTS
Module 1 ASSIGNMENTS
0 Module-1 Assignments
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
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
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
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
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
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")
SOLUTION :
nterms = int(input("Enter any number"))
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
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 :
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
def sum(num):
if num <= 1:
return num
else:
return num + sum(num-1)
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
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))
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
ASSIGNMENT 30
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)
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
if(s==reverse(s)):
print("String is palindrome")
else:
print("String is not palindrome")
ASSIGNMENT 31
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
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:
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
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
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
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:
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
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)
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
SOLUTION:
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))