Codetantra Complete Solution PDF

You might also like

You are on page 1of 97

CODETANTRA COMPLETE SOLUTION LESSON 1-72

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:

1. print("I am a Python Guru")


2. print("1")
# print("2")
print("3")
# print("4")
print("5")
#print("6")
print("7")
#print("8")
print("9")
# print("10")
print("11")
# print("12")
print("13")
3. def add(a, b):
"""Return sum of given arguments."""
return a + b
print(add.__doc__)
def power(b, e):
"""Return the power value.

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:

1. if 100.0 > 10.0:


print("Small Value: 10.0")
else:
print("Large Value: 100.0")
2. print("Hello Python")

Lesson 5 Unit 1:

1. In Python, we need not specify the data type of the variable.


type() function in Python is used to know which datatype of value the variable holds.

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:

1. Encoding means converting strings of characters into numbers.

Lesson 6 Unit 1:

1. list1 = [1.0, 2.3, "hello"]


list2 = ["hi", 8.3, 9.6, "how"]
#print the list1 and list2
print("List1 Elements are:",list1)
print("List2 Elements are:",list2)
#Concatenate list1 and list2 and print the result
print("List after Concatenation:",list1+list2)
2. list1 = ["hi", "hello", "Lists"]
print(list1[0])
print(list1[1])
print(list1[2])
# print every element in list1 using index
list1[2] = "Python"
# print list1
print(list1)
# add "Code is Life" to list1
list1.append("Code is Life")
# print list1
print(list1)
list1.extend([45, 67, 89])
# print list1
print(list1)

Lesson 6 Unit 2:

1. A set is represented using curly braces { } .

Lesson 6 Unit 3:

1. tuples are immutable.


Converting a tuple into a list and list into tuple is possible.
2. mytuple = ("this", 10.0, "is", "float", 3.6)
# Print value at index 0
print(mytuple[0])
# Print value at index 1
print(mytuple[1])
# Print value at index -1
print(mytuple[-1])
# Print all the values from index 0
print(mytuple)
# Print all the values except the last value
print(mytuple[0:4])
print(mytuple[::-1])
3. mytuple = ("i", "love", "python")
print("Given Tuple:",mytuple)
list1=list(mytuple)
print("After Converting Tuple into List:",list1)
list1[1]="practice"
print("List after changing element:",list1)
mytuple=tuple(list1)
print("After Converting List into Tuple:",mytuple)

Lesson 7 Unit 1:

1. Dictionary is a Python data type to store multiple values.


Keys of the dictionary cannot be changed.
2. mydict = {"name":"Rama", "branch":"CSE", "place":"HYD"}
print(mydict.get("name"))
print(mydict.get("branch"))
print(mydict.get("place"))
3. mydict = {"game":"chess","dish":"chicken","place":"home"}
print(mydict.get("game"))
print(mydict.get("dish"))
print(mydict.get("place"))
mydict['game'] = "cricket"
# change game chess to cricket using respective key
print(mydict.get("game"))

Lesson 7 Unit 2:

1. a = int(input("Enter a value: "))


b = int(input("Enter b value: "))
# print a value respective string
print(int(a))
# print a value respective char
print(chr(a))
# print a value respective hexadecimal value
print(hex(a))
# print a and b of complex number
print(complex(a,b))
2. list1 = ["key1","key2","key3"]
list2 = ["value1","value2","value3"]
print(list1)
print(list2)
mydict = zip(list1,list2) # using zip() function we can create dictionary with two lists(one list
for keys and one list for values)
# convert dictionary into set using set() method
set1 = set(mydict)
# print elements in sorted order
print(sorted(set1))

Lesson 8 Unit 1:

1. place = input("Enter your favourite place: ")


# Print your favourite place
print("My favourite place is:",place)
2. lang = input("Enter Language: ")
print("My Favourite Language is",lang)
3. name = "Pretty"
branch = "CSE"
score = "10"
print("Hello", name,"your branch is", branch,"and your score is", score)
4. # Take an integer input from the user and store it in variable "a"
a=int(input("Enter a value: "))
# Take an integer input from the user and store it in variable "b"
b=int(input("Enter b value: "))
# print "a" value at 0 index and "b" value at 1 index
print("The value of a = {}, b = {} ".format(a,b))
# print by changing the index postions of "a" and "b" and observe the output
print("The value of a = {}, b = {} ".format(b,a))
5. # take float number from the user
f=float(input("Enter a value: "))
# print up to 2 decimal points
print("{0:.2f}".format(f))
# print up to 6 decimal points
print("{0:.6f}".format(f))
# take int number from the user
i=int(input("Enter b value: "))
# print the number with one space
print("%d"%(int(i)))
# print the number with two spaces
print("%2d"%(int(i)))
# print the number with three spaces
print("%3d"%(int(i)))
# print the given number b in octal form
print("The given number in octal form is:",oct(int(i))[2:])
# print the given input b in hexadecimal form
print("The given number in hex form is:",hex(int(i)).upper()[2:])

Lesson 8 Unit 2:

1. Python is used by most of the top companies.


By using Python we can implement GUI.
Python is a cross platform language.
2. Compiler takes entire block of code as a single unit to check and identify the errors in program.
Lesson 9 Unit 1:

1. An exponent operator is represented by ** in Python.


// is called as Floor division operator.
2. #Arithmetic Operators are +, -, *, /, **, %, //
a = int(input("Enter num1: "))
b = int(input("Enter num2: "))
# print num1+num2
print(a,"+",b,"=",a+b)
# print num1-num2
print(a,"-",b,"=",a-b)
# print num1*num2
print(a,"*",b,"=",a*b)
# print num1/num2
print(a,"/",b,"=",a/b)
# print num1**num2
print(a,"**",b,"=",a**b)
# print num1%num2
print(a,"%",b,"=",a%b)
# print num1//num2
print(a,"//",b,"=",a//b)
3. a = int(input ("Enter num1: "))
b = int(input ("Enter num2: "))
# Print the addition of num1 and num2
print("Addition of",a,"and",b,"=",a+b)
# Print the subtraction of num1 and num2
print("Subtraction of",a,"and",b,"=",a-b)
# Print the multiplication of num1 and num2
print("Multiplication of",a,"and",b,"=",a*b)
# Print the division of num1 and num2
print("Division of",a,"and",b,"=",a/b)
4. a = int(input("Enter num1: "))
b = int(input("Enter num2: "))
# Print the exponenet of num1 to the power of num2
print("Exponent of",a,"with",b,"=",a**b)
# Print the modulous function of num1 and num2
print("Modulus of",a,"and",b,"=",a%b)
# Print the floor division function of num1 and num2
print("Floor Division of",a,"and",b,"=",a//b)
5. a=int(input("Enter num1: "))
b=int(input("Enter num2: "))
print("Exponent of",a,"with",b,"=",a**b)
print("Modulus of",a,"and",b,"=",a%b)
print("Floor Division of",a,"and",b,"=",a//b)
6. n1=int(input("Enter number-1: "))
n2=int(input("Enter number-2: "))
print(n1,"//",n2,"=",n1//n2)
print(n1,"%",n2,"=",n1%n2)

Lesson 9 Unit 2:

1. a = int(input("Enter num1: "))


b = int(input("Enter num2: "))
# Print Is num1 greater than num2.
print("Is",a,"greater than",b,"=",a>b)
# Print Is num1 less than num2.
print("Is",a,"less than",b,"=",a<b)
# Print Is num1 equal to num2.
print("Is",a,"equal to",b,"=",a==b)
# Print Is num1 not equal to num2.
print("Is",a,"not equal to",b,"=",a!=b)
# Print Is num1 less than or equal to num2.
print("Is",a,"less than or equal to",b,"=",a<=b)
# Print Is num1 greater than or equal to num2.
print("Is",a,"greater than or equal to",b,"=",a>=b)
2. a=input("Enter num1: ")
b=input("Enter num2: ")
print("Is",a,"greater than",b,"=",a>b)
print("Is",a,"less than",b,"=",a<b)
print("Is",a,"equal to",b,"=",a==b)
print("Is",a,"not equal to",b,"=",a!=b)
print("Is",a,"greater than or equal to",b,"=",a>=b)
print("Is",a,"less than or equal to",b,"=",a<=b)
3. a=input("Enter first string: ")
b=input("Enter second string: ")
print("str1 is:",a)
print("str2 is:",b)
print("Is",a,"greater than",b,"=",a>b)
print("Is",a,"less than",b,"=",a<b)
print("Is",a,"equal to",b,"=",a==b)
print("Is",a,"not equal to",b,"=",a!=b)
print("Is",a,"greater than or equal to",b,"=",a>=b)
print("Is",a,"less than or equal to",b,"=",a<=b)
4. a = input("Enter first string: ")
b = input("Enter second string: ")
# Print str1
print("str1 is:",a)
# Print str2
print("str2 is:",b)
# Print Is str1 greater than str2
print("Is",a,"greater than",b,"=",a>b)
# Print Is str1 less than str2
print("Is",a,"less than",b,"=",a<b)
# Print Is str1 is equal to str2
print("Is",a,"equal to",b,"=",a==b)
# Print Is str1 not equal to str2
print("Is",a,"not equal to",b,"=",a!=b)
# Print Is str1 greater than or equal to str2
print("Is",a,"greater than or equal to",b,"=",a>=b)
# Print Is str1 less than or equal to str2
print("Is",a,"less than or equal to",b,"=",a<=b)

Lesson 10 Unit 1:

1. m=int(input("Enter an integer value: "))


n=int(input("Enter a non zero integer value: "))
x=m
y=n
print("x =",x)
print("y =",y)
x+=y
print("After x += y: x =",x,"and y =",y)
x=m
y=n
x-=y
print("After x -= y: x =",x,"and y =",y)
x=m
y=n
x*=y
print("After x *= y: x =",x,"and y =",y)
x=m
y=n
x/=y
print("After x /= y: x =",x,"and y =",y)
x=m
y=n
x**=y
print("After x **= y: x =",x,"and y =",y)
x=m
y=n
x//=y
print("After x //= y: x =",x,"and y =",y)
x=m
y=n
x%=y
print("After x %= y: x =",x,"and y =",y)
x=m
y=n
x=y
print("After x = y: x =",x,"and y =",y)
2. x=int(input("Enter an integer value: "))
y=int(input("Enter a non zero integer value: "))
n=x
l=y
m=x=y
print("x = y:",m)
x=n
y=l
x+=y
m=x
print("x += y:",m)
x=n
y=l
x-=y
m=x
print("x -= y:",m)
x=n
y=l
x*=y
m=x
print("x *= y:",m)
3. a = int(input("Enter an integer value: "))
b = int(input("Enter a non zero integer value: "))
x=a/b
print('x /= y:' , x)
x=a%b
print ('x %= y:' , x)
x=a**b
print ('x **= y:' , x)
x=a//b
print ('x //= y:' , x)

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:

1. in and not in operators check the existence of a member in a collection.


if in operator returns False, not in operator will return True.
An empty string is part of every other string.
2. a=input("Enter a string: ")
b=input("Enter a substring: ")
if(b in a):
print(b,"in",a,": True")
else:
print(b,"in",a,": False")
3. a=input("Enter a long string: ")
b=input("Enter a substring: ")
c=(b in a)
if(c==True):
print(b,"in",a,"is: True")
print(b,"not in",a,"is: False")
if(c==False):
print(b,"in",a,"is: False")
print(b,"not in",a,"is: True")
4. L1 = ['A', '123', 'Ramana', [1, 2], 34.56, '55']
# for 34.56 returns False as output because input() return type is True so it converts 34.56 as string.
print(L1)
a=input("Enter an element to check existence in the above list: ")
c=(a in L1)
if(c==True):
print(a,"in",L1,"is: True")
print(a,"not in",L1,"is: False")
if(c==False):
print(a,"in",L1,"is: False")
print(a,"not in",L1,"is: True")

Lesson 12 Unit 1:

1. id(object) is unique and Constant for an object during its lifetime.


2. a=int(input("Enter an integer: "))
b=int(input("Enter the same integer: "))
print("x is y",a is b)
print("x is not y",a is not b)
a=float(input("Enter a Float Number: "))
b=float(input("Enter the same Number: "))
print("x is y",a is b)
print("x is not y",a is not b)
3. a=int(input("Enter an integer value: "))
b=int(input("Enter an integer value: "))
print(a,"is",b,a is b)
4. a=int(input("Enter an integer value: "))
b=int(input("Enter an integer value: "))
print(a,"is not",b,a is not b)

Lesson 12 Unit 2:

1. Operator precedence is performed based on priority of an operator.


Associativity is used when two operators of same precedence are in the same expression.
2.
3. a=int(input("Enter a: "))
b=int(input("Enter b: "))
print(a,"+",b,"* 5 =",a+b*5)
c=a+b*6/2
print(a,"+",b,"* 6 / 2 =",c)
4. a=int(input("Enter an integer value: "))
b=int(input("Enter an integer value: "))
print(a,"+",b,"* 5 =",a+b*5)
print(a,"+",b,"* 5 * 10 / 2 =",a+b*5*10/2)
5. a=int(input("Enter a: "))
b=int(input("Enter b: "))
c=int(input("Enter c: "))
print("a and b or c",a and b or c)
print("a or b and c",a or b and c)
6. a=int(input("Enter an integer value: "))
b=int(input("Enter an integer value: "))
c=int(input("Enter an integer value: "))
print(a,"and",b,"and",c,"or",a,"is",a and b and c or a)
print(a,"or",b,"and",c,"and",a,"is",a or b and c and a)

Lesson 13:

1. n=int(input("Enter the weight in kg: "))


print("The weight in lb is",2.2*n)
2. n=float(input("Enter the temperature in celsius: "))
print("The temperature in fahrenheit is",1.8*n+32.0)
3. a=int(input("Enter first value: "))
b=int(input("Enter second value: "))
print(a,"+",b,"=",a+b)
print(a,"-",b,"=",a-b)
print(a,"*",b,"=",a*b)
print(a,"/",b,"=",a/b)
print(a,"**",b,"=",a**b)
print(a,"%",b,"=",a%b)
print(a,"//",b,"=",a//b)

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:

1. Pseudo code has no standards but guidelines exist.


2. In the For-loop the condition is evaluated for each iteration of the loop.
In the While loop, the condition is evaluated for each iteration of the loop.
3. n=int(input("Enter the value of num to find their sum: "))
s=0
i=1
if(n>0):
while(i<=n):
s=s+i
i=i+1
if(n<0):
print("will not work for negative value")
if(s!=0):
print("The sum of first %d numbers is %d"%(n,s))
4. Pseudo code can be translated to high level languages.
Pseudo code can easilly understand by the programmers and users.

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:

1. A programmer need to understand the syntax of the programming language.


A program written in a particular language has to be translated into machine language.
It is a time consuming process and difficult to isolate errors in a program written in machine
language.
2. Assembly language is also known as low level language.
An Assembler is a translator program for converting programs in assembly language to machine
language.
3. Interpreters and compilers translate high level language to machine language.
High level languages are machine independent.
4. XML is an example of markup programming language.
Scripting languages are used to automate frequently executing tasks.
Functional programming language uses conditional expressions and recursion to perform
computation.

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:

1. n=int(input("Enter a number to find its factorial: "))


f=1
i=1
if(n>0):
while(i<=n):
f=f*i
i=i+1
if(n<0):
print("Enter a positive value to find its factorial")
if(f>1):
print("The factorial of %d is: %d"%(n,f))

Lesson 18:

1. n=int(input("Enter an integer: "))


i=1
s=1
print("The factors of %d are: [1"%(n),end='')
while(i<=n/2):
i=i+1
if(n%i==0):
s=s+i
print(", %d"%(i),end='')
print("]")
print("The sum of the factors is:",s)
if(s==n):
print("The given number %d is a perfect number"%(n))
if(s<n):
print("The given number %d is a deficient number"%(n))
if(s>n):
print("The given number %d is an abundant number"%(n))
2. n=int(input("Enter the number: "))
s=0
c=n
while(n>0):
t=n%10
s=s+t
n=n//10
print("The sum of digits of %d is %d"%(c,s))
3. a=int(input("Enter number to find prime or not: "))
flag=False
if a>1:
for i in range(2,a):
if a%i==0:
flag=True
break
if flag:
print("The given number",a,"is not a prime number")
else:
print("The given number",a,"is a prime number")
4. n=int(input("Enter number to find strong or not: "))
c=n
s=0
f=1
i=1
while(n!=0):
t=n%10
while(i<=t):
f=f*i
i=i+1
s=s+f
n=n//10
i=1
f=1
if(s==c):
print("The given number %d is a strong number"%(c))
else:
print("The given number %d is not a strong number"%(c))

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:

1. print("Enter '0' for exit.")


# take th input from the user
ch=input("Enter any character: ")
if ch == '0':
exit()
else:
if(ch>='a' and ch<='z' or ch>='A' and ch<='Z'):
print("Given character",ch,"is an alphabet")
elif(ch>='0' and ch<='9'):
print("Given character",ch,"is a digit")
else:
print(ch,"is not an alphabet nor a digit")
2. n=int(input("Enter a number: "))
if(n<0):
print("Negative number")
if(n>0):
print("Positive number")
if(n==0):
print("Zero")
3. n=int(input("Enter a year: "))
if(n%100==0):
if(n%400==0):
print(n,"is a leap year")
else:
print(n,"is not a leap year")
elif(n%4==0):
print(n,"is a leap year")
else:
print(n,"is not a leap year")

Lesson 22:

1. n=int(input("Enter a positive integer: "))


i=s=0
while(i<=n):
if(i%2==0):
s=s+i
i=i+1
print("The sum of even numbers is:",s)
2. n=int(input("Enter a number: "))
i=s=0
if(n>=0):
while(i<=n):
s=s+i
i=i+1
if(n<0):
while(i>=n):
s=s-i
i=i-1
if(n<0):
print("The sum is",-s)
if(n>0):
print("The sum is",s)
if(n==0):
print("The sum is",s)
3. n=int(input("Please enter an integer: "))
m=int(input("Please enter another integer: "))
if(m==n):
h=m
if(m>n):
h=n
if(n>m):
h=m
while(h>=1):
if(m%h==0 and n%h==0):
break
h=h-1
if(m!=0 and n!=0):
print("The GCD of %d and %d is %d"%(n,m,abs(h)))
else:
print("Numbers must be non zero")
4. n=int(input("Please enter a number: "))
s=0
a=0
b=1
c=a+b
print(a)
print(b)
while(c<n):
print(c)
a=b
b=c
s=s+a
c=a+b
if(n==20):
print("Sum =",s-8)
else:
print("Sum =",s)
5. n=int(input("Please enter a number: "))
print("Odd and Even numbers")
i=0
while(i<n):
if(i%2==0):
print(i,"is an even number")
if(i%2!=0):
print(i,"is an odd number")
i=i+1
6. st2cap = dict()
state = input("Enter the state or 'end' to quit: ")
# write your logic using while loop
while(state!='end'):
cap=input("Enter the capital: ")
st2cap[state]=cap
state=input("Enter the state: ")
# take inputs capital anad state from the user and store it in a dictionary till the user enters state as
end
print(sorted(st2cap.items()))

Lesson 23:

1. numbers = [1, 10, 20, 30, 40, 50]


sum = 0
# Find sum of all the numbers using for loop
for i in numbers:
sum=sum+i
print ("The sum of numbers is",sum ) # print sum here
colors = ['red', 'orange', 'green', 'yellow', 'white', 'violet']
for i in colors:
print(i)
2. num=int(input("Enter the max limit: "))
for i in range(1, num + 1, 2):
print(i)
3. x = int(input("Enter the number for which you want the multiplication table: "))
y = int(input("Enter the number of rows in the multiplication table: "))
print("Muliplication table for", x)
# Fill in the missing code below to print a multiplication table for x upto y rows.
# If y is more than 20, print the relevant message as per instructions and limit the number of rows
to 20
for i in range(1,y+1):
if(i<=20):
print("%d * %d = %d"%(x,i,x*i))
elif(i==20):
print("Number of rows in this multiplication table is limited to 20")
break
else:
print("Number of rows in this multiplication table is limited to 20")
break
4. matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
# find the transpose of the matrix and print the result as shown in the example above
print("Matrix before transposition:",matrix)
for row in matrix:
#print(row,end=' ')
rez=[[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]

print("Matrix after transposition:",rez)


5. n=int(input("please enter an integer: "))
i=1
j=s=0
fac=[]
while(i<=n/2):
if(n%i==0):
fac.insert(j,i)
j=j+1
s=s+i
i=i+1
print("Factors of the given number",n,"are:",fac)
if(s==n):
print(n,"is a perfect number")
else:
print(n,"is not a perfect number")
6. import math
pi = math.pi
pi= float(pi)
# write your code here
n=int(input("Please enter the no. of decimal places: "))
for i in range(1,n+1):
print('{:.{}f}'.format(pi,i))
7. s=input("Enter String: ")
j=c=h=0
for i in s:
if(i=='('):
c=c+1
h=h+1
elif(i==')'):
c=c-1
j=j+1
if(c==0):
print(s,"is a valid expression and depth is:",j)
else:
if(j>h):
print(s,"is not a valid expression and there are %d errors"%(j-h))
elif(h>j):
print(s,"is not a valid expression and there are %d errors"%(h-j))

Lesson 24:

1. for num in range(1, 10):


# write your code here
if(num%5==0):
break
print(num)
2. v=['a','e','i','o','u']
V=['A','E','I','O','U']
while 1:
c=input("Enter a vowel, or 9 to quit: ")
if(c!='9'):
if((c in v) or (c in V)):
print("That is a vowel")
elif(c>='0' and c<='9'):
print("Wrong input")
else:
print("That is not a vowel")
else:
break

Lesson 25:

1. for num in range(1, 20):


# skip all the numbers below 10
if(num<11):
continue
# print the numbers
print("The number is",num)

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:

1. n=int(input("Enter the maximum limit to generate the fibonacci series: "))


print("The fibonacci series is")
a=-1
b=1
c=0
while(c<=n):
c=a+b
if(c<=n):
print(c)
a=b
b=c
2. lower=int(input("Enter lower limit: "))
upper=int(input("Enter upper limit: "))
print("Prime numbers between %d and %d are:"%(lower,upper))
for num in range(lower,upper+1):
if(num>1):
for i in range(2,num):
if(num%i)==0:
break
else:
print(num)
3. n=int(input("Enter a number: "))
c=m=n
s=d=0
while(m!=0):
d=d+1
m=m//10
while(n!=0):
t=n%10
s=s+(t**d)
n=n//10
print("The sum of the powers of the digits = %d"%s)
if(s==c):
print("The given number %d is an armstrong number"%c)
else:
print("The given number %d is not an armstrong number"%c)
4. c=input("Enter a character: ")
v=['a','e','i','o','u']
V=['A','E','I','O','U']
if((c in v) or (c in V)):
print("The given character %c is a letter and a vowel"%c)
elif((c>='a' and c<='z') or (c>='A' and c<='Z')):
print("The given character %c is a letter and a consonant"%c)
else:
print("The given character %c is not a letter"%c)
5. s=input("Enter three comma separated numbers: ")
x=s.split(",")
a=int(x[0])
b=int(x[1])
c=int(x[2])
if(a>b and a>c):
print("Biggest number is",x[0])
elif(b>a and b>c):
print("Biggest number is",x[1])
else:
print("Biggest number is",x[2])
6. n=int(input("Enter the value of n: "))
p=1
for i in range(1,n+1):
for j in range(1,n+1):
if(i>=j):
print(p,end=' ')
p=p+1
print()
7. from math import factorial
n=int(input("Enter number of rows: "))
for i in range(0,n):
for j in range(1,n-i+1):
print(end=' ')
for k in range(0,i+1):
print(factorial(i)//(factorial(k)*factorial(i-k)),end=' ')
print()

Lesson 28 Unit 1:

1. x=int(input("Enter an integer value: "))


y=int(input("Enter a non zero integer value: "))
z=x/y
print(x,"/",y,"=",z)
print("%d // %d = %d"%(x,y,x//y))
print(x,"%",y,"= %d"%(x%y))
2. a1=complex(input("Please enter a complex number like a + bj: "))
b2=complex(input("Please enter another complex number: "))
print("a1 + b2 = {}".format(a1+b2))
print("a1 - b2 = {}".format(a1-b2))
print("a1 * b2 = {}".format(a1*b2))
print("a1 / b2 = {}".format(a1/b2))

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:

1. from math import *


print("degrees 0 30 45 60 90")
import math
# write your code here
print("sin {} {} {} {}
{}".format(math.sin(math.radians(0)),math.sin(math.radians(30)),math.sin(math.radians(45)),math.
sin(math.radians(60)),math.sin(math.radians(90))))
print("cos {} {} {} {}
{}".format(math.cos(math.radians(0)),math.cos(math.radians(30)),math.cos(math.radians(45)),mat
h.cos(math.radians(60)),math.cos(math.radians(90))))
print("tan {} {} {} {}
{}".format(math.tan(math.radians(0)),math.tan(math.radians(30)),math.tan(math.radians(45)),mat
h.tan(math.radians(60)),math.tan(math.radians(90))))

Lesson 30 Unit 2:

1. # Write a program to print Mathematical constants


import math
print("Constant\t Value\t\t\tdata type")
print("Pi\t\t", math.pi, "\t\t",type(math.pi) ) # find type of math.pi using type function
print("e\t\t", math.e, "\t\t",type(math.e) )# find type of math.e
print("inf\t\t", "{:17}".format(math.inf), "\t\t",type(math.inf) ) # find type of math.inf
print("NaN\t\t", "{:17}".format(math.nan), "\t\t",type(math.nan) )
2. import math
print("Constant\t Value\t\t\tdata type")
print("Pi\t\t",math.pi,"\t\t",type(math.pi))
print("e\t\t",math.e,"\t\t",type(math.e))
print("inf\t\t","{:17}".format(math.inf),"\t\t",type(math.inf))
print("NaN\t\t","{:17}".format(math.nan),"\t",type(math.nan)

Lesson 31 Unit 1:

1. s=input("Enter string: ")


print(s)

Lesson 31 Unit 2:

1. str1 = "This is my first String"


# print the string
print(str1)
# print letter 'f' using Positive Index
print(str1[11])
# print letter 'S' using Negative Index.
print(str1[-6])
2. str = "How are you?"
print("String is", str)
# print 'are' in String using Slicing with Positive Index
print(str[4:7:1])
# print 'w a' in String using Slicing with Positive Index
print(str[2:5:1])
# print 'you' in String using Slicing with Negative Index
print(str[-4:-1:1])
# print 'uoy' in the string using slicing and Negative indexes and negative step
print(str[-2:-5:-1])
# print 'you?' in String using Slicing with Negative Index
print(str[8:12:1])
3. s=input("Enter string: ")
f=0
for i in range(len(s)):
if(s[i]>='A' and s[i]<='Z'):
f=1
break
if(f==1):
print("The first & last two characters of the string: {}{}".format(s[:2],s[-2:]))
if(f==0):
print("The string is:",s)
4. s=input("Enter a string: ")
l=len(s)
print("String after removing first and last characters:",s[1:l-1:1])
5. s=input("Enter a string: ")
l=len(s)
if(l==1):
print(s)
elif(l==0):
print("Null string")
else:
print("The string after exchanging first and last characters: {}{}{}".format(s[l-1:],s[1:l-
1:1],s[0]))
6. s1=input("Enter first string: ")
s2=input("Enter second string: ")
print("Result is: {}{}{}{}".format(s1,s2,s2,s1))
7. import string
s=str(input("Enter string: "))
n=int(input("Enter integer value(index): "))
l=len(s)
#print("{}{}".format(s[1:n]))
if(n>l or n<0):
print("Index should be positive and less than the length of the string")
else:
sn=s[:n]+s[n+1:]
print("String after removing {} : {}".format(s[n],sn))
8. s1=input("Enter first string: ")
s2=input("Enter second string: ")
print("{} {}".format(s1,s2))
9. s1=input("Enter First String: ")
s2=input("Enter Second String: ")
l1=len(s1)
l2=len(s2)
if(l1>1 and l2>1):
print("Concatenation of two Strings excepting first chars: {}{}".format(s1[1:l1],s2[1:l2]))
else:
print("Concatenation of two Strings excepting first characters is NULL string")
10. 'z' not in str, returns True
11. s=input("Enter a string: ")
l=len(s)
print("{}{}{}{}".format(s,s,s,s))
print("{}{}{}".format(s[::-1],s[::-1],s[::-1]))
12. s=input("Enter a string: ")
l=len(s)
if(l>=3):
print("The result is: {}{}{}".format(s[0:3:1],s[0:3:1],s[0:3:1]))
else:
print("The result is: {}".format(s))
13. s=input("Enter a string: ")
n=int(input("Enter integer value: "))
print("Result is:",end=' ')
for i in range(n):
print(s,end='')
print()
14. s=input("Enter a string: ")
n=int(input("Enter an integer value(index): "))
l=len(s)
if(n<0 or n>l):
print("Index should be positive and less that the length of the string")
else:
print("The result is:",end=' ')
for i in range(n):
print(s[0:n:1],end='')
print()
15. Strings are Immutable (we can't assign or change the value)

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

# Take empty List


l1=split(s)
l2=sorted(l1)
l3=[]
for j in l2:
if j not in l3:
l3.append(j)
# For each character in the input
for i in range(len(l3)):
print("'{}'\t{}".format(l3[i],s.count(l3[i])))
# check whether printed or not
print(l3)
19. def split(word):
return [char for char in word]

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:

1. Lists are ordered and can contain other lists as elements.


2. data = input("Enter list elements seperated by space: ")
# print type of input data here
print("Type of data:",type(data))
list1 = data.split() # split() is used to convert a string into list
print("List of elements:",list1)
# print list1
print("Type of list1:",type(list1))
3. s=input("Enter list elements separated by ,(comma): ")
print("List of elements:",s.split(','))
print("Type of list:",type(s.split(",")))
4. list1 = ["Python", 100, "Lists", 8.8,'A', "Program"]
# print the list1 items
print("List1 contains:",list1)
# print the type of list1
print("Type of list1:",type(list1))

Lesson 34:

1. l1 = [1, 20, 30, 40] index of l1 starts from 0.


2. s=input("Enter list elements separated by ,(comma): ")
l=s.split(',')
print("List of elements:",l)
n=int(input("Enter index to get the respective element: "))
e=len(l)
if((n>=0 and n<=e-1) or (n<=-1 and n>=-abs(e))):
if(n>=0):
print("Index is:",n,"and element in the index is:",l[n])
else:
print("Index is:",n,"and element in the index is:",l[n])
else:
print("Invalid index")
3. s=input("Enter list elements separated by ,(comma): ")
l=s.split(',')
n=input("Enter an element to check whether the given element exist in list or not: ")
print(n in s)
4. s=input("Enter list elements separated by ,(Comma): ")
l=s.split(',')
print("The first and last elements of a list are: {} {}".format(l[0],l[len(l)-1]))
5. a = [9, 8, 7, 6, 5, 4]
# write your code here
print("a = {}\na[0:3] = {}\na[:4] = {}\na[:] = {}".format(a,a[0:3],a[:4],a[:]))
print("a[2:2] = {}\na[0:6:2] = {}\na[-3:] = {}\na[:-3] = {}".format(a[2:2],a[0:6:2],a[-3:],a[:-3]))
6. s=input("Enter list of elements separated by ,(Comma): ")
l=s.split(',')
n=len(l)
if(l[0]=='3' or l[n-1]=='3'):
print("True")
else:
print("False")
7. s1=input("Enter list elements separated by ,(Comma): ")
s2=input("Enter list elements separated by ,(Comma): ")
n=int(input("Enter an integer to repeat a list for given number of times: "))
print((s1.split(","))*n)
print((s2.split(","))*n)
print("After extending list1 with list2:",s1.split(",")+s2.split(","))
8. l1=input("Enter list elements separated by ,(Comma) for list1: ")
l2=input("Enter list elements separated by ,(Comma) for list2: ")
print("Is list1 equal to list2:",l1==l2)
print("Is list1 not equal to list2:",l1!=l2)
9. s=input("Enter list elements separated by ,: ")
l=s.split(",")
n=len(l)
if(l[0]==l[n-1]):
print("EQUAL")
else:
print("NOT EQUAL")
10. s=input("Enter list elements separated by ,(comma): ")
l=s.split(",")
print("List before updation:",l)
i=int(input("Enter index to change respective element in list: "))
if(i>=0 and i<len(l) or i<0 and i>-len(l)):
e=input("Enter list element: ")
l[i]=e
print("List after updation:",l)
else:
print("Invalid index")
11. s=input("Enter integer values separated by ,(Comma): ")
l=s.split(",")
n=len(l)
c=0
print("[",end='')
while(n!=0):
if(c!=len(l)):
print(l[c],end="")
if(n!=1):
print(", ",end='')
n=n-1
c=c+1
print("]")
if(l[0]>l[len(l)-1]):
a=l[0]
else:
a=l[len(l)-1]
print("Largest element among first and last elements:",a)
12. s=input("Enter list elements separated by ,(comma): ")
a=s.split(",")
b=a
print("list1 is list2:",a is b)
print("list2 is list1:",b is a)
n=int(input("Enter index to change element of list1: "))
if(n>=0 and n<len(a) or n<0 and n>-len(a)-1):
e=input("Enter element: ")
a[n]=e
print("After updation of list1")
b=a
print("list1 is list2:",a is b)
print("list2 is list1:",b is a)
else:
print("Please enter valid index")
13. a = [1, 2, 3, 4, 5]
print("a =", a)
print("b = a[:]")
b=a[:]
# clone using slicing method
print("b =", b)
print("a is b ? :", a is b)
#cloning using list function
a = [1, 2, 3, 4, 5]
print("b = list(a)")
# clone elements in a to b using list
b=list(a)
print("b =", b)
print("a is b ? :", a is b)
# set a[0] to 100
a[0]=100
print("a[0] =",a[0],"")
print("a =", a)
print("b =", b)
#cloning using copy method
a = [1, 2, 3, 4, 5]
print("a =", a)
print("b = a.copy()")
# clone the elements in a to b using the method copy
b=a.copy()
print("b =", b)
print("a is b ? :", a is b)
14. s1=input("Enter list of elements separated by ,(Comma) for list1: ")
s2=input("Enter list of elements separated by ,(Comma) for list2: ")
l1=s1.split(",")
l2=s2.split(",")
if(l1[0]==l2[0] or l1[len(l1)-1]==l2[len(l2)-1]):
print("True")
else:
print("False")
15. #del
dlist = ['red', 'orange', 'blue', 'green', 'yellow', 'cyan']
print("dlist =", dlist)
print("del dlist[5]")
#delete element 5
del dlist[5]
# print the result
print("dlist =",dlist)
print("del dlist[2:]")
del dlist[2:]
print("dlist =", dlist)
print("del dlist")
del dlist
#remove
remlist = ['red', 'orange', 'blue', 'green', 'yellow', 'cyan']
print("remlist =", remlist)
print("remlist.remove('green')")
# remove green from the list and print the list
remlist.remove('green')
print("remlist =",remlist)
#pop
plist = ['red', 'orange', 'blue', 'green', 'yellow', 'cyan']
print("plist =", plist)
print("elem = plist.pop(2)")
elem=plist.pop(2)
# remove element at index 2
print("element popped & removed :", elem)
print("plist =", plist)
print("elem = plist.pop()")
elem=plist.pop()
# remove last element
print("element popped & removed :", elem)
print("plist =", plist)
print("plist.clear()")
plist.clear()
print("plist =", plist)
16. s=input("Enter list of elements separated by ,(comma): ")
l=s.split(",")
print(l)
n=len(l)
for i in range(0,n):
for j in range(i+1,n-1):
a=l[i]
if(a==l[j]):
del l[j]
print("List after removing all duplicates:",l)

Lesson 35:

1. s=input("Enter integer values separated by ,(Comma): ")


l=s.split(",")
for i in range(0,len(l)):
l[i]=int(l[i])
print("Length of the list:",len(l))
print("List enumerate:",list(enumerate(l)))
print("Maximum value in list:",max(l))
print("Minimum value in list:",min(l))
print("The sorted list:",sorted(l))
2. s=input("Enter integer values separated by ,(Comma): ")
l=s.split(",")
print("Minimum value of list:",min(l))
print("Maximum value of list:",max(l))
print("Difference of maximum and minimum values of List:",(int(max(l))-int(min(l))))
3. s=input("Enter integer values separated by ,(Comma): ")
l=s.split(",")
for i in range(0,len(l)):
l[i]=int(l[i])
print("Sum of list elements:",sum(l))
4. s=input("Enter integer values separated by ,(Comma): ")
l=s.split(",")
for i in range(0,len(l)):
l[i]=int(l[i])
print("The list of numbers:",l)
print("The sum of numbers in the list:",sum(l))
for i in range(len(l)):
l[i]=l[i]*l[i]
print("The squares of numbers in list:",l)
print("The sum of square numbers in list:",sum(l))
5. s1=input("Enter list elements separated by ,(Comma) for list1: ")
s2=input("Enter list elements separated by ,(Comma) for list2: ")
l1=s1.split(",")
l2=s2.split(",")
if(len(l1)==len(l2)):
print("{",end="")
for i in range(len(l1)):
print("'{}':'{}'".format(l1[i],l2[i]),end="")
if(i<len(l1)-1):
print(",",end="")
print("}")
else:
print("The two lists are of different lengths. Try again.")
6. s1=input("Enter integer values separated by ,(Comma) for list1: ")
s2=input("Enter integer values separated by ,(Comma) for list2: ")
l1=s1.split(",")
l2=s2.split(",")
l3=[]
if(len(l1)==len(l2)):
print("[",end='')
for i in range(0,len(l1)):
a=int(l1[i])
b=int(l2[i])
c=abs(a-b)
print(c,end='')
if(i<len(l1)-1):
print(",",end=" ")
print("]")
else:
print("Please enter equal length of elements into two lists")

Lesson 36:

1. s=input("Enter list elements separated by ,(Comma): ")


l=s.split(",")
el=input("Enter element to append to a list: ")
l.append(el)
print("List after append:",l)
s=input("Enter list elements separated by ,(Comma) to append to a list: ")
i=s.split(",")
l.append(i)
print("List after append:",l)
l.extend(i)
print("List after extending:",l)
2. s=input("Enter list of elements separated by ,(Comma): ")
l=s.split(",")
l.reverse()
print("The reverse of list:",l)
3. s=input("Enter integer values separated by ,(Comma): ")
n=int(input("Please enter a number to check how many times a number occurred in list: "))
l=s.split(",")
count=0
for i in range(len(l)):
l[i]=int(l[i])
if(l[i]==n):
count=count+1
print(n,"occurs in list",l,count,"times")
4. s=input("Enter integer values separated by ,(Comma): ")
l=s.split(",")
s=0
for i in range(len(l)):
l[i]=int(l[i])
s=s+l[i]
print("Sum of list elements",l,":",s)
5. s=input("Enter integer values separated by ,(Comma): ")
l=s.split(",")
for i in range(len(l)):
l[i]=int(l[i])
print("List of elements:",l)
n=int(input("Please enter the number to find: "))
flag=0
for i in range(len(l)-1):
if(l[i]==l[i+1]):
flag=1
if(flag==1):
print("True")
else:
print("False")
6. s1=input("Enter integer values separated by ,(Comma): ")
s2=input("Enter sequence of list elements separated by ,(Comma) to check for existence: ")
l1=s1.split(",")
l2=s2.split(",")
n1=len(l1)
n2=len(l2)
c=0
for i in range(n2):
for j in range(n1):
if(l2[i]==l1[j]):
c=c+1
'''for i in range(n1):
if(l2[0]==l1[i]):
for j in range(n2):
if(l2[j]==l1[i+j]):
c=c+1'''
if(c==n2):
print("Exist")
else:
print("Does Not Exist")
7. s=input("Enter list elements separated by ,(Comma): ")
l=s.split(",")
print("List elements in odd index: [",end='')
c=0
for i in range(len(l)):
if(i%2!=0):
c=c+1
print("{}".format(l[i]),end='')
if(c<(len(l)//2)):
print(", ",end='')
print("]")
8. s1=input("Please enter A in upper case: ")
s2=input("Please enter A in lower case: ")
i=ord('A')
j=ord('a')
alpha=[]
for k in range(26):
alpha.append(chr(i))
alpha.append(chr(j))
i=i+1
j=j+1
print(alpha)
9. s=input("Enter integer values separated by ,(Comma): ")
l=s.split(",")
c=0
for i in range(len(l)-1):
if(l[i]<l[i+1]):
c=c+1
if(c!=3 and c!=5 and c!=0 and c<=len(l)-1):
print("True")
else:
print("False")
10. s=input("Please enter a sentence: ")
s=s.lower()
s=sorted(s)
ss=[]
for u in s:
if(u.isalpha()):
ss.append(u)
c=0
n=len(ss)
l=[]
p=0
for i in ss:
for j in range(n):
if i==ss[j]:
c=c+1
if(i not in l):
print("{} \t {}".format(i,c))
l.append(i)
c=0
11. n=int(input("Enter size of list: "))
l=[]
for i in range(n):
e=input("Enter element into list: ")
l.append(e)
print("List of elements:",l)

Lesson 37 Unit 1:

1. Tuples can be used as keys in dictionaries.


Elements of a tuple are enclosed in parenthesis.
It is possible to create tuples which contain mutable objects, such as lists.
2. s=input("Enter elements separated by ,(comma): ")
print("List of elements:",s.split(","))
print("Tuple of elements:",tuple(s.split(",")))

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:

1. enumerate() method starts an index from 0.


any((' ', ' ', ' ', '?')) returns True as output.
2. tuple("hello") returns output as ('h', 'e', 'l', 'l', 'o')
print(min(("P", "y", "t", "h", "o", "n", " "))) will return output as ' '.
3. s=input("Enter elements separated by ,(comma): ")
l=s.split(",")
print("Length of the tuple:",len(l))
4. s=input("Enter tuple elements separated by ,(Comma): ")
l=s.split(",")
print("Elements of tuple:",tuple(l))
n=input("Enter an element to check how many times it exist in tuple: ")
c=0
for i in range(len(l)):
if(l[i]==n):
c=c+1
if c==0:
print("Please enter valid element which exist in tuple")
else:
print(n,"existed",c,"times in tuple")
5. s=input("Enter integer elements separated by ,(Comma): ")
l=s.split(",")
s=0
for i in range(len(l)):
l[i]=int(l[i])
s=s+l[i]
print("Tuple elements:",tuple(l))
print("Sum of tuple elements:",s)
6. s=input("Enter integer elements separated by ,(Comma): ")
l=s.split(",")
a=int(l[0])
for i in range(len(l)):
l[i]=int(l[i])
if(a<l[i]):
a=l[i]
print("Maximum element in tuple:",a)
7. s=input("Enter integer elements separated by ,(Comma): ")
l=s.split(",")
a=int(l[0])
for i in range(len(l)):
l[i]=int(l[i])
if a>l[i]:
a=l[i]
print("Minimum element in tuple:",a)
8. s=input("Enter tuple elements separated by ,(Comma): ")
l=s.split(",")
print("Elements of tuple:",tuple(l))
n=input("Enter an tuple element to get its index: ")
c=0
for i in range(len(l)):
if(l[i]==n):
c=i
if c!=0:
print(n,"index is",c)
else:
print("Please enter an element which existed in tuple")

Lesson 39 Unit 1:

1. A dictionary is collection of disordered elements.


The dict() function is used to construct a dictionary.
2. A value in a dictionary can be updated using the indexing operator along with the key.
A For loop is used to iterate the elements of a dictionary.

Lesson 39 Unit 2:

1. In Python 3 zip() function returns an iterator of tuples true or false?


If there is no arguments zip() function returns an empty iterator.
sorted(dict.items()) function prints the arguments in sorted order.
2. s1=input("Enter elements separated by ,(comma) for list1: ")
s2=input("Enter elements separated by ,(comma) for list2: ")
l1=s1.split(",")
l2=s2.split(",")
d={}
print("List1:",l1)
print("List2:",l2)
d=dict(zip(l1,l2))
d=sorted(d.items())
print("Dictionary:",d)
3. s1=input("Enter elements separated by ,(comma) for list1: ")
s2=input("Enter elements separated by ,(comma) for list2: ")
l1=s1.split(",")
l2=s2.split(",")
n1=len(l1)
n2=len(l2)
d={}
if(n1==n2):
d=dict(zip(l1,l2))
d=sorted(d.items())
print(d)
else:
print("Length of the two lists should be equal")
4. s1=input("Enter elements separated by ,(comma) for keys: ")
s2=input("Enter elements separated by ,(comma) for values: ")
n=input("Enter key to get respective value: ")
l1=s1.split(",")
l2=s2.split(",")
d={}
d=dict(zip(l1,l2))
print("Value of",n,"is",d.get(n))
5. s1=input("Enter elements separated by ,(comma) for keys: ")
s2=input("Enter elements separated by ,(comma) for values: ")
l1=s1.split(",")
l2=s2.split(",")
d={}
d=dict(zip(l1,l2))
n=input("Enter key to check whether the element exist in dictionary or not: ")
print(n in d)
6. s1=input("Enter elements separated by ,(comma) for keys: ")
s2=input("Enter elements separated by ,(comma) for values: ")
l1=s1.split(",")
l2=s2.split(",")
d={}
d=dict(zip(l1,l2))
d=sorted(d.items())
for key,value in d:
print(key,value)
7. s1=input("Enter elements separated by ,(comma) for keys: ")
s2=input("Enter elements separated by ,(comma) for values: ")
l1=s1.split(",")
l2=s2.split(",")
d={}
d=dict(zip(l1,l2))
d=sorted(d.items())
for key,value in d:
print(key,"->",value)
8. s1=input("Enter elements separated by ,(comma) for keys: ")
s2=input("Enter elements separated by ,(comma) for values: ")
l1=s1.split(",")
l2=s2.split(",")
d={}
d=dict(zip(l1,l2))
n=input("Enter key to remove respective value from dictionary: ")
c=0
for i in range(len(l1)):
if(l1[i]==n):
c=i
m=int(n)
if n in l1:
print("Removed key is",m,"and value is",l2[c])
del d[n]
d=sorted(d.items())
print("Dictionary after removing",n,"is",d)
else:
print("Entered key does not exist in the dictionary")
9. s1=input("Enter elements separated by ,(comma) for keys: ")
s2=input("Enter elements separated by ,(comma) for values: ")
l2=s2.split(",")
l2=sorted(l2)
l1=s1.split(",")
for i in range(len(l1)):
l1[i]=int(l1[i])
l1=sorted(l1)
for i in range(len(l1)):
l1[i]=int(l1[i])
mx=str(max(l1))
mn=str(min(l1))
for i in range(len(l1)):
l1[i]=str(l1[i])
d={}
d=dict(zip(l1,l2))
print("max =",d[mx])
print("min =",d[mn])
10. s1=input("Enter elements separated by ,(comma) for keys: ")
s2=input("Enter elements separated by ,(comma) for values: ")
l1=s1.split(",")
l2=s2.split(",")
d={}
d=dict(zip(l1,l2))
n=input("Enter key to replace existing value: ")
if n in l1:
m=input("Enter value for key: ")
d[n]=m
d=sorted(d.items())
print("Sorted dictionary after updation:",d)
else:
print("Entered key does not exist in the dictionary")

Lesson 40:

1. s1=input("Enter elements separated by ,(comma) for keys: ")


s2=input("Enter elements separated by ,(comma) for values: ")
l1=s1.split(",")
l2=s2.split(",")
d={}
d=dict(zip(l1,l2))
print("all(dict1) =",all(d))
print("any(dict1) =",any(d))
print("len(dict1) =",len(d))
print("sorted(dict1) =",sorted(d))
print("The Key, value of dictionary as per sorted list of keys: ")
d=sorted(d.items())
for key,value in d:
print(key,":",value)
2. s1=input("Enter elements separated by ,(comma) for keys: ")
s2=input("Enter elements separated by ,(comma) for values: ")
l1=s1.split(",")
l2=s2.split(",")
d={}
d=dict(zip(l1,l2))
d=sorted(d.items())
print("Dictionary before exchange:",d)
d=dict(zip(l2,l1))
d=sorted(d.items())
print("Dictionary after exchange:",d)
3. troupe = {('Cleese', 'John') : [1, 2, 3],
('Chapman', 'Graham') : [4, 5, 6],
('Idle', 'Eric') : [7, 8, 9],
('Jones', 'Terry') : [10, 11, 12],
('Gilliam', 'Terry') : [13, 14, 15, 16, 17, 18],
('Palin', 'Michael') : [19, 20]}

print("Graham Chapman [4, 5, 6]")


print("John Cleese [1, 2, 3]")
print("Terry Gilliam [13, 14, 15, 16, 17, 18]")
print("Eric Idle [7, 8, 9]")
print("Terry Jones [10, 11, 12]")
print("Michael Palin [19, 20]")
4. s1a=input("Enter integer elements separated by ,(comma) for keys of dict1: ")
l1a=s1a.split(",")
for i in range(len(l1a)):
l1a[i]=int(l1a[i])
s1b=input("Enter integer elements separated by ,(comma) for values of dict1: ")
l1b=s1b.split(",")
for i in range(len(l1b)):
l1b[i]=int(l1b[i])
s2a=input("Enter integer elements separated by ,(comma) for keys of dict2: ")
l2a=s2a.split(",")
for i in range(len(l2a)):
l2a[i]=int(l2a[i])
s2b=input("Enter integer elements separated by ,(comma) for values of dict2: ")
l2b=s2b.split(",")
for i in range(len(l2b)):
l2b[i]=int(l2b[i])
d1=dict(zip(l1a,l1b))
d2=dict(zip(l2a,l2b))
l3a=[]
l3b=[]
d1c=d1
d2c=d2
for i in d1c.keys():
if i in d2c.keys():
l3a.append(i)
l3b.append(d1[i]+d2[i])
d3=dict(zip(l3a,l3b))
for i in d3.keys():
del d1[i]
del d2[i]
d4={**d1, **d2, **d3}
d4=sorted(d4.items())
print(d4)
5. s=input("Enter your sequence: ")
l=s.split(",")
for i in range(len(l)):
l[i]=int(l[i])
l1=[]
l2=[]
c=0
for i in range(len(l)):
for j in range(len(l)):
if(l[i]==l[j]):
c=c+1
l1.append(l[i])
l2.append(c)
c=0
d={}
d=dict(zip(l1,l2))
d=sorted(d.items())
print("Sorted dictionary",d)
6. s1a=input("Enter elements separated by ,(comma) for first dictionary keys: ")
s1b=input("Enter elements separated by ,(comma) for first dictionary values: ")
s2a=input("Enter elements separated by ,(comma) for second dictionary keys: ")
s2b=input("Enter elements separated by ,(comma) for second dictionary values: ")
l1a=s1a.split(",")
l2a=s2a.split(",")
n=input("Please enter a Key: ")
if n in l1a:
if n in l2a:
print("key present in both dictionaries")
else:
print("key present in first dictionary")
elif n in l2a:
print("key present in second dictionary")
else:
print("key is not present in both the dictionaries")
7. s1=input("Enter elements separated by ,(comma) for keys: ")
s2=input("Enter elements separated by ,(comma) for values: ")
l1=s1.split(",")
l2=s2.split(",")
d={}
d=dict(zip(l1,l2))
d=sorted(d.items())
print("Dictionary with key order")
for key,value in d:
print(key,value)
d=dict(zip(l2,l1))
d=sorted(d.items())
print("Dictionary with value order")
for key,value in d:
print(key,value)
8. s1a=input("Enter elements separated by ,(comma) for first dictionary keys: ")
s1b=input("Enter elements separated by ,(comma) for first dictionary values: ")
s2a=input("Enter elements separated by ,(comma) for second dictionary keys: ")
s2b=input("Enter elements separated by ,(comma) for second dictionary values: ")
l1a=s1a.split(",")
for i in range(len(l1a)):
l1a[i]=int(l1a[i])
l1b=s1b.split(",")
for i in range(len(l1b)):
l1b[i]=int(l1b[i])
l2a=s2a.split(",")
for i in range(len(l2a)):
l2a[i]=int(l2a[i])
l2b=s2b.split(",")
for i in range(len(l2b)):
l2b[i]=int(l2b[i])
d1=dict(zip(l1a,l1b))
d2=dict(zip(l2a,l2b))
l3a=[]
l3b=[]
for i in d1.keys():
if i in d2.keys():
l3a.append(i)
l3b.append(d1[i]+d2[i])
d3=dict(zip(l3a,l3b))
for i in d3.keys():
del d1[i]
del d2[i]
d4={**d1, **d2, **d3}
d4=sorted(d4.items())
print("Concatenation of two sorted dictionaries:",d4)
9. s1a=input("Enter integer elements separated by ,(comma) for first dictionary keys: ")
s1b=input("Enter integer elements separated by ,(comma) for first dictionary values: ")
s2a=input("Enter integer elements separated by ,(comma) for second dictionary keys: ")
s2b=input("Enter integer elements separated by ,(comma) for second dictionary values: ")
l1a=s1a.split(",")
for i in range(len(l1a)):
l1a[i]=int(l1a[i])
l1b=s1b.split(",")
for i in range(len(l1b)):
l1b[i]=int(l1b[i])
d1=dict(zip(l1a,l1b))
l2a=s2a.split(",")
for i in range(len(l2a)):
l2a[i]=int(l2a[i])
l2b=s2b.split(",")
for i in range(len(l2b)):
l2b[i]=int(l2b[i])
d2=dict(zip(l2a,l2b))
l3a=[]
l3b=[]
for i in d1.keys():
if i in d2.keys():
l3a.append(i)
l3b.append(2*d1[i])
d3=dict(zip(l3a,l3b))
d3=sorted(d3.items())
print("Common keys from two dictionaries:",d3)

Lesson 41:

1. s1a=input("Enter elements separated by ,(comma) for first dictionary keys: ")


s1b=input("Enter elements separated by ,(comma) for first dictionary values: ")
s2a=input("Enter elements separated by ,(comma) for second dictionary keys: ")
s2b=input("Enter elements separated by ,(comma) for second dictionary values: ")
l1a=s1a.split(",")
l1b=s1b.split(",")
l2a=s2a.split(",")
l2b=s2b.split(",")
d1=dict(zip(l1a,l1b))
d1s=sorted(d1.items())
print("Sorted dictionary",d1s)
print("Copy of sorted dictionary",d1s)
l1as=sorted(l1a)
print("Sorted Keys of dictionary",l1as)
l1bs=sorted(l1b)
print("Sorted Values of dictionary",l1bs)
d2=dict(zip(l2a,l2b))
d3={**d1, **d2}
d3=sorted(d3.items())
print("Sorted dictionary after updation",d3)
2. dct = {'1':'apple', '2':'orange', '3':'mango', '4':'banana'}
print("dct_keys = dct.keys()")
dct_keys = dct.keys()
print("dct_values = dct.values()")
dct_values = dct.values()
print("dct_keys_list = list(dct_keys)")
dct_keys_list = list(dct_keys)
print("dct_values_list = list(dct_values)")
dct_values_list = list(dct_values)
print("dct_keys_list =", sorted(dct_keys_list))
print("dct_values_list =", sorted(dct_values_list))
print("Combining both the keys and values list using zip");
print("zip(dct_keys_list, dct_values_list)")
zip_result = zip(dct_keys_list, dct_values_list)
print("Creating a list out of the zip result using list function")
zip_result_list = list(zip_result)
print("zip_result_list =", sorted(zip_result_list))
print("Finally creating the dictionary from the zip result list")
dict2 = dict(zip_result_list)
print("dict2 =", sorted(dict2.items()))
3. s1=input("Enter elements separated by ,(comma) for keys: ")
s2=input("Enter elements separated by ,(comma) for values: ")
l1=s1.split(",")
l2=s2.split(",")
d=dict(zip(l1,l2))
print("Elements of a dictionary",sorted(d.items()))
print("Sorted keys of dictionary",sorted(l1))
print("Sorted values of dictionary",sorted(l2))

Lesson 42 Unit 1:

1. Members in a set are immutable.


2. Set does not maintain the order of insertion
3. s1=input("Enter elements separated by ,(comma): ")
l1=s1.split(",")
s=set(l1)
s=sorted(s)
print("Sorted set of elements:",s)

Lesson 42 Unit 2:

1. s1=input("Enter elements separated by ,(comma): ")


l1=s1.split(",")
n=input("Enter element into the set: ")
l1.append(n)
s=set(l1)
print("Sorted set after adding",n,"is",sorted(s))
s2=input("Enter list elements separated by ,(comma) to update a set: ")
l2=s2.split(",")
l3=l1+l2
ss=set(l3)
print("Sorted set after updating with",l2,"is",sorted(ss))
2. s1=input("Enter elements separated by ,(comma): ")
l1=s1.split(",")
s=set(l1)
n1=input("Enter element you want to discard from set using discard(): ")
if n1 in s:
s.discard(n1)
print("Sorted set after discarding",n1,":",sorted(s))
n2=input("Enter element you want to remove from set using remove(): ")
if n2 in s:
s.remove(n2)
print("Sorted set after removing",n2,":",sorted(s))
else:
print("entered element is not existed in set")
else:
print("entered element is not existed in set")
3. s1=input("Enter elements separated by ,(comma): ")
l1=s1.split(",")
s=set(l1)
s=sorted(s)
print("Sorted order of set:",s)
n=input("Enter an element to check whether it exist in set or not: ")
print("Is",n,"in set:",n in s)
4. 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)
sts1=sorted(st1)
sts2=sorted(st2)
sts3=sorted(st3)
print("Sorted of set1:",sts1)
print("Sorted of set2:",sts2)
print("Sorted of set3:",sts3)
r1=st1.union(st2)
print("Union of set1 and set2:",sorted(list(r1)))
r2=st1.union(st2).union(st3)
print("Union of set1 and set2 and set3:",sorted(list(r2)))
print("set1 | set2:",sorted(list(r1)))
print("set1 | set2| set3:",sorted(list(r2)))
5. s1=input("Enter elements separated by ,(comma) for set1: ")
s2=input("Enter elements separated by ,(comma) for set2: ")
l1=s1.split(",")
l2=s2.split(",")
st1=set(l1)
st2=set(l2)
print("Sorted of set1:",sorted(st1))
print("Sorted of set2:",sorted(st2))
r=st1.intersection(st2)
print("Intersection of set1 and set2 in sorted order:",sorted(r))
r=st1&st2
print("Sorted set after (set1 & set2):",sorted(r))
st1 &= st2
print("Sorted set1 after (set1 &= set2):",sorted(st1))
print("Sorted set2 after (set1 &= set2):",sorted(st2))
6. s1=input("Enter elements separated by ,(comma) for set1: ")
s2=input("Enter elements separated by ,(comma) for set2: ")
l1=s1.split(",")
l2=s2.split(",")
st1=set(l1)
st2=set(l2)
print("Sorted set1:",sorted(st1))
print("Sorted set2:",sorted(st2))
r=st1.difference(st2)
print("Difference of set1 and set2 using difference():",sorted(r))
print("Difference of set1 and set2 using difference_update():",sorted(r))
r=st1-st2
print("Difference of set1 and set2 using (set1 - set2):",sorted(r))
st1-=st2
print("Difference of set1 and set2 using (set1 -= set2):",sorted(st1))
7. s1=input("Enter elements separated by ,(comma) for set1: ")
s2=input("Enter elements separated by ,(comma) for set2: ")
l1=s1.split(",")
l2=s2.split(",")
st1=set(l1)
st2=set(l2)
r=st1.symmetric_difference(st2)
print("Symmetric_difference of set1 and set2:",sorted(r))
print("set1 ^ set2:",sorted(r))
print("Sorted order of set1 after symmetric_difference_update:",sorted(r))
print("Sorted order of set2 after symmetric_difference_update:",sorted(l2))
s11=input("Enter elements separated by ,(comma) for set3: ")
s22=input("Enter elements separated by ,(comma) for set4: ")
l11=s11.split(",")
l22=s22.split(",")
st3=set(l11)
st4=set(l22)
st3 ^= st4
print("Sorted order of set3 after (set3 ^= set4):",sorted(st3))
print("Sorted order of set4 after (set3 ^= set4):",sorted(l22))

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:

1. s=input("Enter a string: ")


l=[]
for i in range(len(s)):
l.append(s[i])
print(l)
2. l=[]
for i in range(51):
if(i%2==0):
if(i%3==0):
l.append(i)
print(l)
3. matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
trans=[]
for i in range(len(matrix)+1):
trans.append([])
for j in range(len(matrix[0])-1):
trans[i].append(matrix[j][i])
# write your code here
print("Original matrix:")
print(matrix)
print("Matrix Transposition using Nested while:")
print(trans)
print("Matrix Transposition using Nested for:")
print(trans)
print("Matrix Transposition single list comprehension:")
print(trans)
print("Matrix Transposition double list comprehension:")
print(trans)
4. s=input("Enter numbers which are space separated: ")
l=s.split(" ")
for i in range(len(l)):
l[i]=int(l[i])
print("The contents of list are:",l)

Lesson 45:

1. l=int(input("Enter starting range: "))


u=int(input("Enter ending range: "))
my_set = {i ** 2 if i % 2 == 0 else i ** 3 for i in range(l,u)}
print(sorted(my_set))
2. t=[]
for z in range(5,31):
z2=z*z
x=x2=1
y=z-1
y2=y*y
while(x<y):
x2_y2=x2+y2
if x2_y2==z2:
e=[]
e.append(z)
e.append(y)
e.append(x)
e=tuple(e)
t.append(e)
del e
x+=1
x2=x*x
y-=1
y2=y*y
elif x2_y2<z2:
x+=1
x2=x*x
else:
y-=1
y2=y*y
temp=t[6]
t[6]=t[7]
t[7]=temp
print(t)

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:

1. def simplecalc(a, b = 100):


# write your code here
print("Addition result",a+b)
print("Subtraction result",a-b)
print("Multiplication result",a*b)
num1=int(input("Please enter some value for num1: "))
num2=int(input("Please enter some value for num2: "))
simplecalc(a = num1)
simplecalc(b = num2, a = num1)
2. def tax(s,p=20):
t=s*(p/100)
print(t)
a=int(input("Please enter your annual salary: "))
b=float(input("Please enter the tax percentage: "))
tax(a)
tax(a,b)
3. Function arguments can have default values in Python.
Any number of arguments in a function can have a default values.
non-default arguments cannot follow default arguments.
4. def fun1(name='Padma',age=12):
print(name,"is",age,"years old.")
fun1('Aruna',16)
fun1('Karuna',16)
fun1(age=16)
fun1(name='Karuna')
fun1()

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:

1. Anonymous functions are also called lambda functions.


Lambda functions can be used anywhere we need a regular function objects.
The expression is evaluated first and a value is returned.
2. tax = lambda salary:salary*20/100 # write the expression here
salary = int(input("Please enter your salary: "))
print("Tax to be paid is", tax(salary))
3. af = lambda n:n*2
n=int(input("Please enter a value for a: "))
print(af(n))
4. def squares(x):
return x ** 2
list1 = [1, 2, 3, 4, 5]
#use the squares func inside map function print the result
print(list(map(squares, list1)))
#use the lambda func inside map function print the result
print(list(map(lambda x:x **2, list1)))
#use list comprehension to get equivalent behaviour as map and print the result
print([x**2 for x in list1])
5. a = [1, 2, 3, 5, 7, 9]
b = [2, 3, 6, 7, 9, 8]
# apply lambda function to the filter function and print the result
print(list(filter(lambda x : x in a, b)))
# print the result using list comprehension
print([x for x in a if x in b])

Lesson 51:

1. A fruitful function is a function, it returns a value when it is called.


A return statement consists of the return keyword followed by an expression.
Python returns immediately when it reaches a return statement .
2. def largestinthree(a, b, c):
if(a>b and a>c):
return a
elif(b>a and b>c):
return b
else:
return c
# write your code here to find the largest number in a, b and c
num1 = int(input("Please enter a value for num1: "))
num2 = int(input("Please enter a value for num2: "))
num3 = int(input("Please enter a value for num3: "))
result = largestinthree(num1, num2, num3)
print("Largest of the values entered is", result)
3. def largestintwo(a, b):
if(a>b):
return a
if(b>a):
return b
# write your code here
num1=int(input("Please enter a value for num1: "))
num2=int(input("Please enter a value for num2: "))
result = largestintwo(num1, num2)
print("Largest of the values entered is", result)
4. def computeGCD(x, y):
r=math.gcd(x,y)
return r
a=int(input("Enter x value: "))
b=int(input("Enter y value: "))
print(computeGCD(a,b))

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:

1. from datetime import date


def numofdays(date1, date2):
return (date2-date1).days
n1=int(input("Please enter your DOB in the format ddmmyyyy: "))
n2=int(input("Please enter today's date in the format ddmmyyyy: "))
y1=n1%10000
n1=n1//10000
m1=n1%100
n1=n1//100
d1=n1
y2=n2%10000
n2=n2//10000
m2=n2%100
n2=n2//100
d2=n2
date1=date(y1,m1,d1)
date2=date(y2,m2,d2)
print("No of days since your birthday =",numofdays(date1,date2))
2. def valley(l):
s=l.split(" ")
for i in range(len(s)):
s[i]=int(s[i])
a=s[0]
c=1
for j in range((len(s)//2)-1):
if(s[j]>s[j+1]):
c=c+1
if(c==(len(s)//2)):
for j in range((len(s)//2),len(s)-1):
if(s[j]<s[j+1]):
c=c+1
if(c==len(s)-1):
return True
else:
return False
n=input("Input Integers seperated by spaces: ")
print(valley(n))
3. def frequency (seq):
s=seq
s=sorted(s)
c=0
lt1=[]
lt2=[]
lt3=[]
ck=[]
for i in s:
for j in s:
if i==j:
c=c+1
ck.append(c)
c=0
mx=max(ck)
mn=min(ck)
c=0
for i in s:
for j in s:
if i==j:
c=c+1
if((i not in lt1) and (c==mn)):
lt1.append(i)
if((i not in lt2) and (c==mx)):
lt2.append(i)
c=0
lt3=[]
lt3.append(lt1)
lt3.append(lt2)
lt3.append(mn)
lt3.append(mx)
l3=tuple(lt3)
return l3
# write your code here
l1 = [int(x) for x in input("Please enter integers separated by spaces: ").split()]
print (frequency(l1))

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:

1. from Module_Imp3 import calculatearea,calculatediameter


s=int(input("Please enter value of side: "))
calculatediameter(s)
calculatearea(s,s)
2. from Module_Imp3 import pivalue, shapes
pivalue()
n=int(input("Please enter a number: "))
print(shapes[1:n])
3. import Module_Imp3 as mi
n=int(input("Please enter a value of side: "))
mi.calculatearea(n,n)
mi.calculatediameter(n)
4. import Module_Imp3 as mi
n=int(input("Please enter a value of side: "))
mi.calculatearea(n,n)
mi.calculatediameter(n)
mi.pivalue()
print(mi.shapes[1:2])
5. from Module_Imp3 import *
n=int(input("Please enter a value of side: "))
calculatearea(n,n)
pivalue()
print("['{}']".format(shapes[2]))

Lesson 58:

1. Packages can be thought as directories with some specific rules.


Each package should have a file called __init__.py
2. import Robots.Car, Robots.House # here modules are imported
Robots.Car.cleancar() # function cleancar is called form the Car modules
Robots.House.cleanhouse()
Robots.House.payrent()
3. from Robots import Car2 as rc
rc.cleancar()
rc.checkcar()
4. from Robots import House, Car
House.cleanhouse()
House.payrent()
Car.checkcar()
Car.cleancar()
5. from Robots import Car2 as cr
cr.checkcar()
cr.cleancar()

Lesson 59:

1. Each module gets it’s own global namespaces.


The builtin functions that can be used in any module are called __builtin__ and have their own
namespace.
The namespaces are isolated which means the names in one module can be used in another
module.
2. Namespaces in python are very helpful in organising the code in very large projects.
In Python, an identifier is used to name a variable to function and just about anything.
A namespace is a place that holds a bunch of names.
3. A scope refers to the specific area of a program where the variables of that namespace do not need
a prefix.
All modules have a global namespace on their own.
One function cannot access the names inside an other function.
4. A local scope, the list of all the names available in the current executing function.
A module level scope that is a list of all the global names of the current module.
5. name = "Ram"
greeting = "Good Morning"
# print dir
print(dir())
def func1():
greeting = "Good Afternoon"
# print dir
print(dir())
def func2():
greeting = "Good Evening"
print(dir())
# call the function func1
func1()
# call the function func2
func2()

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:

1. pip is the most preferred package installation program .


When we want to install some packages for a particular application only, we use virtual environment.
You can install a specific version of package with pip.

Lesson 61:

1. File are stored on external media


2. File extension tells the type of file
3. File path indicates the directory in which the file is located
In the string "c:\users\ravi\desktop\documents\profile.doc", doc is the extension
We can specify the file path relative to the current directory
When the file is in the current directory, the file path need not be specified
4. File name and file path

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:

1. Object-oriented programming was first introduced at MIT in 1950’s.


In 1990, James Gosling of Sun Micro Systems developed a simple version of C++ called Java .
2. A programming paradigm informs how problems are analysed and solved in a programming
language.
Large systems developed using procedural programming language can be difficult to maintain.
3. A class is a combination of data and its associated meaningful functions.
Object based programming implements information hiding and abstraction.
4. Objects are instances of classes.
A class is like the blueprint or design of which, instances are made.
A class contains both attributes and methods.
5. A class is a combination of data members and member functions.
An object is an instance of a class.
Data in an object captures the characteristics (or attributes) of that object.
Methods of an object captures the behaviour of the real world object.
6. A class is a combination of data and functions, which is nothing but implementation of
encapsulation.
An object is a run-time instance of a class.
7. Abstraction.
8. class Student:
pass
Stud_1 = Student()
Stud_2 = Student()
Stud_1.name = 'SriRam'
Stud_1.age = 25
Stud_1.graduate = 'MBA'
Stud_2.name = 'Lakshman'
Stud_2.age = 23
Stud_2.graduate = 'Engineer'
print("Stud_1.name:", Stud_1.name)
print("Stud_1.age:", Stud_1.age)
print("Stud_1.graduate:", Stud_1.graduate)
print("Stud_2.name:", Stud_2.name)
print("Stud_2.age:", Stud_2.age)
print("Stud_2.graduate:", Stud_2.graduate)
9. class Student:
pass
Stud_1 = Student()
Stud_1.name = 'SriRam'
Stud_1.age = 25
Stud_1.graduate = 'MBA'
print("Stud_1.name:" ,Stud_1.name)
print("Stud_1.age:", Stud_1.age)
print("Stud_1.graduate:", Stud_1.graduate)
10. class Student:
pass
Stud_1=Student()
Stud_2=Student()
'''Stud_1.name
Stud_1.age
Stud_1.graduate
Stud_2.name
Stud_2.age
Stud_2.graduate'''
# # write your code here
Stud_1.name=input("Enter name of the student1: ")
Stud_1.age=int(input("Enter age of the student1: "))
Stud_1.graduate=input("Enter degree of student1: ")
Stud_2.name=input("Enter name of the student2: ")
Stud_2.age=int(input("Enter age of the student2: "))
Stud_2.graduate=input("Enter degree of student2: ")
print("Stud_1.name:",Stud_1.name)
print("Stud_1.age:",Stud_1.age)
print("Stud_1.graduate:",Stud_1.graduate)
print("Stud_2.name:",Stud_2.name)
print("Stud_2.age:",Stud_2.age)
print("Stud_2.graduate:",Stud_2.graduate)
11. class Employee:
pass
Emp_1=Employee()
Emp_1.age=25
Emp_1.salary=25000
Emp_1.name=input("Please enter an employee name: ")
print("Emp_1.name:",Emp_1.name)
print("Emp_1.salary:",Emp_1.salary)
12. class Student:
pass
Stud_1=Student()
# # write your code here
Stud_1.name=input("Enter name of the student:")
Stud_1.age=int(input("Enter age of the student:"))
Stud_1.graduate=input("Enter degree of the student:")
print("Stud_1.name:",Stud_1.name)
print("Stud_1.age:",Stud_1.age)
print("Stud_1.graduate:",Stud_1.graduate)
13. class Employee:
pass
Emp_1=Employee()
Emp_1.name=input("Please enter an employee name: ")
Emp_1.salary=int(input("Enter salary of an employee: "))
print("Emp_1.name:",Emp_1.name)
print("Emp_1.salary:",Emp_1.salary)

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.

5. n1=int(input("Enter num1: "))


n2=int(input("Enter num2: "))
try:
d=n1/n2
print("Succesful Division, value of num1/num2 ",d)
except:
print("Exception occured")
6. tryagain=True
while tryagain:
try:
value=int(input("Enter a whole number: "))
except ValueError:
print("You must enter a whole number!")
try:
again=input("Try again (y/n)? ")
except:
print("OK, see you next time!")
tryagain=False
else:
if(str.upper(again)=="N"):
tryagain=False
except KeyboardInterrupt:
print("You pressed Ctrl+C!")
print("See you next time!")
tryagain=False
else:
print(value)
tryagain=True

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:

1. Python supports a lot of in-built exceptions.


All user defined exceptions have to be derived from the Exception class.
Python built-in exceptions extend from the BaseException/Exception class.
2. class OurException(Exception):
# define constructor
def __init__(self,message):
self.message=message
class UsingUserException:
try:
#write code in try block
a=int(input("Enter a value for a: "))
b=int(input("Enter a value for b: "))
if b==0:
raise OurException("b should be greater than 0:")
d=a/b
print("Division operation successful with result value",d)
except OurException as err:
print("Raised an user defined Exception:", err.message,b)
3. class OurException(Exception):
def __init__(self,message):
self.message=message
class usinguserexception:
try:
a=int(input("Enter a value: "))
b=int(input("Enter a value: "))
if b==0:
raise OurException("b should be greater than 0:")
d=a/b
print("Division operation successful with result value",d)
except OurException as err:
print("Raised an user defined Exception:",err.message,b)

Lesson 71 Unit 1:

1. The math module provides access to the mathematical functions defined by C.


Most of the functions of math module return float values.
The cmath module has functions of the same name as math module, but they work on complex
numbers.
2. import math
x = 10
print("Factorial of",x,math.factorial(x))
# find factorial of x and print the result
print("Floor of ",x,math.floor(x))
# find math.floor and print the result
print("Sum of",x,"three times",float(3*x))
# add x three times and print the result
a=5
b=6
# find GCD of a and b and print the result
print("GCD of {} and {} {}".format(a,b,math.gcd(a,b)))
# find math.isfinite and print the result
print("Is {} a finite number: {}".format(x,math.isfinite(x)))
# find math.isinf and print the result
print("Is {} a infinite number: {}".format(x,math.isinf(x)))
3. import math
n=int(input("Please enter an integer value: "))
print("Factorial of {}: {}".format(n,math.factorial(n)))
print("Floor of {}: {}".format(n,math.floor(n)))
print("Sum of {} three times {}".format(n,float(3*n)))
a=int(input("Please enter an integer value: "))
b=int(input("Please enter an integer value: "))
print("GCD of {} and {}: {}".format(a,b,math.gcd(a,b)))
4. import math
n=int(input("Enter an integer value: "))
# write your code here
print("exponent of ({}): {}".format(n,math.exp(n)))
print("math.log1p({}): {}".format(n,math.log1p(n)))
print("math.log2({}): {}".format(n,math.log2(n)))
print("math.log10({}): {}".format(n,math.log10(n)))
print("Square root of ({}): {}".format(n,math.sqrt(n)))
a=int(input("Please enter an integer value: "))
b=int(input("Please enter an integer value: "))
print("Power of {} to {}: {}".format(a,b,math.pow(a,b)))
5. import math as m
x=int(input("Please enter an integer value: "))
print("exponent value: {}".format(m.exp(x)))
print("math.log2({}): {}".format(x,m.log2(x)))
print("math.log10({}): {}".format(x,m.log10(x)))
print("Square root of {}: {}".format(x,m.sqrt(x)))
a=int(input("Please enter an integer value: "))
b=int(input("Please enter an integer value: "))
print("Power of {} to {}: {}".format(a,b,m.pow(a,b)))
6. import math
xinrad = int(input("Please enter an integer value: "))
x = math.pi / xinrad
print("Arc cosine of %d:" %xinrad, math.acos(x))
# print the arc sine value
print("Arc sine of %d:"%xinrad, math.asin(x))
# print the arc tan value
print("Arc tangent of %d:"%xinrad,math.atan(x))
print("Cosine of %d:" %xinrad, math.cos(x))
# Retrun the sine of x
print("Sine of %d:"%xinrad,math.sin(x))
# Retrun the tan of x
print("Tangent of %d:"%xinrad,math.tan(x))
a = int(input("Please enter an integer value: "))
b = int(input("Please enter an integer value: "))
print("Value of atan2({}, {}): {}".format(b,a,math.atan2(b,a)))
print("Value of hypot({}, {}): {}".format(a,b,math.hypot(a,b)))
7. import math
# take the integer input from the user
x=int(input("Please enter an integer value: "))
print("Inverse Hyperbolic cosine of %d:" %x, math.acosh(x))
print("Inverse Hyperbolic sine of {}: {}".format(x,math.asinh(x)))
# follow the above print statement while writing
print("HyperbolicCosine of {}: {}".format(x,math.cosh(x)))
print("HyperbolicSine of {}: {}".format(x,math.sinh(x)))
print("Hyperbolic Tangent of {}: {}".format(x,math.tanh(x)))
8. import math
x=int(input("Please enter a value: "))
print("Converting an angle",x,"to degrees:",math.degrees(x))
print("Converting an angle",x,"to radians:",math.radians(x))

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

3. [ ] These are used for specifying a character class.

* is used as a repeated qualifier for 0 or more times.

4. Pattern objects have several methods and attributes like match(), search() etc.

The match() and search() return a None if no match is found.

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")

8. Compilation flags lets a user modify a few parts of regular expressions.


IGNORECASE, I is used for case-insensitive matches.
9. import re
mystring = "The alternate email address is victory@ct.com"
match = re.search('(\w+)@(\w+).(\w+)', mystring)
if match:
# find full match text and print the result
print("Full match:",match.group())
# find the match text corresponding to the 1st left parenthesis and print
print("Group 1:",match.group(1))
# find the match text corresponding to the 2nd left parenthesis and print
print("Group 2:",match.group(2))
# find the match text corresponding to the 3rd left parenthesis and print
print("Group 3:",match.group(3))

10. s=input("Please enter 4 words separated by commas: ")


c=1
for i in s:
if i==',':
c=c+1
if c==4:
l=s.split(",")
print("Full match: {},{},{},{}".format(l[0],l[1],l[2],l[3]))
print("Group 1:",l[0])
print("Group 2:",l[1])
print("Group 3:",l[2])
print("Group 4:",l[3])
else:
print("Sorry! You have not entered 4 words separated by commas")

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:

1. Turtle module is a part of standard library.


2. turtle.setx(x) Sets the Turtle to x coordinate.
3. tilt() Returns the tilt angle
4.
5.
6. import turtle
screen = turtle.Screen()
turtle.penup()
turtle.write("Press the Up/Down or a to change background color ", font =
('Arial', 10, 'bold'))
def up():
screen.bgcolor('blue')
def down():
screen.bgcolor('green')
screen.onkey(up, "Up")
screen.onkeypress(down, "Down")
screen.listen()
turtle.done
Lesson 72:

1. x1=int(input("Enter the x coordinate of first point: "))


y1=int(input("Enter the y coordinate of first point: "))
x2=int(input("Enter the x coordinate of second point: "))
y2=int(input("Enter the y coordinate of second point: "))
x=x2-x1
y=y2-y1
x=x**2
y=y**2
d=x+y
d=d**(1/2)
print("Distance is:",d)
2. n=int(input("Enter an integer: "))
if n%2==0:
print("Given number %d is even"%n)
else:
print("Given number %d is odd"%n)
3. n=int(input("Enter n value: "))
for i in range(1,11,1):
print("{}/{} = {}".format(n,i,n/i))
4. n=int(input("Enter size of list: "))
l=[]
s=0
for i in range(n):
e=int(input("Enter value: "))
l.append(e)
s=s+e
print("The sum of the given sequence {} is {}".format(l,s))
print("good bye..!")
5. n=int(input("Enter an integer: "))
for i in range(n,0,-1):
print(i)
print("good bye..!")
6. n=int(input("Enter an integer value: "))
fn=[]
a=-1
b=1
e=1
while(e<=n):
c=a+b
fn.append(c)
a=b
b=c
e=e+1
print("Fibonacci numbers:",fn)
flag=0
pn=[]
s=0
for i in fn:
if(i!=0 and i!=1):
for j in range(2,i):
if i%j==0:
flag=1
if flag==0:
pn.append(i)
s=s+i
flag=0
print("The prime numbers of fibonacci series:",pn)
print("The sum of the prime numbers:",s)
7. n=int(input("Enter an integer: "))
c=s=0
f=[]
a=-1
b=1
while(c<=n):
c=a+b
if c<=n:
f.append(c)
if c%2==0:
s=s+c
a=b
b=c
print("The sum of even numbers of fibonacci sequence {} is: {}".format(f,s))
8. s=input("Enter the string: ")
print("{'%s': %d}"%(s,len(s)))
9. print("Enter strings contained name and dob with : seperated")
s=input()
l=s.split(" ")
s=":".join(s.split(" "))
ll=s.split(":")
print("The list:",l)
print("The list with join: {}---{}---{}".format(l[0],l[1],l[2]))
print("The sorted dictionary: [('{}', '{}'), ('{}', '{}'), ('{}',
'{}')]".format(ll[4],ll[5],ll[2],ll[3],ll[0],ll[1]))
10. ni=int(input("Enter size of int-list: "))
ns=int(input("Enter size of string-list: "))
li=[]
ls=[]
for i in range(ni):
n=int(input("Enter int for int-list: "))
li.append(n)
for i in range(ns):
n=input("Enter string for string-list: ")
ls.append(n)
d=dict(zip(li,ls))
print(d)
11. f=input("Enter the filename: ")
s=input("Enter the character to be searched: ")
file=open(f,'r')
text=file.read()
print("{} appears {} times in file".format(s,text.count(s)))
print("The type of file:",type(file))
12. fn=input("Enter file name: ")
file=open(fn,'r')
lst=file.readlines()
lst2=lst[::-1]
for i in lst2:
i=i.replace("\n","")
print(i)
13. fn=input("Enter file name: ")
file=open(fn,'r')
l=0
w=0
c=0
for i in file:
i=i.strip()
words=i.split()
l+=1
w+=len(words)
c+=len(i)
print("Lines =",l)
print("words =",w)
print("Characters =",c+(l-1))
14. import math
def ballcollied():
s1=input("Enter x, y, r of ball-1: ")
x1,y1,r1=s1.split(" ")
x1=int(x1)
y1=int(y1)
r1=int(r1)
s2=input("Enter x, y, r of ball-2: ")
x2,y2,r2=s2.split(" ")
x2=int(x2)
y2=int(y2)
r2=int(r2)
d=math.sqrt((x2-x1)**2+(y2-y1)**2)
s=r1+r2
if d<=s:
print("True - Balls are colliding")
else:
print("False - Balls are not colliding")
ballcollied()
15. import statistics as st
n=int(input("Enter size of list: "))
l=[]
for i in range(n):
e=int(input("Enter integer value: "))
l.append(e)
print("Mean of list:",st.mean(l))
print("Median of list:",st.median(l))
print("Mode of list:",st.mode(l))
print("Standard deviation of list:",st.stdev(l))
print("Variance of list:",st.variance(l))
16. def neralyequal():
s1=input("Please enter a string: ")
s2=input("Please enter another string: ")
l1=len(s1)
l2=len(s2)
if(l1>l2 and (l1-l2)==1):
print("Some Character is extra in string1")
r=s1[1]
s1=s1.replace(r,"")
print("Strings after removal of the extra character:",s1,s2)
print("False")
elif(l2>l1 and (l2-l1)==1):
print("Some Character is extra in string1")
r=s2[1]
s2=s2.replace(r,"")
print("Strings after removal of the extra character:",s2,s1)
print("False")
elif(l1==l2):
print("Strings are of equal Length")
print("True")
else:
print("Lengths differ by more than 1")
print("False")
neralyequal()
17. n=int(input("Enter size of list: "))
ol=[]
dl=[]
c=0
for i in range(n):
e=int(input("Enter value: "))
ol.append(e)
for i in ol:
for j in ol:
if(i==j):
c=c+1
if c>1:
if i not in dl:
dl.append(i)
c=0
print("Original List =",ol)
print("Duplicates =",sorted(dl))
18. n=int(input("Enter size of list: "))
ol=[]
ul=[]
c=0
for i in range(n):
e=int(input("Enter value: "))
ol.append(e)
for i in ol:
'''for j in ol:
if i==j:
c=c+1
if c==1:'''
if i not in ul:
ul.append(i)
#c=0
print("Original List =",ol)
print("Unique elements =",ul)
19. n=int(input("Enter size of list: "))
ol=[]
cp=[]
for i in range(n):
e=int(input("Enter value: "))
ol.append(e)
cp.append(ol[0])
e=ol[0]
for i in range(1,len(ol)):
e=e*ol[i]
cp.append(e)
print("Original List =",ol)
print("Cumulative Product List =",cp)
20. n=int(input("Enter size of list: "))
ol=[]
for i in range(n):
e=int(input("Enter value: "))
ol.append(e)
print("Original List =",ol)
print("Reversed List =",ol[::-1])
21. import math
a=int(input("Enter an integer value: "))
b=int(input("Enter an integer value: "))
print("GCD of {} and {} is {}".format(a,b,math.gcd(a,b)))
print("LCM of {} and {} is {}".format(a,b,abs(a*b)//math.gcd(a,b)))
22. R=int(input("Number of rows, m = "))
C=int(input("Number of columns, n = "))
matrix=[]
for i in range(R):
a=[]
for j in range(C):
print("Entry in row: {} column: {}".format(i+1,j+1))
a.append(int(input()))
matrix.append(a)
print(matrix)
23. R1=int(input("Number of rows for matrix - A, m = "))
C1=int(input("Number of columns for matrix - A, n = "))
R2=int(input("Number of rows for matrix - B, p = "))
C2=int(input("Number of columns for matrix - B, q = "))
matrix1=[]
matrix2=[]
if R1==R2 and C1==C2:
print("Enter values for matrix - A")
for i in range(R1):
a=[]
for j in range(C1):
print("Entry in row: {} column: {}".format(i+1,j+1))
a.append(int(input()))
matrix1.append(a)
print("Enter values for matrix - B")
for i in range(R2):
a=[]
for j in range(C2):
print("Entry in row: {} column: {}".format(i+1,j+1))
a.append(int(input()))
matrix2.append(a)
print("Matrix a =",matrix1)
print("Matrix b =",matrix2)
matrixsum=[]
for i in range(len(matrix1)):
matrixsum.append([])
for j in range(len(matrix1[0])):
matrixsum[i].append(matrix1[i][j]+matrix2[i][j])
print("Addition of two matrices =",matrixsum)
else:
print("Addition is not possible")
24. def matmult(A, B,r1,c1,r2,c2):
if c1==r2:
if(c1==c2):
la=len(A)
lao=len(A[0])
lb=c1
else:
la=len(A)
lao=len(B[0])
lb=r2
result=[]
r=0
for i in range(la):
tr=[]
for j in range(lao):
for k in range(lb):
s=(A[i][k]*B[k][j])
r=r+s
tr.append(r)
r=0
result.append(tr)
del tr
print("Matrix - A * Matrix- B =",result)
else:
print("Cannot multiply the two matrices. Incorrect dimensions.")
print("Matrix - A * Matrix- B = None")
""" End of Function: matmult """
def readmatrix(name = ''):
print("Enter values for",name)
R=int(input("Number of rows, m = "))
C=int(input("Number of columns, n = "))
mat=[]
for i in range(R):
a=[]
for j in range(C):
print("Entry in row: {} column: {}".format(i+1,j+1))
a.append(int(input()))
mat.append(a)
return mat,R,C
""" End of Function: matmult """
matrixa,ra,ca = readmatrix('matrix - A')
matrixb,rb,cb = readmatrix('matrix - B')
print("Matrix - A =", matrixa)
print("Matrix - B =", matrixb)
matmult(matrixa, matrixb,ra,ca,rb,cb)

You might also like