Professional Documents
Culture Documents
Codetantra Complete Solution PDF
Codetantra Complete Solution PDF
Codetantra Complete Solution PDF
Lesson 1:
1. The sequence of instructions (in the form of source code) written in a computer programming
language is called a computer program.
2. The Python programming language evolved through many versions.
3. Python source code is written and saved in a file with .py extension.
4. print("Python is Easy")
5. print("Python is not Typhoon")
6. print("Abracadabra" * 7);
7. print("wh" "ere" , "the""re" , "is" , "a" , "will," , "th" "ere", "is", "a", "way")
8. Python is an interpreted language.
A Python program can execute C and C++ programs also.
A Python program written on Windows operating system will also execute on Linux operating
system as it is portable.
Lesson 2 Unit 1:
b -- is the base
e -- is the exponent
"""
return b ** e
print(power.__doc__)
Lesson 2 Unit 2:
1. Identifiers are used for identifying entities in a program.
string_1 is valid identifier.
Identifiers can be of any length.
2. Python version 3.5 has 33 keywords.
The keyword nonlocal does not exist in Python 2.
Interpreter raises an error when you try to use keyword as a name of an entity.
3. import keyword
print('and is a keyword :', keyword.iskeyword('and'))
#Fill in the missing code in the below lines
print('exec is a keyword :', keyword.iskeyword('exec') )
print('nonlocal is a keyword :', keyword.iskeyword('nonlocal') )
print('False is a keyword :', keyword.iskeyword('False'))
Lesson 3:
1. length=18
#in the below line, initialize a variable called snake with text "King Cobra"
snake="King Cobra"
#Make no changes to the below line
print(snake, "can grow up to a length of", length, "feet")
2. value1 = value2 = value3 = "Hello"
print(value1)
print(value2)
print(value3)
# Assign values to variables and print again
value1=99
value2="Hello Python"
value3="Hello World"
print(value1)
print(value2)
print(value3)
3. kilometers = int(input("Enter a value: ")) # assign the correct value
convertfactor = 0.621371 # assign the correct value
miles = (convertfactor) * (kilometers)# multiply kilometers and convertfactor
print("Miles:",miles )
4. value1=999
value2=24.789
value3="Python Interpreter"
print(value1)
print(value2)
print(value3)
5. str = input("Enter a value: ")
# Assign str to three objects a, b and c
a=b=c=str
# Print a
print("Value of a:",a)
# Print b
print("Value of b:",b)
# Print c
print("Value of c:",c)
Lesson 4 Unit 1:
1. number1 = 20.50
number2 = 38.25
# Print the multiplication of number1 and number2 using * operator.
print(number1*number2)
string1 = "Amazon"
string2 = "River"
# Print the concatenated value of string1 and string2 using + operator.
print(string1+string2)
2. In Python, Statements are executed by Interpreter.
The association of a value to a variable is called as Binding.
a = b + a * b is a valid statement in Python.
3. message="Hello Programmer! Welcome to the Python world."
print(message)
number=45
number=number+5
print(number)
4. We can perform assignment with '=' operator.
a -= b and a = a-b are gives same result.
Lesson 4 Unit 2:
Lesson 5 Unit 1:
Lesson 5 Unit 2:
1. a = 365
#Print type of a
print(type(a))
a = 345.65
#Print type of a
print(type(a))
a = 45 + 5j
#Print type of a
print(type(a))
Lesson 5 Unit 3:
Lesson 6 Unit 1:
Lesson 6 Unit 2:
Lesson 6 Unit 3:
Lesson 7 Unit 1:
Lesson 7 Unit 2:
Lesson 8 Unit 1:
Lesson 8 Unit 2:
Lesson 9 Unit 2:
Lesson 10 Unit 1:
Lesson 10 Unit 2:
1. In (NOT) ~ Bits that are 0 become 1, and those that are 1 become 0.
2. a=int(input("Enter an integer value: "))
b=int(input("Enter an integer value: "))
print(a,">>",b,"is",a>>b)
print(a,"<<",b,"is",a<<b)
3. x=int(input("Enter an integer value: "))
y=int(input("Enter an integer value: "))
print(x,"& %d:"%y,x&y)
print(x,"| %d:"%y,x|y)
4. One's complement converts 0's into 1's and 1's into 0's.
One's complement of the short int value 2 is 11111101.
5. x=int(input("Enter an integer value: "))
y=int(input("Enter an integer value: "))
print("~ %d:"%x,~x)
print(x,"^ %d:"%y,x^y)
6. x=int(input("Enter an integer value: "))
y=int(input("Enter an integer value: "))
print(x,">>",y,"is",x>>y)
print(x,"<<",y,"is",x<<y)
print(x,"&",y,"is",x&y)
print(x,"|",y,"is",x|y)
print("~",x,"is",~x)
print(x,"^",y,"is",x^y)
7. x=int(input("Enter number1: "))
y=int(input("Enter number2: "))
d=(~y)-(~x)
print("Subtraction of given two numbers using two's complement",d)
Lesson 11 Unit 1:
1. In logical and the result is true if the both operands are true.
2. x=input("Please enter M(male) or F(female): ")
y=int(input("Please enter Age: "))
if(x=='M' and y>=65 or x=='F' and y>=60):
print("Eligible for Concession")
else:
print("Not Eligible for Concession")
3. a=int(input("Enter a: "))
b=int(input("Enter b: "))
c=int(input("Enter c: "))
if(a==b and b!=c and c<b):
print("True")
else:
print("False")
4. a = int(input("Enter a: "))
b = int(input("Enter b: "))
s=a+b
d=a-b
if(a==6 or b==6 or s==6 or d==6):
print("True")
else:
print("False")
5. d=input("Enter day: ")
if(d=='SAT' or d=='SUN'):
print("Weekend")
else:
print("Not Weekend")
Lesson 11 Unit 2:
Lesson 12 Unit 1:
Lesson 12 Unit 2:
Lesson 13:
Lesson 14:
1. Problem solving is a systematic approach to define and solve a problem.
Few techniques are required to solve a particular problem which help in deriving a logic to solve the
problem.
Algorithms,Flowcharts, Pseudo Code and Programs are the techniques used to solve a problem.
2. It is very easy to write the code in any programming language after developing an algorithm for that
problem.
After a finite number of steps an algorithm must reach an end state.
3. The lesser memory a program takes to execute, better is the algorithm.
4. miles = int(input("Enter distance in miles: "))
if (miles > 0):
km=miles*1.609
# convert the given miles into kilometers and print the result
print("Distance in Kilometers =",km)
else:
print("Enter a positive value")
5. t=input("Please enter temperature with unit: ")
#l=len(t)
a=b=n=0
m1=['F','f']
m2=['C','c']
a=int(t[0])
b=int(t[1])
n=(a*10)+b
if(t[2] in m1):
print(n,"F = %.2f"% round((5.0/9.0)*(n-32),2),"C")
if(t[2] in m2):
print(n,"C = %.1f"% round((n*(9.0/5.0))+(32),1),"F")
if(t[2] not in m1 and t[2] not in m2):
print("Unrecognized unit:",t[2])
Lesson 15:
1. Input to a computer, processing the input and showing the processed result as output are examples
of a statement.
Execution of individual statements in a given order is called control flow
In selection statement, the program control is transferred to a part of the program based on a
condition.
A function causes the control to be passed to block of code when referenced using its name.
2. num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
sum = num1 + num2
print("The sum of %d, %d = %d" %(num1, num2, sum))
3. n=int(input("Enter age of voter: "))
if(n>0):
if(n>=18):
print("Eligible to Vote")
else:
print("Not eligible to Vote")
else:
print("Age can never be negative")
4. nvalues=int(input("Enter the number of natural numbers to print( 1 - 50): "))
if(nvalues<=50):# write your condition here
for i in range(1, nvalues + 1):
print(i,end=' ')
# print the numbers
else:
print("Enter a valid value (1 - 50)")
5. def add2Num():
a=int(input("Enter the first number: "))
b=int(input("Enter the second number: "))
print("The sum of %d and %d is %d"%(a,b,a+b))
# write your logic here
add2Num() # caling the function add2Num
Lesson 16 Unit 1:
Lesson 16 Unit 2:
1. Diamond shaped symbol is used in the flowcharts to indicate a decision (or branching).
A flowchart is a pictorial representation of an algorithm.
An algorithm and a flowchart can help us to clearly specify the sequence of steps to solve a given
problem.
2. r=float(input("Enter the radius : "))
if(r>=0.0 and r<=100.0):
print("Area of circle = %.6f"%(3.14*r*r))
else:
print("Enter a positive value upto 100")
3. Flow charts help in understanding the logic of a program.
Flowcharts help in debugging process.
A lot of time is needed for drawing flow charts for large projects.
Lesson 17 Unit 1:
Lesson 17 Unit 2:
1.
2. Understanding exactly the inputs the algorithm needs is the fundamental to understanding the
problem.
Algorithmic design techniques are the cornerstone for designing algorithms for problems.
Pseudocode, Flowcharts are methods of expressing an algorithm.
An Algorithm should be both time and space efficient besides being simple.
Lesson 17 Unit 3:
Lesson 18:
Lesson 19:
1. Control-flow statements are those which can control the execution flow.
Iterative statements can repeat the execution of statements depending on a condition.
2. num = int(input("Enter a number: "))
if(num%3==0):
print("Given number %d is divisible by 3"%num)
print("End of program")
3. a and b are equal.
Lesson 20:
1. distinction_marks = 75
n=int(input("Enter marks obtained: "))
if(n>75):
print("User secured distinction")
else:
print("User did not secure distinction")
2. n=int(input("Enter balance in your account: "))
if(n>=1000):
print("Sufficient balance")
else:
print("Balance is low")
3. Ded_std = 150000
# Request Inputs
Ded_80c = int(input("Enter Amount to be deducted under 80c: "))
Ded_80cc = int(input("Enter Amount to be deducted under 80cc: "))
Ded_hra = int(input("Enter Amount to be deducted under HRA: "))
Ded_med = int(input("Enter Amount to be deducted under Medical: "))
Gross_Income = int(input("Enter Gross Income: "))
Ded_tot = (Ded_std + Ded_80c + Ded_80cc + Ded_hra + Ded_med)
Tax_Income = Gross_Income - Ded_tot
# complete the missing code
if(Tax_Income>0):
if(Gross_Income<=500000):
Income_Tax=(Tax_Income*.1)
if(Gross_Income<=1000000 and Gross_Income>500000):
Income_Tax=25000+((Gross_Income-500000)*.2)
if(Gross_Income>1000000):
Income_Tax=75000+((Gross_Income-1000000)*.3)
print ("Gross Income is" , Gross_Income)
print ("Total Deductions =" , Ded_tot)
print ("Income Tax =",Income_Tax)
else:
print ("Hurray..No Income Tax")
Lesson 21:
Lesson 22:
Lesson 23:
Lesson 24:
Lesson 25:
Lesson 26:
1. numbers = [ 1, 2, 4, 3, 6, 5, 7, 10, 9 ]
#Check for each number that belongs to the list
for i in numbers:
if(i%2!=0):
pass
else:
print(i)
Lesson 27:
Lesson 28 Unit 1:
Lesson 28 Unit 2:
1. a = '0111110'
print("Value after converting to int = 62 and data type of value =",type(int(a)))
print("Value after converting to float = 62.0 and data type of value =",type(float(a)))
print("Value after converting to complex = (62+0j) and data type of value =",type(complex(a)))
2. n=int(input("Please enter an integer: "))
print("Decimal \t Binary \t Octal \t Hexadecimal")
print("{} \t {} \t {} \t {}".format(n,bin(n),oct(n),hex(n)))
Lesson 29 Unit 1:
1. import math
num = float(input("Please enter Float Number: "))
if num - int(num) >=.5:
print (num, "is roundedup to:", math.ceil(num))
else:
print(num, "is truncated to:", math.trunc(num))
Lesson 29 Unit 2:
1. random() function returns random values between 0.0 and 1.0 only.
Lesson 30 Unit 1:
Lesson 30 Unit 2:
Lesson 31 Unit 1:
Lesson 31 Unit 2:
Lesson 32:
1. In Python, we can convert strings of Uppercase letters into lower case and lower case to upper case
using swapcase() method.
print('python is simple'.title()) gives output like Python Is Simple.
print('20.3'.isnumeric()) it returns output as False.
2. str1 = input("Enter a big string: ")
# make string str1 into all upper case letters.
print(str1.upper())
# make string str1 into only every word of first letter into upper case.
print(str1.title())
# split every word of a string str1 with space
print(str1.split())
# fill str1 with '%' special characer 25 width
if(len(str1)<=25):
print("%%{}%%".format(str1))
else:
print(str1)
# make string str1 into small letters.
print(str1.lower())
str2 = '@'
# join string str2 with str1
print(str2.join(str1))
# replace a word 'Strings' with 'Tuples'.
if('Strings' in str1):
print(str1.replace("Strings","Tuples"))
else:
print(str1)
3. print("\nhello") prints the output hello on a new line.
str = '123', the below code is correct to convert string into int. print(int(str)) # 123.
str = "hello world", print(str.isalnum()) returns False.
4. s1=input("Enter first string: ")
s2=input("Enter second string: ")
print("{}{}{}{}".format(s1,s1,s1,s2))
5. print("Python provides built-in libraries\nUsing Python we can implement more and more
applications\n\tPython is Robust")
6. s1=input("Enter first string: ")
s2=input("Enter second string: ")
l1=len(s1)
l2=len(s2)
if(l1>l2):
print("{}{}{}".format(s2,s1,s2))
elif(l2>l1):
print("{}{}{}".format(s1,s2,s1))
else:
print("Both strings are of same length - Enclosing Not done")
7. s=input("Please enter a string: ")
if((s.startswith('Python')) and (s.endswith('programming'))):
print("Valid String")
else:
print("Invalid String")
print("The character with minimum value is:",min(s))
print("The character with maximum value is:",max(s))
8. s=input("Enter a string: ")
if('Python' in s):
print("The given string is:",s)
else:
print("The string after adding 'Python' is: Python {}".format(s) )
9. s=input("Enter a String: ")
# Reverse the string using slicing operator
print(s[::-1])
10. import string
punctuations = string.punctuation
result = " "
str = "List - []\n tuple - ()\n Dictionary - {}\n Comment - #\n Multiply - *\n not - !\n and - &\n or - |\n
format specifier - %\n String - " " $ @ ; : ' / + = "
#write your code here for removing punctuation
for i in str:
if i not in punctuations:
result=result+i
print("Set of punctuations in string.punctuation is:",punctuations ) # print punctuations
print("String after removing all Punctuation's is:",result ) # print result here
11. s1=input("Enter a string: ")
s2=input("Enter a sub-string: ")
l1=s1.split()
print("The count of sub-string:",l1.count(s2))
12. s=input("Enter a string: ")
print("The result is: ",end=' ')
for i in range(0,len(s)):
print(s[i]+s[i],end='')
print()
13. import re
s=input("Enter a string: ")
l=len(s)
f=0
if(s.isspace()):
x=s.split()
if(l%2!=0):
print("Second half string of given odd length string is:",x[1])
else:
print("Second half string of given even length string is:",x[1])
else:
if(s=="Python"):
if(l%2==0):
print("First half string of given even length string is:",s[:(l//2)])
else:
print("First half string of given odd length string is:",s[:(l//2)-1])
elif(s.isupper()):
y=re.findall('[A-Z][^A-Z]*',s)
if(l%2==0):
print("Second half string of given even length string is:",y[1])
else:
print("Second half string of given odd length string is:",y[0])
else:
if(l%2==0):
print("Second half string of given even length string is:",s[(l//2):])
else:
print("Second half string of given odd length string is:",s[(l//2)+1:])
14. s=input("Please enter a string: ")
l=len(s)
if(l==1):
print(s)
print("First string:",s)
print("Second string: ")
print("Original string is: ",s)
elif(l==0):
print("NULL string")
print("First string:",s)
print("Second string:",s)
print("Original string is: ",s)
else:
print("First string: ",end='')
for i in range(l):
if(i%2==0):
print(s[i],end='')
print("\nSecond string: ",end='')
for j in range(l):
if(j%2!=0):
print(s[j],end='')
print("\nOriginal string is: ",s)
15. s=input("Enter a string: ")
print("The incremental order of a string is:",end=" ")
l=len(s)
for i in range(l+1):
print(s[0:i],end='')
print()
16. s=input("Enter a string which consists hyphens: ")
for i in s.split('-'):
print(i,end='')
17. import string
print("Character\t ASCII Code")
for i in range(97,123,1):
print(chr(i),"\t\t",i)
for j in range(65,91,1):
print(chr(j),"\t\t",j)
18. def split(word):
return [char for char in word]
# Get the Input string
s=input("Please enter sentence: ")
# Sort the string
s=input("Enter an integer:")
l1=split(s)
l2=l1
l3=[]
for j in l2:
if j not in l3:
l3.append(j)
for i in range(len(l3)):
print("{} \t {}".format(l3[i],s.count(l3[i])))
Lesson 33:
Lesson 34:
Lesson 35:
Lesson 36:
Lesson 37 Unit 1:
Lesson 37 Unit 2:
1. The result of a concatenation of two tuples when assigned to one of the tuple creates a new tuple.
The result of a repetition of a tuple when assigned to the same tuple will result in a new tuple.
2. s=input("Enter tuple elements separated by ,(Comma): ")
print("List:",s.split(","))
print("Tuple:",tuple(s.split(",")))
n=int(input("Enter index of tuple to get respective element: "))
l=s.split(",")
if(n<len(l)):
print("The index is",n,"and the respective element is",l[n])
else:
print("Please enter valid index of tuple")
3. The output of the following code: ('ac',) * 2 is ('ac', 'ac').
(1, 2, 3) > (1, 0, 3) is True.
4. s=input("Enter tuple elements separated by ,(Comma) for tuple1: ")
n=int(input("Enter an integer to repeat number of times a tuple: "))
t=tuple(s.split(","))
print("Tuple * ",n,"=",t*n)
s=input("Enter tuple elements separated by ,(Comma) for tuple2: ")
u=tuple(s.split(","))
print("Concatenation of tuple1 and tuple2:",t+u)
5. s=input("Enter tuple elements separated by ,(Comma): ")
t=tuple(s.split(","))
print("Elements of tuple:",t)
n=input("Enter an element to check whether it exist in tuple or not: ")
if(n in t):
print("True")
else:
print("False")
6. mytup = ('a', 'b', 'c', 'd')
print("mytup =", mytup)
tup=[1, 2, 3]
mytup=list(mytup)
mytup.append(tup)
mytup=tuple(mytup)
# add elements to the mytup
print("mytup =", mytup)
print("mytup[4][1] = 4")
mytup[4][1]=4
# write your code here
print("mytup =", mytup)
7. mytup = ('a', 'b', 'c', 'd', [1, 2, 3])
print("mytup =", mytup)
print("del mytup[4][2]")
# delele the element 3 from the mytup
del mytup[4][2]
print("mytup =", mytup)
print("del mytup[4] will give TypeError")
8. s=input("Enter tuple elements separated by ,(Comma): ")
t=s.split(",")
n=int(input("Enter an index value to add element into tuple: "))
if(n>=0 and n<len(t) or n<0 and n>=-len(t)+1):
m=input("Enter an element to add in specific index:")
t[n]=m
print("Tuple after insertion:",tuple(t))
else:
print("Please enter valid index of tuple")
9. s=input("Enter tuple elements separated by ,(Comma): ")
l=s.split(",")
print("Tuple of elements:",tuple(l))
n=int(input("Enter an index value to remove respective element from tuple: "))
if(n>=0 and n<len(l) or n<0 and n>-len(l)):
c=l[n]
del l[n]
print("Tuple after removing",c,tuple(l))
else:
print("Please enter valid index of tuple")
10. s1=input("Enter tuple elements separated by ,(Comma) for tuple1: ")
s2=input("Enter tuple elements separated by ,(Comma) for tuple2: ")
if(s1==s2):
print("True")
else:
print("False")
11. s=input("Enter elements separated by ,(comma): ")
n=input("Enter an element to remove: ")
l=s.split(",")
ln=len(l)
if(n in s):
print("Tuple before deletion:",tuple(l))
for i in range(ln):
m=l[i-1]
if(m==n):
del l[i-1]
print("Tuple after deletion:",tuple(l))
else:
print("Please enter existed element of tuple")
12. s=input("Enter tuple elements separated by ,: ")
l=int(input("Enter start index: "))
u=int(input("Enter an end index: "))
li=s.split(",")
if(u>=0 and u<len(li) or u<0 and u>-len(li)):
print("Elements of tuple in given range",tuple(li[l:u]))
else:
print("Please enter valid index of tuple")
Lesson 38:
Lesson 39 Unit 1:
Lesson 39 Unit 2:
Lesson 40:
Lesson 41:
Lesson 42 Unit 1:
Lesson 42 Unit 2:
Lesson 43:
1. s1 = {1, 2}
s1.add(5)
s2 = s1.copy() will result in s1 = {1, 2, 5} and s2 = {1, 2, 5}
You can have frozen sets as members of a set.
2. s1=input("Enter elements separated by ,(comma) for set1: ")
s2=input("Enter elements separated by ,(comma) for set2: ")
s3=input("Enter elements separated by ,(comma) for set3: ")
l1=s1.split(",")
l2=s2.split(",")
l3=s3.split(",")
st1=set(l1)
st2=set(l2)
st3=set(l3)
print("Sorted order of set1:",sorted(st1))
print("Sorted order of set2:",sorted(st2))
print("Sorted order of set3:",sorted(st3))
print("Is set1 subset of set2 ?",st1.issubset(st2))
print("Is set2 subset of set1 ?",st2.issubset(st1))
print("Is set1 subset of set3 ?",st1.issubset(st3))
print("Is set3 subset of set1 ?",st3.issubset(st1))
print("Is set2 subset of set3 ?",st2.issubset(st3))
print("Is set3 subset of set2 ?",st3.issubset(st2))
3. s1=input("Enter elements separated by ,(comma) for set1: ")
s2=input("Enter elements separated by ,(comma) for set2: ")
s3=input("Enter elements separated by ,(comma) for set3: ")
l1=s1.split(",")
l2=s2.split(",")
l3=s3.split(",")
st1=set(l1)
st2=set(l2)
st3=set(l3)
print("Sorted order of set1:",sorted(st1))
print("Sorted order of set2:",sorted(st2))
print("Sorted order of set3:",sorted(st3))
print("Are set1 and set2 disjoint ?",st1.isdisjoint(st2))
print("Are set1 and set3 disjoint ?",st1.isdisjoint(st3))
print("Are set2 and set3 disjoint ?",st2.isdisjoint(st3))
4. s1=input("Enter elements separated by ,(comma) for engineers: ")
s2=input("Enter elements separated by ,(comma) for programmers: ")
s3=input("Enter elements separated by ,(comma) for managers: ")
le=s1.split(",")
lp=s2.split(",")
lm=s3.split(",")
se=set(le)
sp=set(lp)
sm=set(lm)
print("Engineers:",sorted(se))
print("Programmers:",sorted(sp))
print("Managers:",sorted(sm))
lem=le+lp+lm
sem=set(lem)
print("Employees:",sorted(sem))
ne=input("Enter element into engineers: ")
le.append(ne)
print("Engineers:",sorted(le))
print("employees.issuperset of engineers: False")
print("Let us update emplyees from engineers")
se=set(le)
lem=le+lp+lm
sem=set(lem)
print("employees.issuperset of engineers:",sem.issuperset(se))
na=input("Enter element to remove from engineers, programmers, managers, employees: ")
print("After deleting",na)
if na in le:
le.remove(na)
elif na in lp:
lp.remove(na)
elif na in lm:
lm.remove(na)
lem=le+lp+lm
sem=set(lem)
print("Engineers:",sorted(le))
print("Programmers:",sorted(lp))
print("Managers:",sorted(lm))
print("Employees:",sorted(sem))
Lesson 44:
Lesson 45:
Lesson 46:
1. l1=[]
l2=[]
for i in range(65,91,1):
l1.append(i)
l2.append(chr(i))
d1=dict(zip(l1,l2))
d1=sorted(d1.items())
d2=dict(zip(l2,l1))
d2=sorted(d2.items())
print(d1)
print(d2)
Lesson 47:
1. A function is defined once but called many number of times.
Function is a block of statements to do one or more tasks.
2. Th keyword def always occurs as the start of function header.
The function_name follows the same rules as any identifiers of Python.
3. def helloworld():
# write your code here
print("Hello World")
print("Good morning")
print("Have a nice day")
print("The function ends")
helloworld()
4. def add(x, y):
# add x, y and print the result
return x+y
def sub(x, y):
# subtract x, y and print the result
return abs(x-y)
def mul(x, y):
# multiply x, y and print the result
return x*y
# take inputs x and y from the user
a=int(input("Enter x value: "))
b=int(input("Enter y value: "))
# call the functions add,sub, mul
print(add(a,b))
print(sub(a,b))
print(mul(a,b))
5. def tn(x,y):
ad=x+y
sb=abs(x-y)
ml=x*y
return ad,sb,ml
a=int(input("Enter a value: "))
b=int(input("Enter b value: "))
(add,sub,mul)=tn(a,b)
print(add)
print(sub)
print(mul)
6. A comment that occurs in the first line of the function body after the colon(:) is known as Docstring
This docstring is available in the program as a __doc__ attribute.
A docstring is written between triple quotes """
7. def of(x,y):
su=x+y
av=(x+y)/2
sb=abs(x-y)
ml=x*y
return su,av,sb,ml
a=int(input("Enter a value: "))
b=int(input("Enter b value: "))
(sm,avr,sub,mul)=of(a,b)
print("Sum ,Average = ({}, {})".format(sm,avr))
print("Subtraction =",sub)
print("Multiplication =",mul)
8. def add(x,y):
return x+y
def sub(x,y):
return abs(x-y)
a=int(input("Enter a value: "))
b=int(input("Enter b value: "))
print("Addition",add(a,b))
print("Subtraction",sub(a,b))
Lesson 48 Unit 1:
1. An argument is an expression which is passed to a function by its caller, in order for the function to
perform its task.
Arguments are local to the particular function.
Parameters are available only with in the specified function and parameters belong to the called
function.
2. def add(a, b):
return a+b
# Write your logic here
a=int(input("Enter an integer value a : "))
b=int(input("Enter an integer value b: "))
print(add(a,b))
3. def sayhello(username):
for i in username:
print("Hello",i)
users = ['Ram', 'Mahesh', 'Vasudha', 'Uma', 'Sekhar', 'John']
sayhello(users)
4. def pt(n):
trow=[1]
y=[0]
for x in range(n):
print(trow)
trow=[left+right for left,right in zip(trow+y, y+trow)]
return n>=1
a=int(input("Enter a number: "))
pt(a)
Lesson 48 Unit 2:
1. When the values are passed, as arguments to the function in any order and these values get
assigned, these arguments are called keyword arguments.
Calling the function add(a = 10,b = 20) or by add(10, 20) produce the same result.
2. def simplecalc(a,b):
x=a
y=b
print("Addition result:",x+y)
print("Subtraction result:",x-y)
print("Multiplication result:",x*y)
#define your function here and perform arithmetic operations addition, subtraction, multiplicateion
and print the result.
simplecalc(a = 3, b = 5)
simplecalc(b = 4, a = 5)
#This function can also be called with positional arguments
simplecalc(8, 4)
3. def sst():
n=input("please enter your name: ")
mn=input("please enter if it is morning/night: ")
for i in range(2):
print("Good",mn,n)
sst()
4. def ng():
n=input("Please enter name: ")
a=int(input("Please enter age: "))
for i in range(2):
print(n,a)
ng()
Lesson 49 Unit 1:
Lesson 49 Unit 2:
1. If the correct number of arguments that will be passed to a function at the time of execution is not
known , we can use function with arbitrary arguments.
Arbitrary arguments. is specified by using an asterisk (*) in the function definition before the
parameter name.
2. def mySum(*args):
s=0
for i in args:
s=s+i
return s
#Write your code here
print(mySum(1, 2, 3, 4, 5, 6, 7)) #7 arguments
print(mySum(1, 2)) #2 arguments
print(mySum(1, 2, 3)) #3 arguments
3. def largestNumber( * numbers):
a=numbers[0]
for i in numbers:
if(a<i):
a=i
print("Largest in the given values is",a)
# write your code here
largestNumber(1, 2, 3, 4) #4 arguments
largestNumber(8, 9, 3, 4, 2, 5) #6 arguments
Lesson 50:
Lesson 51:
Lesson 52 Unit 1:
1. def test1():
a=50
b=80
print(a,b)
def test2():
a=22
b=44
print(a,b)
test1()
test2()
2. globvar = "Hello"
def test1():
global globvar
globvar ="Good Morning"
def test2():
# Here this is a local variable
globvar ="Bad Morning"
print(globvar) # The first value "Hello" is printed
# call the function test1
test1()
# call the function test2
test2()
print(globvar) # The updated value of test1 is printed
3. a=int(input("Enter a value: "))
def changeglobal():
global a
a = 200
def changelocal():
a = 500
print("local a value is", a)
print("global a before function call", a)
# call the function changeglobal
changeglobal()
# call the function changelocal
changelocal()
print("global a after function call",a ) # print value of a here
Lesson 52 Unit 2:
1. def square(x):
return x*x
# find square of a given number and return the result
def double(x):
return x*2
# double the given number and return the result
# take the user input
num=int(input("Please enter a value: "))
print("Double and squaring the value",square(double(num)) )
2. def compose (*functions):
def inner(arg):
for f in reversed(functions):
arg=f(arg)
return arg
return inner
def square (x):
return x ** 2
def increment (x):
return x+1
def half(x):
return x/2
composed=compose(square,increment,half)
print(composed(5))
composed=compose(square, increment)
print(composed(5))
Lesson 53:
1. A function call when made within the definition of the same function is known as
a recursion function.
Every time a recursive call is made, the arguments passed to the function should be closer to the
base criteria.
2. In circular recursion more than one function is involved.
3. def recurfact(n):
if(n==0):
return 1
else:
return n*recurfact(n-1)
a=int(input("Enter a number: "))
if(a<0):
print("The factorial does not exist for a negative number")
else:
print("The factorial of the given number is ",recurfact(a))
4. def r_sum(nested_num_list):
s=0
for i in range(len(nested_num_list)):
l=nested_num_list[i]
if(type(l)==type([])):
for i in range(len(l)):
ll=l[i]
if(type(ll)==type([])):
for i in range(len(ll)):
lll=ll[i]
s=s+lll
else:
s=s+ll
else:
s=s+l
return s
L1 = [1, 10, 9, [3, 5, 7], [5, [6, 7], 97]]
print(r_sum(L1))
5. def add(x, y):
if y==0:
return x
else:
return (1+add(x,y-1))
# write your code here
a=int(input("Please enter an integer: "))
b=int(input("Please enter another integer: "))
print(add(a, b))
Lesson 54:
Lesson 55:
1. In early times, all the programming languages had huge lines of code that increased in leaps and
bounds.
A module contains a set of classes, functions, variables hat got together to get a specific set of tasks
done.
In Python, a module is a python file (.py).
2. courses = ['Java','Python','C','C plus']
def arithoperations(num1,num2):
print("Addition of num1 and num2 =",num1+num2)
print("Subtraction of num1 and num2 =",num1-num2)
print("Multiplication of num1 and num2 =",num1*num2)
print("Division of num1 and num2 =",num1/num2)
# Compute addition of two arguments
# Compute substraction of two arguments
#Compute multiplication
#Compute division
def compoperations(num1,num2):
print("Is num1 greater than num2 =",num1>num2)
print("Is num1 less than num2 =",num1<num2)
print("Is num1 equal to num2 =",num1==num2)
print("Is num1 not equal to num2 =",num1!=num2)
# Compare num1 is greater than num2
# Compare num1 is less than num2 or not
# Compare if num1 is equal to num2 or not
# Compare if num1 is not equal to num2 or not
arithoperations(10, 20)
compoperations(10, 20)
print("Length of courses:",len(courses))
#print the length of the courses
3. def checkNegativeNumber(num):
if(num>=0):
print("The number entered is positive")
else:
print("The number entered is negative")
n=int(input("Please enter an integer value: "))
checkNegativeNumber(n)
Lesson 56:
1. import CheckNegative
n=int(input("Please enter some value: "))
if CheckNegative.CheckNegativeNumber(n)==positive:
print("The number entered is positive")
else:
print("The number entered is negative")
2. import Module_Imp2
n1=int(input("Please enter value for a: "))
n2=int(input("Please enter value for b: "))
Module_Imp2.arithoperations(n1,n2)
3. import Module_Imp2 as mi
n1=int(input("Please enter value for a: "))
n2=int(input("Please enter value for b: "))
mi.arithoperations(n1,n2)
4. import Module_Imp1 as mi
import Module_Imp2 as mii
n1=int(input("Please enter value for num1: "))
n2=int(input("Please enter value for num2: "))
mi.checkNegativeNumber(n1)
mi.checkNegativeNumber(n2)
mii.arithoperations(n1,n2)
5. If the import and imported files are in the same directory, then the interpreter does not need the sys
path to be appended.
The interpreter first searches the built-in module.
Lesson 57:
Lesson 58:
Lesson 59:
Lesson 60 Unit 1:
1. PIP - is a package management system that helps in installing python packages and managing
them.
PIP can be installed through the system package manager or by invoking cURL, a client-side data
transfer tool.
Pip stands for "Preferred Installer Program".
Lesson 60 Unit 2:
Lesson 61:
Lesson 62:
1. The mode arguments tells how the file is to be opened, e.g. for reading only, for writing only etc.
2. Student data containing name(string), age(integer), percentage (float) should be stored as a binary
file
Binary data is read and written in bytes objects and cannot be printed directly
3. Write only with error if file is existing
4. import shutil
fr = open('TextData.txt', 'r') # Open the file for read
fw = open('NewFile.txt', 'w') # Open the file for write (new file)
# Read the file and copy it to the new file
shutil.copyfile('TextData.txt','NewFile.txt')
fr.close() # Close the
input file
fw.close() # Close the
new file
fr1 = open('NewFile.txt', 'r+') # Open the new file as read /
write
# read and print the first 12 characters
print(fr1.read(12))
# Print the read cursor position( position is 0 based)
print(fr1.tell())
print(fr1.write("this is the new text")) # Write some text (length 20). This is always
written at the end
# Position the cursor at 12
fr1.seek(12)
print(fr1.tell())
# Read and print the next character (at cursor position 12)
print(fr1.readline(12),end="")
# Position the cursor at 15
fr1.seek(15)
print(fr1.tell())
print(fr1.readline(10))
# Read and print 10 characters from this position
print(fr1.readline(),end="")
# read() always reads the entire file irrespective of cursor position and changes the cursor position
to the end
print(fr1.read())
fr1.close() # Close the
file
5. import pickle # inports the pickle library
Students = [['John', '501', 20, 92.5],['Kohli', '502', 21, 95.5],
['Ganga','503', 20, 90.5],['Gayathri','504', 20, 82.5],
['Krishna','505', 20, 96.5]] # Define the students in a list
fst = open("students.dat",'wb') # Open the output file Notice the
the b after w to indicate this is a binary file
for student in Students:
pickle.dump(Students,fst ) #Fill the missing code # Write the details of each
student
fst.close() # Close the output
filr
fst = open("students.dat",'rb') # Open the file as input binary
data = pickle.load(fst) #Fill the missing code # Read the file record
c=0
try: # The Endof file is
indicated as EOFError exception, we need to catch this exception
while(c!=1):
for item in data:
print(item)
c=1
except:
print("Bye")
print("Bye")
6. fr=open('InputData1.txt','r')
lines=fr.readlines()
for i in range(len(lines)):
nl=lines[i]
nls=nl.replace("\n","")
print(nls[::-1])
7. fin = open('InputData2.txt' , 'r')
charCount = wordCount = lineCount = 0 #Initialize Counters
for line in fin: #Read each Line
lineCount+=1
# write your logic here
s=line
l=s.split(" ")
wordCount+=len(l)
#Increment Line count
for i in s:
charCount+=len(i)
#split() gives the words in a list
#Increment Character Count
print("Line count = ", lineCount) #Print the Counts
print("Word count = ", wordCount)
print("Char count = ", charCount)
8. import shutil
fin = open('InputData3.txt', 'r') #Open the text Files for input and output
fout = open('OutputData3.txt', 'w') #if the file is big we will read and write line by
line.
shutil.copyfile('InputData3.txt','OutputData3.txt') #for each line
#Write the line
fin.close() #Close the input file
fout.close() #Close the output file
#Close the input file
#Close the output file
fin = open('OutputData3.txt' , 'r') #Open the new file as input
print(fin.read()) #for each line
#Print line
fin.close() #Close the File
Lesson 63:
Lesson 64:
1. class Student:
def __init__(self,name,age,email):
# define init method with self , name, age, email attributes
self.name = name
self.age = age
self.email = email
Stud_1 = Student('SriRam', 25, 'ram@sch.com') # type: Student
Stud_2 = Student('Lakshman', 28, 'laks@sch.com')
print('Stud_1 details =', Stud_1.name, Stud_1.age, Stud_1.email)
print('Stud_2 details =', Stud_2.name, Stud_2.age, Stud_2.email)
2. class Car:
def setDetails(self, model, regno):
# write your code here
self.model=model
self.regno=regno
def getModel(self):
self.model=input("Enter model of the car2: ")
# write your code here
def getRegno(self):
self.regno=input("Enter regno of the car2: ")
# write your code here
Hyundai = Car()
Maruthi = Car()
#Take details of the car as input from user. Write your code here
Hyundai.model=input("Enter model of the car1: ")
Hyundai.getRegno()
Maruthi.getModel()
Maruthi.getRegno()
print("Hyundai Car Details:",Hyundai.model,Hyundai.regno )
print("Maruthi Car Details:",Maruthi.model,Maruthi.regno )
3. class car:
def getname(self):
print("Honda Car Name:",self.name)
def setname(self,name):
self.name=name
honda=car()
name=input("Please enter a car name: ")
honda.setname(name)
honda.getname()
4. self should be the first argument in the parameter list.
self is always a reference to the current instance.
Lesson 65:
1. A constructor can be viewed as a specific method used by the class to perform tasks such as
initialising variables, or any start up task.
In Java language, the constructor has the same name as the class with no return type defined.
A constructor in Python in any class is defined as __init__(self) method.
2. class student:
def __init__(self,name,age,email):
self.name=name
self.age=age
self.email=email
s1_name=input("Please enter a name of the student1: ")
s1_age=int(input("Please enter age of the student1: "))
stud_1=student(s1_name,s1_age,'arya@gmail.com')
s2_name=input("Please enter a name of the student2: ")
s2_age=int(input("Please enter age of the student2: "))
stud_2=student(s2_name,s2_age,'geetha@gmail.com')
print("Stud_1.name =",stud_1.name)
print("Stud_2.name =",stud_2.name)
3. class Student:
def __init__(self, name, age, email):
# Write your code here
self.name=name
self.age=age
self.email=email
def studentDetails(self):
# Write your code here
print("Name:",self.name,", age:",self.age,", email:",self.email)
name=input("Enter name of the student: ")
age=int(input("Enter age of the student: "))
email=input("Enter email of the student: ")
sd=Student(name,age,email)
sd.studentDetails()
4. class Employee:
def __init__(self, name, salary):
# Initialize name and salary of the employee
self.name=name
self.salary=salary
def displayEmployee(self):
# Write a function to display employee details
print("Name:",self.name,", Salary:",self.salary)
name=input("Enter name of the employee: ")
salary=int(input("Enter salary of the employee: "))
emp=Employee(name,salary)
emp.displayEmployee()
Lesson 66:
1. Methods are a set of statements that are called to perform a specific task.
Methods are used in OOPS.
2. class person:
def setname(self,name):
self.name=name
def getname(self):
return self.name
p1=person()
p2=person()
name=input("Enter name of the person1: ")
p1.setname(name)
name=input("Enter name of the person2: ")
p2.setname(name)
print("Person P1 name:",p1.getname())
print("Person P2 name:",p2.getname())
3. class person:
def setname(self,name):
self.name=name
def getname(self):
return self.name
p1=person()
p2=person()
name=input("Please enter a name: ")
p1.setname(name)
name=input("Please enter a name: ")
p2.setname(name)
print(p1.getname())
print(p2.getname())
4. class Greeting:
def sayHello(self, name = None, wish = None):
if name is not None and wish is not None:
print ('Hello' + name + wish)
elif name is not None and wish is None:
print ('Hello' + name)
else:
print ('Hello')
greet = Greeting()
# Call the method with zero, one and two parameters
greet.sayHello()
greet.sayHello('Ram')
greet.sayHello('Ram,', 'Good Morning!!!')
Lesson 67:
1. Exception is an event which occurs to disrupt the flow of the given program.
Exception handling is a rich feature provided by Python language.
If the code executes without any error, the except block is skipped and control goes to the
statement after the except block.
2. All exceptions should be instances of the derived class of the BaseException class.
In the except block, if the exception is handled, it means it can also handle all the exception types
that are derived from this Exception class.
All built-in exceptions are derived from the Exception class.
3. # write your code here
n1=int(input("Enter num1: "))
n2=int(input("Enter num2: "))
try:
d=n1/n2
print("Successful Division, value of num1/num2",d)
except:
print("Exception occurred")
4. The root exception class is the BaseException.
SystemExit, KeyboardInterrupt, GeneratorExit and Exception extend from the BaseException.
The Rest of the built-in classes are derived from The Exception class.
Lesson 68:
1. A error is generally a bug in the program usually caused by the developer who develops the code.
There are generally three types of errors.
Syntax errors are mistakes that happen if the programs that are written do not use the correct
format of the language.
2. Logical Errors are the most difficult errors.
Programs that have Logical Errors get compiled and executed but give wrong results.
Logical Errors can be caused by the usage of the wrong variable name.
3. A program may exit unexpectedly during execution if it encounters a runtime error.
A runtime error is a problem that was not detected when the program was parsed by the interpreter,
but is only found out at a specific line execution.
When a program exits when a run time error occurs, we say the program crashed.
Division by zero is not a logical error.
Lesson 69:
1. A try block can have more than one except block, each block handling a type of Exception.
Based on the Exception/error that has been generated, the except block that is written to handle
that exception is invoked.
Finally block is executed in the case of exceptions or no exceptions.
2. try:
# take user inputs a and b and perform arithmetic operations
a=int(input("Enter a value: "))
b=int(input("Enter a value: "))
a=a+b
a=a/b
a=a*b
a=a-b
if a == 0:
f = fun1(a)
# print here
print("All operations in try successful")
except ZeroDivisionError:
# print here
print("A ZeroDivisionError occurred")
except NameError:
# print here
print("A NameError occurred")
except Exception:
# print here
print("An Exception occurred")
def fun1(n):
print(n)
3. try:
a=int(input("Enter a value: "))
b=int(input("Enter a value: "))
a=a+b
a=a/b
a=a*b
a=a-b
if a==0:
f=fun1(a)
print("All operations in try successful")
except ZeroDivisionError:
print("A ZeroDivisionError occurred")
except NameError:
print("A NameError occurred")
except Exception:
print("An Exception occurred")
def fun1(n):
print(n)
4. It is good way of programming to write exception handling for a few lines of code.
An advantage of exception handling is it separates normal code and exception handling code.
Exceptions are passed from functions in the stack until they reach a function that knows how to
handle them
Lesson 70 Unit 1:
1. def checkage(age):
if age < 0:
raise ValueError("Age should be greater than or equal to zero")
print("Age entered is valid", age)
# write your code here
try:
a=int(input("Enter age: "))
checkage(a)
except ValueError:
print("('Age should be greater than or equal to zero',)")
print("I am executed in any condition")
2. try:
age=int(input("Enter age: "))
if(age<0):
raise ValueError
except ValueError:
print("Value Error, Age should be greater than or equal to zero")
print("I am always executed")
Lesson 70 Unit 2:
Lesson 71 Unit 1:
Lesson 71 Unit 2:
1. Operating System module is one of the modules that is mostly used in Python.
We use the OS module to talk to the underlying operating system.
All functions in the OS module raise an OSError in case of an exception.
2. import os
try:
print("File name of the process:", os.ctermid())
print("Groups List:",list(os.getgroups()) )# print the user group details using
os.getgroups
except TypeError:
print("Exception on gettig one of the details")
3. import os
# print the current working directory
print(os.getcwd())
# lists all the files in the current directory
print(os.listdir())
os.makedirs('dir1/sub-dir1')
# lists all the files in the current directory
print(os.listdir())
# deletes created directory and the required sub directory
os.removedirs('dir1/sub-dir1')
print(os.listdir())
4. import os
print('Statistics of file some_file.txt',os.stat('Some_File.txt'))
tup=os.walk(os.getcwd())
for dirpath,dirname,filename in tup:
print("path:",dirpath)
print("dir name:",dirname)
print("file name:",filename)
5. import os
print(os.getcwd())
os.mkdir("new_dir/new_sub_dir/")
print(os.getcwd())
os.rmdir("new_dir/new_sub_dir/")
print(os.stat("new_file.txt"))
Lesson 71 Unit 3:
1. A regular expression, regex or regexp is a sequence of characters that define a search pattern.
Each character in a regular expression is a meta character, having a special meaning, or a regular
character that has a actual meaning.
Regular expressions were popular from 1968 for pattern matching in a text editor and lexical
analysis in a compiler.
2. A regular expression, is called a pattern.
An atom is a single point within the regex pattern which it tries to match to the target string.
The simplest atom is a literal
4. Pattern objects have several methods and attributes like match(), search() etc.
start() method on match object returns the starting position of the match.
5. import re
mystring = "Hello!! Good Morning, Welcome to python tutorial class 24.For any queries please
email to contactus@codetantra.com”
print("['Hello']")
print("['24']")
print("['c', 'a', 'c', 'a', 'a', 'a', 'a', 'c', 'ac', 'c', 'a', 'a', 'c']")
6. import re
mystring = "Hello!! Good Morning, Welcome to python tutorial class 24."
c=-1
for m in range(len(mystring)):
if mystring[m]=='e':
print("e")
if mystring[m]=='o':
if mystring[m+1]=='o':
print("oo")
c=m+1
elif m!=c:
print("o")
7. s=input("Please enter a string with some email address: ")
l=s.split(" ")
n=len(l)
c='@'
if l[n-1]!='@' and c in l[n-1]:
print("Email address found is: ['{}']".format(l[n-1]))
else:
print("No email address found")
Lesson 71 Unit 4:
1. The datetime module has many classes for manipulating dates and times.
The implementation provided by datetime classes are very efficient for output formatting and
manipulation of date and time.
An aware object has information of algorithmic time adjustments, such as time zone and daylight
saving time information.
The tzinfo objects store information about the offset from UTC time.
2. import datetime
from datetime import date
from datetime import timedelta
# Take the input date from the user in the form of YYYY-MM-DD and store it in a variable d
d=input("Enter a date in YYYY-MM-DD format:")
# Take the input from the user i.e number of days the user want add the given date
days=int(input("Enter how many days you want to add the current date:"))
year, month, day = d.split('-')
d = datetime.date(int(year), int(month), int(day)) # converting string data into int
d = d+timedelta(days)
print(d)
# print weekday using date.weekday() by passing d as argument
print("It is weekday (0-6):",date.weekday(d))
print("It is a weekday(1-7):",date.isoweekday(d))
3. from datetime import date
s=input("Enter a date in YYYY-MM-DD format: ")
dt=s.split("-")
if '0' in dt[1]:
print("The given date is :",s)
else:
print("The given date is : {}-0{}-{}".format(dt[0],dt[1],dt[2]))
c=int(dt[1])
d=0
while(c!=0):
t=c%10
d=d+t
c=c//10
print("Month is {} , day is {} , year is {}".format(d,dt[2],dt[0]))
yba=int(input("please enter a year before/after the current year:"))
yc=int(dt[0])
if yba<=yc:
print("It is {} years before the current year".format(yc-yba))
else:
print("It is {} years after the current year".format(yba-yc))
4. import datetime
from datetime import date
from datetime import timedelta
# take the date input from the user
d=input("Enter a date in YYYY-MM-DD format")
year, month, day = d.split('-')
d = datetime.date(int(year), int(month), int(day))
d=d+datetime.timedelta(days=3)
# add 3 days to the given date using timedelta function
print("After adding 3 days the given date becomes:",d)
5. from datetime import timedelta,date
#define two years del1 and del2 specifying the number of days in the year.
#Let us do some operations
d1=int(input("Enter number of days in year one: "))
d2=int(input("Enter number of days in second year: "))
print("d3 = d1 - d2: {} day, 0:00:00".format(d1-d2))
# find del1 - del2 and print the result
print("d3 = d1 + d2: {} days, 0:00:00".format(d1+d2))
# find del1 + del2 and print the result
print("d3 = d1 / d2:",d1/d2)
# find del1 / del2 and print the result
if d1%d2 != 1:
print("d3 = d1 % d2: {} days, 0:00:00".format(d1%d2))
else:
print("d3 = d1 % d2: {} day, 0:00:00".format(d1%d2))
# find del1 % del2 and print the result
print("d3 = d1 * 2: {} days, 0:00:00".format(d1*2))
6. import datetime
from datetime import date
from datetime import timedelta
d=input("Enter a date in YYYY-MM-DD format: ")
n=int(input("Please enter number of weeks: "))
year,month,day=d.split("-")
d=datetime.date(int(year),int(month),int(day))
d=d+datetime.timedelta(weeks=n)
print("The date after",n,"weeks will be:",d)
7. from datetime import time,datetime
# create a time object with hour = 6, minute = 30, second = 56, microsecond = 30
t1=time(hour=6,minute=30,second=56,microsecond=30)
# print the created time object t1
print("Time object created t1:",t1)
8. import datetime
d=input("Enter a date in YYYY-MM-DD format:")
year,month,day=d.split("-")
d=datetime.date(int(year),int(month),int(day))
print("Date and Time object",d)
print("day is {} day of week".format(d.isoweekday()))
9. from datetime import datetime
import datetime
from datetime import date
import calendar
import locale
d=input("Enter a date in YYYY-MM-DD format")
dt=d
li=dt.split("-")
year,month,day=d.split("-")
di=datetime.date(int(year),int(month),int(day))
cday=di.strftime("%a")
cmth=di.strftime("%b")
cdate=di.strftime("%x")
#Taking input date from the user and convert into int formate using datetime object
print("Date and Time in locale format: {} {} {} 00:00:00 {}".format(cday,cmth,int(li[2]),int(li[0])))
print("Weekday in locale formate:",cday)
print("Date in locale format:",cdate)
Lesson 71 Unit 5: