#2clients
Explore tagged Tumblr posts
talkingtea · 5 years ago
Note
About G's manager: nothing he's had G do since 2015 has led 2grow G's career. True G should share blame 4turning his career into promo 4a rando PT but consider he discovered G at 20 + estranged from his dad & u can see emotional attachment that has blinded G. All he's done 4G is stupid defense like engagement news to mask loss of movie role but he's done gr8 offense 4his other 2clients: LA & her bro i.e. house buy, wedding, using G & celeb friends etc... A clear-headed person would seek new mgmt
Sadly it seems that Grant feels indebted to his manager because he gave him a chance before anyone else did. Tbh, we get it, but if Grant isn’t careful a feeling of obligation will have his whole damn career derailed.
We will never forget how on Robert’s bday (Grant’s manager) he spent the day posting photos of his clients who he spent time with him for his bday or sent him a cake, etc. On each picture he mentioned who the person was, talked about their current project and then thanked them.
With Grant he posted a picture of them with LA and then promoted them as a couple. He didn’t mention a word about Grant’s work and Grant was literally the only client he did that with.. What’s crazy is that Grant later posted a photo of just him and his manager which means Robert probably had that picture too but he chose to post the one that included LA instead.
29 notes · View notes
cakesbynea · 7 years ago
Photo
Tumblr media
#aboutlastnight #bakersgonnabake #steelers #cowboys #blackandyellow #blueandsilver #2clients #idoparties #idocatering #idocandybuffetts #idocakes #memphisfoodie #memphistn #memphiscakes #cakesofinstagram #zebra #bookme #nflcakes #nfl (at Cakes & Catering by Nea)
0 notes
mycelebrityandi · 2 years ago
Photo
Tumblr media
Nigerian man repeatedly accused of hunting gay men has been arrested for killing a man he claimed asked him for a homosexual relationship. Prior to being nabbed, a Pro-LGBTQ platform had shared a Facebook post about the suspect identified as #emmanuelnwonah warning gay people in Nigeria to be careful. It was alleged that he operates in Ajah with some group of guys. The post shared on May 14 read; “COME AND SEE OOOOOOOOOO Can you see how KITO Manuel popularly known as Khalifa on Instagram is dealing with his 2clients in a 3Some? Wilson Justice sorry o! They were lucky they invited him over, This Manuel has a gun for REAL , he operates in Ajah with some group of straight guys who are know to be a deadly cultists in that Area. If ur friend eventually fall into their trap, they will use his phone to invite you to a party venue,they will point gun at ur friend and ask him to feel relax and invite you for a group sex or party. Do you know how many tbs they have poisoned ? Some are even deaf via their Hot slap.....Noble is a witness SCHOOL U NO GREE GO, LEARN WORK YOU SAY LAI LAI GOD FORBID, OK... ASHAWO NKOR? U STILL USE ONE LEFT YANSH HOLLAM ,SEY NOOOOOOOOOOO YOUR CUSTOMERS NOR GO DRINK WATER DROP CUP IN PEACE . WHY TAKING ADVANTAGE OF THE SAME LAW THAT PROHIBIT THE LGBT FREEDOM. SAME LAW THAT IS DEALING WITH YOU. YOU ARE NOT DIFFERENT FROM THE SARS KHALIFA ! KHALIFA! GO AND ASK DESMOND GOLD,THE HONORABLE VICE CHANCELLOR OF THE KITORIST, HES MORE DANGEROUS THAN YOU, I FLUSHED HIM OUT OF THE COMMUNITY..... I WILL FINISH YOU TO THE POINT THAT YOU WONT SEE WHO WILL GIVE YOU 1K FOR ORDINARY TRANSPORT. It will show and then u can watch all the shocking and other juicy black D***k and shobo.” Few months after the post in May went viral, Emmanuel has now been arrested for allegedly killing one David. In one of the videos shared online, he was seen apologizing to members of the LGBTQ community. Before being taken away for murder, a security operative was heard in one of the videos saying he shouldn't have taken laws into his hands. The security operative said he should have reported his claim for it to be investigated. #lgbt #lagos #nigeria #mycelebrityandi https://www.instagram.com/p/CiiGhMroTzd/?igshid=NGJjMDIxMWI=
0 notes
cristileigh · 7 years ago
Video
Shaking them. Beautiful follicles!!! But sweet goodbye because my beautiful client is going to move to Tennessee in marry the man of her dreams I wish you the best of luck & if you ever in Cape Coral I'm always here for you💋❤️✌️🐥🌈 #hairvideos #capecoralcolorist #milkshakenorthamerica #capecoralfl #irma 2client #capecoral #hairvideos #healthylifestyle #healthychoices #lovemyclients #missyoualready 😿#forverlove #congratulations (at Cape Coral, Florida)
1 note · View note
monicaham · 5 years ago
Photo
Tumblr media
👑👔"EN JUNIO" 📸 APARTA YA!!!... Las PROMOCIONES y Precio Especial 2017 para Festejar para los Guapos de la casa,, a PAPÁ!!! y Los PapasitOs🧢!!! Por " DÍA DEL PADRE " Regalate una Sesión de Fotos🎩,, CASUAL/Fashion Individual: Sexy Boys/Daddy's #Retrato Amigos & #FAMILIA ,Pareja: Padre e Hijos,, #fitnessPhoto, #GymShoot, Big Daddy, PapiRusters, Big Papa, Sexy Boy,, PapitOs,, #FatherDay,, Consintiendo🤗! Change your profile picture for a picture taken by professional photographer Monica Ham and Look your best... Aprovecha!! TEMPORADA ESPECIAL #SweetDaddySession Se quedan los "Paquetes Promocionales de Mini Sesiones".. Si QUIERES REALIZAR SESIÓN EN JUNIO 2019,, LLAME YA📲 !!! 📷 Reserva tú espacio! Aun tengo horarios y fechas disponibles. El Mejor Regalo para toda una vida... Sesiones Con Backs/ Fondos Atemporales, Con Set Personalizados, Área de Chimenea ó Rincón del Jardin,, Ahora,Tú tambien Regalate un Retrato especial,, Desde $350 (contenidos, Locación en Casa/Studio, duración en flayer/publicidad). "SEGUIMOS CON PROMO DE ENTREGA DIGITAL E IMPRESO"... ó Algún otros de los Paquetes MÁS Completos,,Para Tú Sesión de Locación: Exteriores e Interiores de nuestra localidad Tam-Mad, En la Casa/Studio(Área de Chimenea con Variante de accesorios decorativos y Área del Rincón del Jardin) ó En tú propio hogar etc. Más tiempo de sesión, Con cambios de vestimenta, Con variantes de contenidos,, Con otros Descuento y Promociones. #SessionFriends #Parejas Paquete Especial de #Comuniones #Embarazados,, #PhotoShooting #Preg #PregnantPhotography #FamilySession #PhotoPET #NewbornPortrait #BDaySession/#ChildrensSmashCake Sesión de Cumpleaños de Adultos/ #AdultCakeSmash "Casuales SPLASH PhotoShoOting" Retrato & Video Social (SESIONES JUNIO 2019)...Aparta!! AHORA con MÁS CONTENIDO, Más FotOs, MÁS Descuentos & Regalo. "Paquete Especial de 1er.Comunión" desde $970. Pregunta por los otros paquetes más completos (PROMOCIÓN: Si traes 2Clientes que"Contraten"(de Igual ó Mayor precio) Retrato de Comunión a ellas tendran-10%+REGaLO,, El tú obtendras un -20% +REGaLOs "APARTANDO" en MAYO (Eventos & Sesiones de Mayo a Julio 2019) Ultimas Fechas!! #PORTRAIT OUTLET en #QuinceAños #BODA (en Fotografia & Diseño by Monica Ham) https://www.instagram.com/p/By-53ymHcAa/?igshid=1oyn3236ujrla
0 notes
moneyflipp-promo · 6 years ago
Photo
Tumblr media
Videos currently priced at $200 but if you refer us 2CLIENTS We shoot your visual for $100 #150filmz #mfm_media #ejfilmz #musickaddicts 🔌 (at Bronx, New York) https://www.instagram.com/p/Bu5b2golYtI-hZEhKqgM9RbGoRr1eCFF5ctjgc0/?utm_source=ig_tumblr_share&igshid=8ldaoxw4ypu9
0 notes
margdarsanme · 4 years ago
Text
NCERT Class 12 Computer Science Chapter 1 Review of Python
NCERT Class 12 Computer Science Python Solutions for Chapter 1 :: Review of Python
TOPIC-1
Python Basics
Very Short Answer Type Questions(1 mark)
Question 1.Name the Python Library modules which need to be imported to invoke the following functions:
load ()
pow () [CBSE Delhi 2016]
Answer:
pickle
math
Question 2.Name the modules to which the following func-tions belong:
Uniform ()
fabs () [CBSE SQP 2016]
Answer:
random ()
math ()
Question 3.Differentiate between the round() and floor() functions with the help of suitable example.[CBSE Comptt. 2016]Answer:The function round() is used to convert a fractional number into whole as the nearest next whereas the function floor() is used convert to the nearest lower whole number, e.g.,round (5.8) = 6, round (4.1) = 5 and floor (6.9) = 6, floor (5.01) = 5
Short Answer Type Questions (2 marks):
Question 1.Out of the following, find those identifiers, which cannot be used for naming Variables or functions in a Python program:Total * Tax, While, Class, Switch, 3rd Row, finally, Column 31, Total. [CBSE Outside Delhi-2016]Answer:Total * Tax, class, 3rd Row, finally
Question 2.Name the Python Library modules which need to be imported to invoke the follwing functions :
sqrt()
dump() (CBSE Outside Delhi-2016)
Answer:
math
pickle
Question 3.Out of the following, find the identifiers, which cannot be used for naming Variable or Functions in a Python program: [CBSE Delhi 2016]_Cost, Price*Qty, float, switch, Address one, Delete, Number12, doAnswer:Price *Qty, float, Address one, do
Question 4.Out of the following find those identifiers, which can not be used for naming Variable or Functions in a Python Program:Days * Rent, For, A_price, Grand Total, do, 2Clients, Participantl, My cityAnswer:Illegal variables or functions name are as below: Days * Rent, do, 2Clients, For and Grant Total Because of being either keyword or including space or operator or starting with integar.
Question 5.Name the function / method required for [CBSE SQP 2015]
Finding second occurrence of m in madam.
get the position of an item in the list.
Answer:
find
index
Question 6.Which string method is used to implement the following:
To count the number of characters in the string.
To change the first character of the string in capital letter.
To check whether given character is letter or a number.
To change lowercase to uppercase letter.
Change one character into another character. [CBSE TextBook]
Answer:
len(str)
str.capitalize()
ch.isalnum()
str.upper()
str.replace(old,new)
Question 7.What is the difference between input() and raw_input()?Answer:raw_input() takes the input as a string whereas input() basically looks at what the user enters, and automatically determines the correct type. We use the inputQ function when you are expecting an integer from the end-user, and raw_input when you are expecting a string.
Question 8.What are the two ways of output using print()?Answer:Ordinarily, each print statement produces one line of output. You can end the print statement with a trailing ’ to combine the results of multiple print statements into a single line.
Question 9.Why does the expression 2 + 3*4 result in the value 14 and not the value 24?Answer:Operator precedence rules* make the expression to be interpreted as 2 + (3*4) hence the result is 14.
Question 10.How many times will Python execute the code inside the following while loop? You should answer the question without using the interpreter! Justify your answers.
i = 0 while i < 0 and i > 2 : print “Hello ...” i = i+1
Answer:0 times.
Question 11.How many times will Python execute the code inside the following while loop?
i = 1 while i < 10000 and i > 0 and 1: print “ Hello ...” i = 2 * i
Answer:14.
Question 12.Convert the following for loop into while loop, for i in range (1,100):
if i % 4 == 2 : print i, “mod”, 4 , “= 2”
Answer:
i=1 while i < 100: if i % 4 == 2: print i, “mod”, 4 , “= 2” i = i +1
Question 13.Convert the following for loop into while loop.
for i in range(10): for j in range(i): print '$', print"
Answer:
i=0 while i < 10: j=0 while j < i: print '$’ print"
Question 14.Rewrite the following for loop into while loop: [CBSE Text Book]
for a in range(25,500,25): print a
Answer:
a=25 while a < 500: print a a = a + 25
Question 15.Rewrite the following for loop into while loop: [CBSE Text Book]
for a in range(90, 9, -9): print a
Answer:
a = 90 while a > 9: print a a = a-9
Question 16.Convert the following while loop into for loop:
i = 0 while i < 100: if i % 2 == 0: print i, “is even” else: print i, “is odd” i = i + 1
Answer:
for i in range(100): if i % 2 == 0: print i, “is even” else : print i, “is odd”
Question 17.Convert the following while loop into for loop
char = "" print “Press Tab Enter to stop ...” iteration = 0 while not char == “\t” and not iteration > 99: print “Continue?” char = raw_input() iteration+ = 1
Answer:
char = "" print “Press Tab Enter to stop ...” for iteration in range(99): if not char == ‘\t’: print “Continue?” char = raw_input()
Question 18.Rewrite the following while loop into for loop:
i = 10 while i<250: print i i = i+50
Answer:
for i in range(10, 250, 50): print i
Question 19.Rewrite the following while loop into for loop:
i=88 while(i>=8): print i i- = 8
Answer:
for i in range(88, 9, -8) print i
Question 20.Write for statement to print the series 10,20,30, ……., 300Answer:
for i in range(10, 301, 10): print i
Question 21.Write for statement to print the series 105,98,91,… .7Answer:
for i in range(105, 8, -7): print i
Question 22.Write the while loop to print the series: 5,10,15,…100Answer:
i=5 while i <= 100: print i i = i + 5
Question 23.How many times is the following loop executed? [CBSE Text Book]for a in range(100,10,-10):print aAnswer:9 times.
Question 24.How many times is the following loop executed? [CBSE Text Book]
i = 100 while (i<=200): print i i + =20
Answer:6 times
Question 25.State whether the statement is True or False? No matter the underlying data type if values are equal returns true,
char ch1, ch2; if (ch1==ch2) print “Equal”
Answer:True. Two values of same data types can be equal.
Question 26.What are the logical operators of Python?Answer:or, and, not
Question 27.What is the difference between ‘/’ and ‘//’ ?Answer:
// is Integer or Floor division whereas / is normal division (eg) 7.0 // 2 → 3.0 7.0/2 → 3.5
Question 28.How can we import a module in Python?Answer:1. using import
Syntax: import[,,...] Example: import math, cmath
2. using from
Syntax: fromimport[, ,.. ,] Example: . from fib. import fib, fib2.
Question 29.What is the difference between parameters and arguments?Answer:
S.No.ParametersArguments1Values provided in function headerValues provided in function call.2(eg) def area (r):—> r is the parameter(eg) def main() radius = 5.0 area (radius)—> radius is the argument
Question 30.What are default arguments?Answer:Python allowes function arguments to have default values; if the function is called without the argument, the argument gets its default value
Question 31.What are keyword arguments?Answer:If there is a function with many parameters and we want to specify only some of them in function call,then value for such parameters can be provided by using their names instead of the positions. These are called keyword argument.
(eg) def simpleinterest(p, n=2, r=0.6) ' def simpleinterest(p, r=0.2, n=3)
Question 32.What are the advantages of keyword arguments?Answer:It is easier to use since we need not remember the order of the arguments.We can specify the values for only those parameters which we want, and others have default values.
Question 33.What does “in” do?Answer:“in” is a membership operator. It evaluates to true if it finds a variable/string in the specified sequence :Otherwise i+evaluates to false.
(eg) S = “Hello World" if “Hell” in S: print “True” will print True.
Question 34.What does “not in” do?Answer:“not in” is a membership operator. It evaluates to true if it does not finds a variable/stringin the specified sequence. Otherwise it evaluates to false,
(eg) S = “Hello World” if “Hell” not in S: print “False” will print False.
Question 35.What does “slice” do?Answer:The slice[n:m] operator extracts subparts from a string. It doesn’t include the character at index m.
(eg) S = “Hello World” print s[0:4] → Hell
Question 36.What is the use of negative indices in slicing?Answer:Python counts from the end (right) if negative indices are given.
(eg) S = “Hello” print S[:-3] >> He print S[-3:] >> llo
Question 37.Explain find() function?Answer:find (sub[,start[,end]])This function is used to search the first occurrence of the substring in the given string.It returns the index at which the substring starts. It returns -1 if the substring doesn’t occur in the string.
(eg) str = “computer” - str.findf("om”) → 1
Question 38.What are the differences between arrays and lists?Answer:An array holds fixed number of values. List is of variable-length – elements can be dynamically added or removedAn array holds values of a single type. List in Python can hold values of mixed data type.
Question 39.What is the difference between a tuple and a list?Answer:A tuple is immutable whereas a list is a mutable.A tuple cannot be changed whereas a list can be changed internally.A tuple uses parenthess (()) whereas a list uses square brackets ([]).tuple initialization: a = (2, 4, 5)list initialization: a = [2, 4, 5]
Question 40.Carefully observe the following python code and answer the question that follows:x=5def func2():x=3global xx=x+1print xprint xOn execution the above code produces the following output.63Explain the output with respect to the scope of the variables.Answer:Names declared with global keyword have to be referred at the file level. This is because the global scope.If no global statement is being used the variable with the local scope is accessed.Hence, in the above code the statement succeeding the statement global x informs Python to incrementthe global variable xHence, the output is 6 i.e. 5 + 1 which is also the value for global x.When x is reassingned with the value 3 the local x hides the global x and hence 3 printed.(2 marks for explaning the output) (Only 1 mark for explaining global and local namespace.)
Question 41.Explain the two strategies employed by Python for memory allocation. [CBSE SQP 2016]Answer:Pythonuses two strategies for memory allocation-(i) Reference counting(ii) Automatic garbage collectionReference Counting: works by counting the number of times an object is referenced by other in the system.When an object’s reference count reaches zero, Python collects it automatically.Automatic Garbage Collection: Python schedules garbage collection based upon a threshold of object allocations and object deallocations. When the number of allocations minus the number of deallocations are greater that the threshold number, the garbage collector is run and the unused blocks of memory is reclaimed.
TOPIC – 2Writing Python Programs
Question 1.Rewrite the following code in Python after removing all syntax errors(s). Underline each correction done in the code. [CBSE Delhi-2016]for Name in [Amar, Shveta, Parag]if Name [0] = ‘s’:Print (Name)Answer:
for Name in [“_Amar”, ”_Shveta_” , "_Parag_”] : if Name [0] E == ‘S’ : Print (Name)
Question 2.Rewrite the following code is Python after removing all syntax errors(s).Underline each correction done in the code. [CBSE Outside Delhi-2016]for Name in [Ramesh, Suraj, Priya]if Name [0] = ‘S’:Print (Name)Answer:
for Name in [“_Ramesh_”, “_Suraj_” , “_Priya_”] if Name [0] =_=‘S’ : print (Name)
Question 3.What will be the output of the following python code considering the following set of inputs?AMARTHREEA1231200Also, explain the try and except used in the code.Start = 0while True :Try:Number = int (raw input (“Enter Number”))breakexcept valueError : start=start+2print (“Re-enter an integer”)Print (start)Answer:Output:
Enter Number AMAR Re-enter an integer Enter Number THREE Re-enter an integer Enter Number A123 Re-enter an integer Enter Number 12006
Explanation : The code inside try makes sure that the valid number is entered by the user.When any input other an integer is entered, a value error is thrown and it prompts the user to enter another value.
Question 4.Give the output of following with justification. [CBSE SQP 2015]
x = 3 x+ = x-x print x
Answer:Output: 3Working:
x = 3 x = (x+ x-x ):x = 3 + 3 - 3 = 3
Question 5.What will be printed, when following Python code is executed? [CBSE SQP 2015]
class person: def init (self,id): self.id = id arjun = person(150) arjun. diet [‘age’] = 50 print arjun.age + len(arjun. diet )
Justify your answer.Answer:52arjun.age = 50arjun.dict has 2 attributes so length of it is 2. So total = 52.
Question 6.What would be the output of the following code snippets?print 4+9print “4+9”Answer:13 (addition), 49 (concatenation).
Question 7.Highlight the literals in the following programand also predict the output. Mention the types ofvariables in the program.
a=3 b='1' c=a-2 d=a-c e=“Kathy” f=‘went to party.’ g=‘with Sathy’ print a,g,e,f,a,g,“,”,d,g,“,”,c,g,“and his”,e,f
Answer:a, c,d = integerb, e,f,g = stringOutput: 3 with Sathy Kathy, went to party. 3 with Sathy, 2 with Sathy , 1 with Sathy and his Kathy, went to party.
Question 8.What is the result of 4+4/2+2?Answer:4 + (4/2) + 2 = 8.
Question 9.Write the output from the following code: [CBSE Text Book]
x= 10 y = 20 if (x>y): print x+y else: print x-y
Answer:– 10
Question 10.Write the output of the following code:print “Python is an \n interpreted \t Language”Answer:Python is an interpreted Language
Question 11.Write the output from the following code:
s = 0 for I in range(10,2,-2): s+=I print “sum= ",s
Answer:sum= 28
Question 12.Write the output from the following code: [CBSE TextBook]
n = 50 i = 5 s = 0 while i<n: s+ = i i+ = 10 print “i=”,i print “sum=”,s
Answer:
i= 15 i= 25 i= 35 i= 45 i= 55 sum= 125
Question 13.Write the output from the following code: [CBSE TextBook]
n = 50 i = 5 s = 0 while i<n: s+ = i i+ = 10 print “i=”,i print “sum=”,s
Answer:
i= 15 i= 25 i= 35 i= 45 i= 55 sum= 125
Question 14.Observe the following program and answer the question that follows:import randomx = 3N = random, randint (1, x)for 1 in range (N):print 1, ‘#’, 1 + 1a. What is the minimum and maximum number of times the loop will execute?b. Find out, which line of output(s) out of (i) to (iv) will not be expected from the program?i. 0#1ii. 1#2iii. 2#3iv. 3#4Answer:a. Minimum Number = 1Maximum number = 3b. Line iv is not expected to be a part of the output.
Question 15.Observe the following Python code carefully and obtain the output, which will appear on the screen after execution of it. [CBSE SQP 2016]
def Findoutput (): L = "earn" X = " " count = 1 for i in L: if i in ['a', 'e',' i', 'o', 'u']: x = x + 1. Swapcase () else: if (count % 2 ! = 0): x = x + str (len (L[:count])) else: x = x + 1 count = count + 1 print x Findoutput ()
Answer:EA3n
Question 16.Find and write the output of the following Python code:
Number = [9,18,27,36] for N in Numbers: print (N, "#", end = " ") print ()
Answer:
ElementStack of operatorsPostfix Expression1#001#(1#)(1#)2#(1#)(1#2#)1#(2#)(1#2#3#)2#(1#)1#3#(2#)1#2#(3#)1#2#3#
Question 17.What are the possible outcome(s) executed from the following code? Also,specify the maximum and import random. [CBSE Delhi 2016]
PICK=random.randint (0,3) CITY= ["DELHI", "MUMBAI", "CHENNAI", "KOLKATA"]; for I in CITY : for J in range (1, PICK) print (I, end = " ") Print ()
(i)(ii)DELHIDELHIDELHIMUMBAIMUMBAIDELHIMUMBAICHENNAICHENNAIDELHIMUMBAICEHNNAIKOLKATAKOLKATA(iii)(iv)DELHIDELHIMUMBAIMUMBAIMUMBAICHENNAIKOLKATAKOLKATAKOLKATAKOLKATA
Answer:Option (i) and (iii) are possible option (i) onlyPICKER maxval = 3 minval = 0
Question 18.Find and write the output of the following Python code : [CBSE Outside Delhi-2016]
Values = [10,20,30,40] for val in Values: for I in range (1, Val%9): print (I," * ", end= " ") print ()
Answer:
ElementStack of operatorsPostfix Expression1*001*(1.*)(1*)2*0(1*2*)1*(1,*)(1*2*3*)2*(2.*)1*3*01*2*(1.*)1*2*3*(2,* )(3,* )
Question 19.Write the output from the following code:
y = 2000 if (y%4==0): print “Leap Year” else: print “Not leap year”
Answer:Leap Year.
Question 20.What does the following print?
for i in range (1,10): for j in'range (1,10): print i * j, print
Answer:1 2 3 4 5 6 7 8 92 4 6 8 10 12 14 16 183 6 9 12 15 18 21 24 274 8 12 16 20 24 28 32 365 10 15 20 25 30 35 40 456 12 18 24 30 36 42 48 547 14 21 28 35 42 49 56 638 16 24 32 40 48 56 64 729 18 27 36 45 54 63 72 81
Question 21.What will be the output of the following statement? Also, justify the answer.
>> print ‘Radhsa’s dress is pretty’.
Answer:SyntaxError: invalid syntax.The single quote needs to be replaced by V to get the expected output.
Question 22.Give the output of the following statements :
>>> str=‘Honesty is the best policy’ >>> str.replace(‘o’,‘*’)
Answer:‘H*nesty is the best p*licy’.
Question 23.Give the output of the following statements :
>> str=‘Hello Python’ >>> str.istitle()
Answer:True.
Question 24.Give the output of the following statements:
>> str=‘Hello Python’ >>> print str.lstrip(“Hel”)
Answer:Hello Python
Question 25.Write the output for the following codes:
A={10:1000,20:2000,30:3000,40:4000,50:5000} print A.items() print A.keys() print A.values()
Answer:[(40,4000), (10,1000), (20,2000), (50,5000), (30,3000)] [40,10, 20, 50, 30] [4000,1000, 2000, 5000, 3000]
Question 26.Write the output from the following code:
t=(10,20,30,40,50) print len(t)
Answer:5
Question 27.Write the output from the following code:
t=(‘a’,‘b’,‘c’,‘A’,‘B’) print max(t) print min(t)
Answer:‘c’A’
Question 28.Find the output from the following code:
T=(10,30,2,50,5,6,100,65) print max(T) print min(T)
Answer:1002
Question 29.Write the output from the following code:
T1=(10,20,30,40,50) T2 =(10,20,30,40,50) T3 =(100,200,300) cmp(T1, T2) cmp(T2,T3) cmp(T3,T1)
Answer:0-11
Question 30.Write the output from the following code:
T1=(10,20,30,40,50) T2=(100,200,300) T3=T1+T2 print T3
Answer:(10,20,30,40,50,100,200,300)
Question 31.Find the output from the following code:
t=tuple() t = t +(‘Python’,) print t print len(t) t1=(10,20,30) print len(t1)
Answer:(‘Python’,)13
Question 32.Rewrite the following code in Python after remo¬ving all syntax error(s).Underline each correction done in the code.
for student in [Jaya, Priya, Gagan] If Student [0] = ‘S’: print (student)
Answer:for studednt in values [“Jaya”, “Priya”, “Gagan”]:if student [0] = = “S”print (student)
Question 33.Find and write the output of the following Python code:
Values = [11, 22, 33, 44] for V in Values: for NV in range (1, V%10): print (NV, V)
Answer:1, 112,223,334, 44
Question 34.What are the possible outcome(s) executed from the following code? Also, specify the maximum and minimum values that can be assigned to variable SEL.
import random SEL=random. randint (0, 3) ANIMAL = [“DEER”, “Monkey”, “COW”, “Kangaroo”]; for A in ANIMAL: for AAin range (1, SEL): print (A, end =“”) print ()
(i)(ii)(iii)(iv)DEERDEERDEERDEERDEERMONKEYMONKEYDELHIMONKEYMONKEYMONKEYMONKEYCOWCOWDELHIMONKEYCOWCOWKANGAROOKANGAROOKANGAROOKANGAROOKANGAROOKANGAROO
Answer:Maximum value of SEL is 3.The possible output is belowDEERMonkey MonkeyKangaroo Kangaroo KangarooThus (iv) is the correct option.
TOPIC-3Random Functions
Question 1.What are the possible outcome(s) executed from the following code ? Also specify the maximum and minimum values that can be assigned to variable PICKER. [CBSE Outside Delhi-2016]
import random PICKER = random randint (0, 3) COLOR = ["BLUE", "PINK", "GREEN", "RED"]: for I in COLOR : for J in range (1, PICKER): Print (I, end = " ") Print ()
(i)(ii)(iii) (iv)BLUEBLUEPINKSLUEBLUEPINKBLUEPINKPINKGREENPINKPINKGREENBLUEPINKGREENGREENREDGREENGREENREDBLUEPINKGREENREDREDRED
Answer:Option (i) and (iv) are possibleORoption (i) onlyPICKER maxval = 3 minval = 0
Question 2.What are the possible outcome(s) expected from the following python code? Also specifymaximum and minimum value, which we can have. [CBSE SQP 2015]
def main(): p = ‘MY PROGRAM’ i = 0 while p[i] != ‘R’: l = random.randint(0,3) + 5 print p[l],’-’, i += 1
(i) R – P – O – R –(ii) P – O – R – Y –(iii) O -R – A – G –(iv) A- G – R – M –Answer:Minimum value=5Maximum value=8So the only possible values are O, G, R, AOnly option (iii) is possible.
TOPIC-4Correcting The Errors
Question 1.Rewrite the following Python code after removing all syntax error(s). Underline the corrections done.[CBSE SQP 2015]
def main(): r = raw-input(‘enter any radius : ’) a = pi * math.pow(r,2) print “ Area = ” + a
Answer:
def main (): r = raw_input(‘enter any radius : ’) a = pi * math.pow(r,2) print “ Area = ”, a
Question 2.Rectify the error (if any) in the given statements.
>> str=“Hello Python” >>> str[6]=‘S’
Answer:
str[6] = ‘S’ is incorrect ‘str’ object does not support item assignment. str.replace(str[6],‘S’).
Question 3.Find the errors from the following code:T=[a,b,c]print TAnswer:NameError: name ‘a’ is not defined .T=[‘a’,‘b’,‘c’]
Question 4.Find the errors from the following code:for i in 1 to 100:print IAnswer:for i in range (1,100):print i
Question 5.Find the errors from the following code:
i=10 ; while [i<=n]: print i i+=10
Answer:
i=10 n=100 while (i<=n): print i i+=10
Question 6.Find the errors from the following code:
if (a>b) print a: else if (a<b) print b: else print “both are equal”
Answer:
if (a>b) // missing colon print a: else if (a<b) // missing colon // should be elif print b: else // missing colon print “both are equal"
Question 7.Find errors from the following codes:
c=dict() n=input(Enter total number) i=1 while i<=n: a=raw_input(“enter place”) b=raw_input(“enter number”) c[a]=b i=i+1 print “place”,“\t”,“number” for i in c: print i,“\t”,c[a[i]]
Answer:
c=dict() n=input(‘‘Enter total number”) i=1 while i<=n : a=raw_input(“enter place”) b=raw_inputf enter number”) c[a]=b i=i+1 print “place”,“\t”,“number” for i in c: print i,“\t”,c[i]
Question 8.Observe the following class definition and answer the question that follows : [CBSE SQP 2016]
class info: ips=0 def _str_(self): #Function 1 return "Welcome to the Info Systems" def _init_(Self): self. _ Sstemdate= " " self. SystemTime = " " def getinput (self): self . Systemdate = raw_input ("enter data") self , SystemTime = raw_Input ("enter data") Info, incrips () Estaiomethod # Statement 1 def incrips (): Info, ips, "times" I = Info () I. getinput () Print I. SystemTime Print I. _Systemdate # Statement 2
i. Write statement to invoke Function 1.ii. On Executing the above code, Statement 2 is giving an error explain.Answer:i. print Iii. The statement 2 is giving an error because _ Systemdate is a private variable and hence cannot to be printed outside the class.
TOPIC – 5Short Programs
Question 1.Write a program to calculate the area of a rectangle. The program should get the length and breadth ;values from the user and print the area.Answer:
length = input(“Enter length”) breadth = input(“Enter breadth”) print “Area of rectangle =”,length*breadth
Question 2.Write a program to calculate the roots of a quadratic equation.Answer:
import math a = input(“Enter co-efficient of x^2”) b = input(“Enter co-efficient of x”) c = inputfEnter constant term”) d = b*b - 4*a*c if d == 0: print “Roots are real and equal” root1 = root2 = -b / (2*a) elif d > 0: print “Roots are real and distinct” root1 = (- b + math.sqrt(d)) / (2*a) root2 = (-b - math.sqrt(d)) / (2*a) else: print “Roots are imaginary” print “Roots of the quadratic equation are”,root1,“and”,root2
Question 3.Write a program to input any number and to print all the factors of that number.Answer:
n = inputfEnter the number") for i in range(2,n): if n%i == 0: print i,���is a factor of’.n
Question 4.Write a program to input ,.any number and to check whether given number is Armstrong or not.(Armstrong 1,153,etc. 13 =1, 13+53 +33 =153)Answer:
n = inputfEnter the number”) savedn = n sum=0 while n > 0: a = n%10 sum = sum + a*a*a n = n/10 if savedn == sum: print savedn,“is an Armstrong Number” else: print savedn,”is not an Armstrong Number”
Question 5.Write a program to find all the prime numbers up to a given numberAnswer:
n = input("Enter the number”) i = 2 flag = 0 while (i < n): if (n%i)==0: flag = 1 print n,“is composite” break i = i+ 1 if flag ==0 : print n,“is prime”
Question 6.Write a program to convert decimal number to binary.Answer:
i=1 s=0 dec = int ( raw_input(“Enter the decimal to be converted:”)) while dec>0: rem=dec%2 s=s + (i*rem) dec=dec/2 i=i*10 print “The binary of the given number is:”,s raw_input()
Question 7.Write a program to convert binary to decimalAnswer:
binary = raw_input(“Enter the binary string”) decimal=0 for i in range(len(str(binary))): power=len (str (binary)) - (i+1) decimal+=int(str(binary)[i])*(2**power) print decimal
Question 8.Write a program to input two complex numbers and to find sum of the given complex numbers.Answer:
areal = input("Enter real part of first complex number”) aimg = input("Enter imaginary part of first complex number”) breal = input("Enter real part of second complex number”) bimg = input("Enter imaginary part of second complex number”) totreal = areal + breal totimg = aimg + bimg print “Sum of the complex numbers=",totreal, “+i”, totimg
Question 9.Write a program to input two complex numbers and to implement multiplication of the given complex numbers.Answer:
a = input("Enter real part of first complex number”) b = input("Enter imaginary part of first complex number”) c = input("Enter real part of second complex number”) d = input("Enter imaginary part of second complex number”) real= a*c - b*d img= a*d + b*c print “Product of the complex numbers=",real, “+i”,img
Question 10.Write a program to find the sum of all digits of the given number.Answer:
n = inputfEnter the number”) rev=0 while (n>0): a=n%10 sum = sum + a n=n/10 print “Sum of digits=”,sum
Question 11.Write a program to find the reverse of a number.Answer:
n = input("Enter the number”) rev=0 while (n>0): a=n%10 rev=(rev*10)+a n=n/10 print “Reversed number=”,rev
Question 12.Write a program to print the pyramid.12 23 3 34 4 4 45 5 5 5 5Answer:
for i in range(1,6): for j in range(1,i+1): print i, print
Question 13.Write a program to input username and password and to check whether the given username and password are correct or not.Answer:
import string usemame= raw_input(“Enter username”) password = raw_input(“Enter password”) if cmp(username.strip(),“XXX”)== 0: if cmp(password,”123”) == 0: print “Login successful” else: print “Password Incorrect” else: print “Username Incorrect”
Question 14.Write a generator function generatesq () that displays the squareroots of numbers from 100 to nwhere n is passed as an argument.Answer:
import math def generatesq (n) : for i in range (100, n) : yield (math, sqrt (i))
Question 15.Write a method in Python to find and display the prime number between 2 to n.Pass n as argument to the method.Answer:
def prime (N) : for a in range (2, N): for I in range (2, a): if N%i ==0 : break print a OR def prime (N): for a in range (2, N): for I in range (2, a) : if a%1= = 0 : break else : print a
Question 16.Write a program to input username and password and to check whether the given username and password are correct or not.Answer:
import string usemame= raw_input(“Enter username”) password = raw_input(“Enter password”) if cmp(usemame.strip(),“XXX”)== 0: if cmp(password,”123”) == 0: print “Login successful” else: print “Password Incorrect” else: print “Username Incorrect”
Question 17.Which string method is used to implement the following: [CBSE Text Book]
To count the number of characters in the string.
To change the first character of the string in capital letter.
To check whether given character is letter or a number.
To change lowercase to uppercase letter.
Change one character into another character.
Answer:
len(str)
str.title() or str.capitalize()
str.isalpha and str.isdigit()
lower(str[i])
str.replace(char, newchar)
Question 18.Write a program to input any string and to find the number of words in the string.Answer:
str = “Honesty is the best policy” words = str.split() print len(words)
Question 19.Write a program to input n numbers and to insert any number in a particular position.Answer:
n=input(“Enter no. of values") num=[] for i in range (n): number=input(“Enter the number") num.append(number) newno = input(“Enter the number to be inserted”) pos = input(“Enter position”) num.insert(newno,pos) print num
Question 20.Write a program to input n numbers and to search any number from the list.Answer:
n=input(“Enter no. of values”) num=[] flag=0 for i in range (n): number=input(“Enter the number”) num. append(number) search = input(“Enter number to be searched") for i in range(n): if num[i]==search: print search,“found at position”,i flag=1 if flag==0: print search, “not found in list”
Question 21.Write a program to search input any customer name and display customer phone numberif the customer name is exist in the list.Answer:
def printlist(s): i=0 for i in range(len(s)): print i,s[i] i = 0 phonenumbers = [‘9840012345’,‘9840011111’,’ 9845622222’,‘9850012345’,‘9884412345’] flag=0 number = raw_input(“Enter the phone number to be searched") number = number.strip() try: i = phonenumbers.index(number) if i >= 0: flag=1 except ValueError: pass if(flag <>0): print “\nphone number found in Phonebook at index”, i else: print'\iphonenumbernotfoundin phonebook” print “\nPHONEBOOK” printlist(phonenumbers)
Question 22.Write a program to input n numbers and to reverse the set of numbers without using functions.Answer:
n=input(“Enter no. of values”) num=[] flag=0 for i in range (n): number=input(“Enter the number”) num. append(number) j=n-1 for i in range(n): if i<=n/2: num[i],num[j] = num[j],num[i] j=j-1 else: break print num
Question 23.Find and write the output of the following Python code: [CBSE Complementry-2016]
class Client: def init (self, ID = 1, NM=”Noname”) # constructor self.CID = ID self. Name = NM def Allocate (self, changelD, Title) : self.CID = self.CID + Changeld self.Name = Title + self. Name def Display (self) : print (self. CID). "#”, self. Name) C1 = Client () C2 = Client (102) C3 = Client (205, ‘’Fedrick”) C1 . Display () C2 . Display () C3 . Display () C2 . Allocate (4, "Ms.”) C3 .Allocate (2, "Mr.”) C1. Allocate (1, "Mrs.”) C1. Display () C2 . Display () C3 . Display ()
Answer:
CID Name — Fedrick 102 Mr. Fedrick 205 Mrs. Fedrick — Mr. & Mrs. Fedrick
Question 24.What will be the output of the following Python code considering the following set of inputs?
MAYA Your 5 Apples Mine2 412 Also, explain the try and except used in the code. Count = 0 while True : try: Number=int (raw input ("Input a Number :")) break Except valueError : Count=Count + 2 # For later versions of python, raw_input # Should be consider as input
mehtods:– DenCal () # Method to calcualte Density as People/Area– Add () # Method to allow user to enter values Dcode, DName, People, Area and Call DenCal () Mehtod– View () # Method to display all the data members also display a message “”High Population”if the Density is more than 8000.Answer:Output is below2 Re Enter Number10 Re Enter Number5 Input = Number3 Input = numberTry and except are used for handling exception in the Pythan code.
Question 25.Write a method in Python and display the prime numbers between 2 to N. Pass as argument to the methods.Answer:
def prime (N) : for a in range (2, N) Prime=1 for I in range (2, a): if a%i= = 0 : Prime = 0 if Prime = = 1: print a OR def prime (N) : for a in range (2, N): for I in range (2, a) : if a%i = = 0: break else : print a OR Any other correct code performing the same
Long Answer Type Questions (6 marks)
Question 1.Aastha wnats to create a program that accepts a string and display the characters in the reversein the same line using a Stack. She has created the following code, help her by completing thedefinitions on the basis of requirements given below:[CBSE SQP 2016]
Class mystack : def inin (self): selfe. mystr= # Accept a string self.mylist= # Convert mystr to a list # Write code to display while removing element from the stack. def display (self) : : :
Answer:
class mystack : def _init_ (self) : self.myster= rawjnput ("Enter the string”) self.mylist = list (self.mystr) def display (self) : x = len (self. mylist) if (x > 0) : for i in range (x) : print self.mylist.pop (), else : print "Stack is empty”
via Blogger https://ift.tt/3kkMk05
0 notes
letraescarlataorg · 5 years ago
Text
En estos 2vídeos, Beatriz Hermida, relata las condiciones de 2 tratos de "gestación subrogada altruista" con "compensaciones" de 2clientes🇪🇸a los que tuvo acceso, cuyo objeto del contrato es el menor, si este no nace con vida, el mismo se rescinde Las madres calladitas más guapas https://t.co/oHbZl0r29Q
En estos 2vídeos, Beatriz Hermida, relata las condiciones de 2 tratos de "gestación subrogada altruista" con "compensaciones" de 2clientes🇪🇸a los que tuvo acceso, cuyo objeto del contrato es el menor, si este no nace con vida, el mismo se rescinde Las madres calladitas más guapas https://t.co/oHbZl0r29Q
— Teresa Domínguez ✍ (@letra_escarlata) May 29, 2020
from Twitter https://twitter.com/letra_escarlata
0 notes
eithelistic · 9 years ago
Photo
Tumblr media
ATM work for today #wedding for #hairstyling 💆💇👰 #workfortoday #workaholics #2clients (at Seda Hotel Nuvali)
0 notes
avalemode · 10 years ago
Photo
Tumblr media
There's just something about circle skirts... #sewing #newproject #2clients
0 notes
inkkbully · 12 years ago
Photo
Tumblr media
My Monday in nutshell... #mydaughter #2clients #noflinching
0 notes
monicaham · 6 years ago
Photo
Tumblr media
Área Bosque en #Playa Escondida ó Miramar Beach to Cd. #Madero #Tamaulipas Ultimas Fechas!! #PORTRAIT OUTLET en #PrimeraComunion, #BODAS y #15años "Aparta en JUNIO" PREGUNTA POR LOS PAQUETES,, Promo PRECIOS 2017!! & PROMOCIONES EXCLUSIVAS (Eventos/Sesiones, Checando Agenda 2019) y Otras Promos en Sesión Post-Evento Splash DRESS,, PREGUNTA POR TÚ PROMOCION ¿Eres Clientes de Casa? de CLIENTE FRECUENTE... Compartan! "Paquete Especial de 1er.Comunión" desde $970. Pregunta por los otros paquetes más completos (PROMOCIÓN: Si traes 2Clientes que"Contraten"(de Igual ó Mayor precio) Retrato de Comunión a ellas tendran-10%+REGaLO,, El tú obtendras un -20% +REGaLOs "APARTANDO" en MAYO (Eventos & Sesiones de Mayo a Julio 2019) "Captando los Diferentes Rostros & Momentos". FanPage FB: Fotografía & Diseño by Mónica Ham Instagram: HamFotografiaMonica Casa/Studio by @MONICA_HAM Photographer, Graphic Designer & Video🙏🏻Gracias Dios!! 17 Años.... LLAME YA📲!!, CHECA LA AGENDA!! Citas inbox ó 8331407622 (WhatsApp) El mayor ó mejor arte; es el de hacer felices a los demás,,Dejame hacerte feliz con mis imagenes, con mis fotografías. #tampico #altamina #Photographer #fotografo #photography #Fotografía #CdMadero #HAMFOTOGRAFIAMONICA #photographerdiarymonicaham #ILoveMyWork #YoAmoMiTrabajo #YoSoyJaiba #OrgulloDeSerJaiba #OrgullosamenteJaiba 🇲🇽 #proudtobemex (en Ciudad Madero, Tamaulipas) https://www.instagram.com/p/ByL74KsHeMq/?igshid=19nvu7qh9dmnb
0 notes
margdarsanme · 4 years ago
Text
NCERT Class 12 Computer Science Chapter 1 Review of Python
NCERT Class 12 Computer Science Python Solutions for Chapter 1 :: Review of Python
TOPIC-1
Python Basics
Very Short Answer Type Questions(1 mark)
Question 1.Name the Python Library modules which need to be imported to invoke the following functions:
load ()
pow () [CBSE Delhi 2016]
Answer:
pickle
math
Question 2.Name the modules to which the following func-tions belong:
Uniform ()
fabs () [CBSE SQP 2016]
Answer:
random ()
math ()
Question 3.Differentiate between the round() and floor() functions with the help of suitable example.[CBSE Comptt. 2016]Answer:The function round() is used to convert a fractional number into whole as the nearest next whereas the function floor() is used convert to the nearest lower whole number, e.g.,round (5.8) = 6, round (4.1) = 5 and floor (6.9) = 6, floor (5.01) = 5
Short Answer Type Questions (2 marks):
Question 1.Out of the following, find those identifiers, which cannot be used for naming Variables or functions in a Python program:Total * Tax, While, Class, Switch, 3rd Row, finally, Column 31, Total. [CBSE Outside Delhi-2016]Answer:Total * Tax, class, 3rd Row, finally
Question 2.Name the Python Library modules which need to be imported to invoke the follwing functions :
sqrt()
dump() (CBSE Outside Delhi-2016)
Answer:
math
pickle
Question 3.Out of the following, find the identifiers, which cannot be used for naming Variable or Functions in a Python program: [CBSE Delhi 2016]_Cost, Price*Qty, float, switch, Address one, Delete, Number12, doAnswer:Price *Qty, float, Address one, do
Question 4.Out of the following find those identifiers, which can not be used for naming Variable or Functions in a Python Program:Days * Rent, For, A_price, Grand Total, do, 2Clients, Participantl, My cityAnswer:Illegal variables or functions name are as below: Days * Rent, do, 2Clients, For and Grant Total Because of being either keyword or including space or operator or starting with integar.
Question 5.Name the function / method required for [CBSE SQP 2015]
Finding second occurrence of m in madam.
get the position of an item in the list.
Answer:
find
index
Question 6.Which string method is used to implement the following:
To count the number of characters in the string.
To change the first character of the string in capital letter.
To check whether given character is letter or a number.
To change lowercase to uppercase letter.
Change one character into another character. [CBSE TextBook]
Answer:
len(str)
str.capitalize()
ch.isalnum()
str.upper()
str.replace(old,new)
Question 7.What is the difference between input() and raw_input()?Answer:raw_input() takes the input as a string whereas input() basically looks at what the user enters, and automatically determines the correct type. We use the inputQ function when you are expecting an integer from the end-user, and raw_input when you are expecting a string.
Question 8.What are the two ways of output using print()?Answer:Ordinarily, each print statement produces one line of output. You can end the print statement with a trailing ’ to combine the results of multiple print statements into a single line.
Question 9.Why does the expression 2 + 3*4 result in the value 14 and not the value 24?Answer:Operator precedence rules* make the expression to be interpreted as 2 + (3*4) hence the result is 14.
Question 10.How many times will Python execute the code inside the following while loop? You should answer the question without using the interpreter! Justify your answers.
i = 0 while i < 0 and i > 2 : print “Hello ...” i = i+1
Answer:0 times.
Question 11.How many times will Python execute the code inside the following while loop?
i = 1 while i < 10000 and i > 0 and 1: print “ Hello ...” i = 2 * i
Answer:14.
Question 12.Convert the following for loop into while loop, for i in range (1,100):
if i % 4 == 2 : print i, “mod”, 4 , “= 2”
Answer:
i=1 while i < 100: if i % 4 == 2: print i, “mod”, 4 , “= 2” i = i +1
Question 13.Convert the following for loop into while loop.
for i in range(10): for j in range(i): print '$', print"
Answer:
i=0 while i < 10: j=0 while j < i: print '$’ print"
Question 14.Rewrite the following for loop into while loop: [CBSE Text Book]
for a in range(25,500,25): print a
Answer:
a=25 while a < 500: print a a = a + 25
Question 15.Rewrite the following for loop into while loop: [CBSE Text Book]
for a in range(90, 9, -9): print a
Answer:
a = 90 while a > 9: print a a = a-9
Question 16.Convert the following while loop into for loop:
i = 0 while i < 100: if i % 2 == 0: print i, “is even” else: print i, “is odd” i = i + 1
Answer:
for i in range(100): if i % 2 == 0: print i, “is even” else : print i, “is odd”
Question 17.Convert the following while loop into for loop
char = "" print “Press Tab Enter to stop ...” iteration = 0 while not char == “\t” and not iteration > 99: print “Continue?” char = raw_input() iteration+ = 1
Answer:
char = "" print “Press Tab Enter to stop ...” for iteration in range(99): if not char == ‘\t’: print “Continue?” char = raw_input()
Question 18.Rewrite the following while loop into for loop:
i = 10 while i<250: print i i = i+50
Answer:
for i in range(10, 250, 50): print i
Question 19.Rewrite the following while loop into for loop:
i=88 while(i>=8): print i i- = 8
Answer:
for i in range(88, 9, -8) print i
Question 20.Write for statement to print the series 10,20,30, ……., 300Answer:
for i in range(10, 301, 10): print i
Question 21.Write for statement to print the series 105,98,91,… .7Answer:
for i in range(105, 8, -7): print i
Question 22.Write the while loop to print the series: 5,10,15,…100Answer:
i=5 while i <= 100: print i i = i + 5
Question 23.How many times is the following loop executed? [CBSE Text Book]for a in range(100,10,-10):print aAnswer:9 times.
Question 24.How many times is the following loop executed? [CBSE Text Book]
i = 100 while (i<=200): print i i + =20
Answer:6 times
Question 25.State whether the statement is True or False? No matter the underlying data type if values are equal returns true,
char ch1, ch2; if (ch1==ch2) print “Equal”
Answer:True. Two values of same data types can be equal.
Question 26.What are the logical operators of Python?Answer:or, and, not
Question 27.What is the difference between ‘/’ and ‘//’ ?Answer:
// is Integer or Floor division whereas / is normal division (eg) 7.0 // 2 → 3.0 7.0/2 → 3.5
Question 28.How can we import a module in Python?Answer:1. using import
Syntax: import[,,...] Example: import math, cmath
2. using from
Syntax: fromimport[, ,.. ,] Example: . from fib. import fib, fib2.
Question 29.What is the difference between parameters and arguments?Answer:
S.No.ParametersArguments1Values provided in function headerValues provided in function call.2(eg) def area (r):—> r is the parameter(eg) def main() radius = 5.0 area (radius)—> radius is the argument
Question 30.What are default arguments?Answer:Python allowes function arguments to have default values; if the function is called without the argument, the argument gets its default value
Question 31.What are keyword arguments?Answer:If there is a function with many parameters and we want to specify only some of them in function call,then value for such parameters can be provided by using their names instead of the positions. These are called keyword argument.
(eg) def simpleinterest(p, n=2, r=0.6) ' def simpleinterest(p, r=0.2, n=3)
Question 32.What are the advantages of keyword arguments?Answer:It is easier to use since we need not remember the order of the arguments.We can specify the values for only those parameters which we want, and others have default values.
Question 33.What does “in” do?Answer:“in” is a membership operator. It evaluates to true if it finds a variable/string in the specified sequence :Otherwise i+evaluates to false.
(eg) S = “Hello World" if “Hell” in S: print “True” will print True.
Question 34.What does “not in” do?Answer:“not in” is a membership operator. It evaluates to true if it does not finds a variable/stringin the specified sequence. Otherwise it evaluates to false,
(eg) S = “Hello World” if “Hell” not in S: print “False” will print False.
Question 35.What does “slice” do?Answer:The slice[n:m] operator extracts subparts from a string. It doesn’t include the character at index m.
(eg) S = “Hello World” print s[0:4] → Hell
Question 36.What is the use of negative indices in slicing?Answer:Python counts from the end (right) if negative indices are given.
(eg) S = “Hello” print S[:-3] >> He print S[-3:] >> llo
Question 37.Explain find() function?Answer:find (sub[,start[,end]])This function is used to search the first occurrence of the substring in the given string.It returns the index at which the substring starts. It returns -1 if the substring doesn’t occur in the string.
(eg) str = “computer” - str.findf("om”) → 1
Question 38.What are the differences between arrays and lists?Answer:An array holds fixed number of values. List is of variable-length – elements can be dynamically added or removedAn array holds values of a single type. List in Python can hold values of mixed data type.
Question 39.What is the difference between a tuple and a list?Answer:A tuple is immutable whereas a list is a mutable.A tuple cannot be changed whereas a list can be changed internally.A tuple uses parenthess (()) whereas a list uses square brackets ([]).tuple initialization: a = (2, 4, 5)list initialization: a = [2, 4, 5]
Question 40.Carefully observe the following python code and answer the question that follows:x=5def func2():x=3global xx=x+1print xprint xOn execution the above code produces the following output.63Explain the output with respect to the scope of the variables.Answer:Names declared with global keyword have to be referred at the file level. This is because the global scope.If no global statement is being used the variable with the local scope is accessed.Hence, in the above code the statement succeeding the statement global x informs Python to incrementthe global variable xHence, the output is 6 i.e. 5 + 1 which is also the value for global x.When x is reassingned with the value 3 the local x hides the global x and hence 3 printed.(2 marks for explaning the output) (Only 1 mark for explaining global and local namespace.)
Question 41.Explain the two strategies employed by Python for memory allocation. [CBSE SQP 2016]Answer:Pythonuses two strategies for memory allocation-(i) Reference counting(ii) Automatic garbage collectionReference Counting: works by counting the number of times an object is referenced by other in the system.When an object’s reference count reaches zero, Python collects it automatically.Automatic Garbage Collection: Python schedules garbage collection based upon a threshold of object allocations and object deallocations. When the number of allocations minus the number of deallocations are greater that the threshold number, the garbage collector is run and the unused blocks of memory is reclaimed.
TOPIC – 2Writing Python Programs
Question 1.Rewrite the following code in Python after removing all syntax errors(s). Underline each correction done in the code. [CBSE Delhi-2016]for Name in [Amar, Shveta, Parag]if Name [0] = ‘s’:Print (Name)Answer:
for Name in [“_Amar”, ”_Shveta_” , "_Parag_”] : if Name [0] E == ‘S’ : Print (Name)
Question 2.Rewrite the following code is Python after removing all syntax errors(s).Underline each correction done in the code. [CBSE Outside Delhi-2016]for Name in [Ramesh, Suraj, Priya]if Name [0] = ‘S’:Print (Name)Answer:
for Name in [“_Ramesh_”, “_Suraj_” , “_Priya_”] if Name [0] =_=‘S’ : print (Name)
Question 3.What will be the output of the following python code considering the following set of inputs?AMARTHREEA1231200Also, explain the try and except used in the code.Start = 0while True :Try:Number = int (raw input (“Enter Number”))breakexcept valueError : start=start+2print (“Re-enter an integer”)Print (start)Answer:Output:
Enter Number AMAR Re-enter an integer Enter Number THREE Re-enter an integer Enter Number A123 Re-enter an integer Enter Number 12006
Explanation : The code inside try makes sure that the valid number is entered by the user.When any input other an integer is entered, a value error is thrown and it prompts the user to enter another value.
Question 4.Give the output of following with justification. [CBSE SQP 2015]
x = 3 x+ = x-x print x
Answer:Output: 3Working:
x = 3 x = (x+ x-x ):x = 3 + 3 - 3 = 3
Question 5.What will be printed, when following Python code is executed? [CBSE SQP 2015]
class person: def init (self,id): self.id = id arjun = person(150) arjun. diet [‘age’] = 50 print arjun.age + len(arjun. diet )
Justify your answer.Answer:52arjun.age = 50arjun.dict has 2 attributes so length of it is 2. So total = 52.
Question 6.What would be the output of the following code snippets?print 4+9print “4+9”Answer:13 (addition), 49 (concatenation).
Question 7.Highlight the literals in the following programand also predict the output. Mention the types ofvariables in the program.
a=3 b='1' c=a-2 d=a-c e=“Kathy” f=‘went to party.’ g=‘with Sathy’ print a,g,e,f,a,g,“,”,d,g,“,”,c,g,“and his”,e,f
Answer:a, c,d = integerb, e,f,g = stringOutput: 3 with Sathy Kathy, went to party. 3 with Sathy, 2 with Sathy , 1 with Sathy and his Kathy, went to party.
Question 8.What is the result of 4+4/2+2?Answer:4 + (4/2) + 2 = 8.
Question 9.Write the output from the following code: [CBSE Text Book]
x= 10 y = 20 if (x>y): print x+y else: print x-y
Answer:– 10
Question 10.Write the output of the following code:print “Python is an \n interpreted \t Language”Answer:Python is an interpreted Language
Question 11.Write the output from the following code:
s = 0 for I in range(10,2,-2): s+=I print “sum= ",s
Answer:sum= 28
Question 12.Write the output from the following code: [CBSE TextBook]
n = 50 i = 5 s = 0 while i<n: s+ = i i+ = 10 print “i=”,i print “sum=”,s
Answer:
i= 15 i= 25 i= 35 i= 45 i= 55 sum= 125
Question 13.Write the output from the following code: [CBSE TextBook]
n = 50 i = 5 s = 0 while i<n: s+ = i i+ = 10 print “i=”,i print “sum=”,s
Answer:
i= 15 i= 25 i= 35 i= 45 i= 55 sum= 125
Question 14.Observe the following program and answer the question that follows:import randomx = 3N = random, randint (1, x)for 1 in range (N):print 1, ‘#’, 1 + 1a. What is the minimum and maximum number of times the loop will execute?b. Find out, which line of output(s) out of (i) to (iv) will not be expected from the program?i. 0#1ii. 1#2iii. 2#3iv. 3#4Answer:a. Minimum Number = 1Maximum number = 3b. Line iv is not expected to be a part of the output.
Question 15.Observe the following Python code carefully and obtain the output, which will appear on the screen after execution of it. [CBSE SQP 2016]
def Findoutput (): L = "earn" X = " " count = 1 for i in L: if i in ['a', 'e',' i', 'o', 'u']: x = x + 1. Swapcase () else: if (count % 2 ! = 0): x = x + str (len (L[:count])) else: x = x + 1 count = count + 1 print x Findoutput ()
Answer:EA3n
Question 16.Find and write the output of the following Python code:
Number = [9,18,27,36] for N in Numbers: print (N, "#", end = " ") print ()
Answer:
ElementStack of operatorsPostfix Expression1#001#(1#)(1#)2#(1#)(1#2#)1#(2#)(1#2#3#)2#(1#)1#3#(2#)1#2#(3#)1#2#3#
Question 17.What are the possible outcome(s) executed from the following code? Also,specify the maximum and import random. [CBSE Delhi 2016]
PICK=random.randint (0,3) CITY= ["DELHI", "MUMBAI", "CHENNAI", "KOLKATA"]; for I in CITY : for J in range (1, PICK) print (I, end = " ") Print ()
(i)(ii)DELHIDELHIDELHIMUMBAIMUMBAIDELHIMUMBAICHENNAICHENNAIDELHIMUMBAICEHNNAIKOLKATAKOLKATA(iii)(iv)DELHIDELHIMUMBAIMUMBAIMUMBAICHENNAIKOLKATAKOLKATAKOLKATAKOLKATA
Answer:Option (i) and (iii) are possible option (i) onlyPICKER maxval = 3 minval = 0
Question 18.Find and write the output of the following Python code : [CBSE Outside Delhi-2016]
Values = [10,20,30,40] for val in Values: for I in range (1, Val%9): print (I," * ", end= " ") print ()
Answer:
ElementStack of operatorsPostfix Expression1*001*(1.*)(1*)2*0(1*2*)1*(1,*)(1*2*3*)2*(2.*)1*3*01*2*(1.*)1*2*3*(2,* )(3,* )
Question 19.Write the output from the following code:
y = 2000 if (y%4==0): print “Leap Year” else: print “Not leap year”
Answer:Leap Year.
Question 20.What does the following print?
for i in range (1,10): for j in'range (1,10): print i * j, print
Answer:1 2 3 4 5 6 7 8 92 4 6 8 10 12 14 16 183 6 9 12 15 18 21 24 274 8 12 16 20 24 28 32 365 10 15 20 25 30 35 40 456 12 18 24 30 36 42 48 547 14 21 28 35 42 49 56 638 16 24 32 40 48 56 64 729 18 27 36 45 54 63 72 81
Question 21.What will be the output of the following statement? Also, justify the answer.
>> print ‘Radhsa’s dress is pretty’.
Answer:SyntaxError: invalid syntax.The single quote needs to be replaced by V to get the expected output.
Question 22.Give the output of the following statements :
>>> str=‘Honesty is the best policy’ >>> str.replace(‘o’,‘*’)
Answer:‘H*nesty is the best p*licy’.
Question 23.Give the output of the following statements :
>> str=‘Hello Python’ >>> str.istitle()
Answer:True.
Question 24.Give the output of the following statements:
>> str=‘Hello Python’ >>> print str.lstrip(“Hel”)
Answer:Hello Python
Question 25.Write the output for the following codes:
A={10:1000,20:2000,30:3000,40:4000,50:5000} print A.items() print A.keys() print A.values()
Answer:[(40,4000), (10,1000), (20,2000), (50,5000), (30,3000)] [40,10, 20, 50, 30] [4000,1000, 2000, 5000, 3000]
Question 26.Write the output from the following code:
t=(10,20,30,40,50) print len(t)
Answer:5
Question 27.Write the output from the following code:
t=(‘a’,‘b’,‘c’,‘A’,‘B’) print max(t) print min(t)
Answer:‘c’A’
Question 28.Find the output from the following code:
T=(10,30,2,50,5,6,100,65) print max(T) print min(T)
Answer:1002
Question 29.Write the output from the following code:
T1=(10,20,30,40,50) T2 =(10,20,30,40,50) T3 =(100,200,300) cmp(T1, T2) cmp(T2,T3) cmp(T3,T1)
Answer:0-11
Question 30.Write the output from the following code:
T1=(10,20,30,40,50) T2=(100,200,300) T3=T1+T2 print T3
Answer:(10,20,30,40,50,100,200,300)
Question 31.Find the output from the following code:
t=tuple() t = t +(‘Python’,) print t print len(t) t1=(10,20,30) print len(t1)
Answer:(‘Python’,)13
Question 32.Rewrite the following code in Python after remo¬ving all syntax error(s).Underline each correction done in the code.
for student in [Jaya, Priya, Gagan] If Student [0] = ‘S’: print (student)
Answer:for studednt in values [“Jaya”, “Priya”, “Gagan”]:if student [0] = = “S”print (student)
Question 33.Find and write the output of the following Python code:
Values = [11, 22, 33, 44] for V in Values: for NV in range (1, V%10): print (NV, V)
Answer:1, 112,223,334, 44
Question 34.What are the possible outcome(s) executed from the following code? Also, specify the maximum and minimum values that can be assigned to variable SEL.
import random SEL=random. randint (0, 3) ANIMAL = [“DEER”, “Monkey”, “COW”, “Kangaroo”]; for A in ANIMAL: for AAin range (1, SEL): print (A, end =“”) print ()
(i)(ii)(iii)(iv)DEERDEERDEERDEERDEERMONKEYMONKEYDELHIMONKEYMONKEYMONKEYMONKEYCOWCOWDELHIMONKEYCOWCOWKANGAROOKANGAROOKANGAROOKANGAROOKANGAROOKANGAROO
Answer:Maximum value of SEL is 3.The possible output is belowDEERMonkey MonkeyKangaroo Kangaroo KangarooThus (iv) is the correct option.
TOPIC-3Random Functions
Question 1.What are the possible outcome(s) executed from the following code ? Also specify the maximum and minimum values that can be assigned to variable PICKER. [CBSE Outside Delhi-2016]
import random PICKER = random randint (0, 3) COLOR = ["BLUE", "PINK", "GREEN", "RED"]: for I in COLOR : for J in range (1, PICKER): Print (I, end = " ") Print ()
(i)(ii)(iii) (iv)BLUEBLUEPINKSLUEBLUEPINKBLUEPINKPINKGREENPINKPINKGREENBLUEPINKGREENGREENREDGREENGREENREDBLUEPINKGREENREDREDRED
Answer:Option (i) and (iv) are possibleORoption (i) onlyPICKER maxval = 3 minval = 0
Question 2.What are the possible outcome(s) expected from the following python code? Also specifymaximum and minimum value, which we can have. [CBSE SQP 2015]
def main(): p = ‘MY PROGRAM’ i = 0 while p[i] != ‘R’: l = random.randint(0,3) + 5 print p[l],’-’, i += 1
(i) R – P – O – R –(ii) P – O – R – Y –(iii) O -R – A – G –(iv) A- G – R – M –Answer:Minimum value=5Maximum value=8So the only possible values are O, G, R, AOnly option (iii) is possible.
TOPIC-4Correcting The Errors
Question 1.Rewrite the following Python code after removing all syntax error(s). Underline the corrections done.[CBSE SQP 2015]
def main(): r = raw-input(‘enter any radius : ’) a = pi * math.pow(r,2) print “ Area = ” + a
Answer:
def main (): r = raw_input(‘enter any radius : ’) a = pi * math.pow(r,2) print “ Area = ”, a
Question 2.Rectify the error (if any) in the given statements.
>> str=“Hello Python” >>> str[6]=‘S’
Answer:
str[6] = ‘S’ is incorrect ‘str’ object does not support item assignment. str.replace(str[6],‘S’).
Question 3.Find the errors from the following code:T=[a,b,c]print TAnswer:NameError: name ‘a’ is not defined .T=[‘a’,‘b’,‘c’]
Question 4.Find the errors from the following code:for i in 1 to 100:print IAnswer:for i in range (1,100):print i
Question 5.Find the errors from the following code:
i=10 ; while [i<=n]: print i i+=10
Answer:
i=10 n=100 while (i<=n): print i i+=10
Question 6.Find the errors from the following code:
if (a>b) print a: else if (a<b) print b: else print “both are equal”
Answer:
if (a>b) // missing colon print a: else if (a<b) // missing colon // should be elif print b: else // missing colon print “both are equal"
Question 7.Find errors from the following codes:
c=dict() n=input(Enter total number) i=1 while i<=n: a=raw_input(“enter place”) b=raw_input(“enter number”) c[a]=b i=i+1 print “place”,“\t”,“number” for i in c: print i,“\t”,c[a[i]]
Answer:
c=dict() n=input(‘‘Enter total number”) i=1 while i<=n : a=raw_input(“enter place”) b=raw_inputf enter number”) c[a]=b i=i+1 print “place”,“\t”,“number” for i in c: print i,“\t”,c[i]
Question 8.Observe the following class definition and answer the question that follows : [CBSE SQP 2016]
class info: ips=0 def _str_(self): #Function 1 return "Welcome to the Info Systems" def _init_(Self): self. _ Sstemdate= " " self. SystemTime = " " def getinput (self): self . Systemdate = raw_input ("enter data") self , SystemTime = raw_Input ("enter data") Info, incrips () Estaiomethod # Statement 1 def incrips (): Info, ips, "times" I = Info () I. getinput () Print I. SystemTime Print I. _Systemdate # Statement 2
i. Write statement to invoke Function 1.ii. On Executing the above code, Statement 2 is giving an error explain.Answer:i. print Iii. The statement 2 is giving an error because _ Systemdate is a private variable and hence cannot to be printed outside the class.
TOPIC – 5Short Programs
Question 1.Write a program to calculate the area of a rectangle. The program should get the length and breadth ;values from the user and print the area.Answer:
length = input(“Enter length”) breadth = input(“Enter breadth”) print “Area of rectangle =”,length*breadth
Question 2.Write a program to calculate the roots of a quadratic equation.Answer:
import math a = input(“Enter co-efficient of x^2”) b = input(“Enter co-efficient of x”) c = inputfEnter constant term”) d = b*b - 4*a*c if d == 0: print “Roots are real and equal” root1 = root2 = -b / (2*a) elif d > 0: print “Roots are real and distinct” root1 = (- b + math.sqrt(d)) / (2*a) root2 = (-b - math.sqrt(d)) / (2*a) else: print “Roots are imaginary” print “Roots of the quadratic equation are”,root1,“and”,root2
Question 3.Write a program to input any number and to print all the factors of that number.Answer:
n = inputfEnter the number") for i in range(2,n): if n%i == 0: print i,“is a factor of’.n
Question 4.Write a program to input ,.any number and to check whether given number is Armstrong or not.(Armstrong 1,153,etc. 13 =1, 13+53 +33 =153)Answer:
n = inputfEnter the number”) savedn = n sum=0 while n > 0: a = n%10 sum = sum + a*a*a n = n/10 if savedn == sum: print savedn,“is an Armstrong Number” else: print savedn,”is not an Armstrong Number”
Question 5.Write a program to find all the prime numbers up to a given numberAnswer:
n = input("Enter the number”) i = 2 flag = 0 while (i < n): if (n%i)==0: flag = 1 print n,“is composite” break i = i+ 1 if flag ==0 : print n,“is prime”
Question 6.Write a program to convert decimal number to binary.Answer:
i=1 s=0 dec = int ( raw_input(“Enter the decimal to be converted:”)) while dec>0: rem=dec%2 s=s + (i*rem) dec=dec/2 i=i*10 print “The binary of the given number is:”,s raw_input()
Question 7.Write a program to convert binary to decimalAnswer:
binary = raw_input(“Enter the binary string”) decimal=0 for i in range(len(str(binary))): power=len (str (binary)) - (i+1) decimal+=int(str(binary)[i])*(2**power) print decimal
Question 8.Write a program to input two complex numbers and to find sum of the given complex numbers.Answer:
areal = input("Enter real part of first complex number”) aimg = input("Enter imaginary part of first complex number”) breal = input("Enter real part of second complex number”) bimg = input("Enter imaginary part of second complex number”) totreal = areal + breal totimg = aimg + bimg print “Sum of the complex numbers=",totreal, “+i”, totimg
Question 9.Write a program to input two complex numbers and to implement multiplication of the given complex numbers.Answer:
a = input("Enter real part of first complex number”) b = input("Enter imaginary part of first complex number”) c = input("Enter real part of second complex number”) d = input("Enter imaginary part of second complex number”) real= a*c - b*d img= a*d + b*c print “Product of the complex numbers=",real, “+i”,img
Question 10.Write a program to find the sum of all digits of the given number.Answer:
n = inputfEnter the number”) rev=0 while (n>0): a=n%10 sum = sum + a n=n/10 print “Sum of digits=”,sum
Question 11.Write a program to find the reverse of a number.Answer:
n = input("Enter the number”) rev=0 while (n>0): a=n%10 rev=(rev*10)+a n=n/10 print “Reversed number=”,rev
Question 12.Write a program to print the pyramid.12 23 3 34 4 4 45 5 5 5 5Answer:
for i in range(1,6): for j in range(1,i+1): print i, print
Question 13.Write a program to input username and password and to check whether the given username and password are correct or not.Answer:
import string usemame= raw_input(“Enter username”) password = raw_input(“Enter password”) if cmp(username.strip(),“XXX”)== 0: if cmp(password,”123”) == 0: print “Login successful” else: print “Password Incorrect” else: print “Username Incorrect”
Question 14.Write a generator function generatesq () that displays the squareroots of numbers from 100 to nwhere n is passed as an argument.Answer:
import math def generatesq (n) : for i in range (100, n) : yield (math, sqrt (i))
Question 15.Write a method in Python to find and display the prime number between 2 to n.Pass n as argument to the method.Answer:
def prime (N) : for a in range (2, N): for I in range (2, a): if N%i ==0 : break print a OR def prime (N): for a in range (2, N): for I in range (2, a) : if a%1= = 0 : break else : print a
Question 16.Write a program to input username and password and to check whether the given username and password are correct or not.Answer:
import string usemame= raw_input(“Enter username”) password = raw_input(“Enter password”) if cmp(usemame.strip(),“XXX”)== 0: if cmp(password,”123”) == 0: print “Login successful” else: print “Password Incorrect” else: print “Username Incorrect”
Question 17.Which string method is used to implement the following: [CBSE Text Book]
To count the number of characters in the string.
To change the first character of the string in capital letter.
To check whether given character is letter or a number.
To change lowercase to uppercase letter.
Change one character into another character.
Answer:
len(str)
str.title() or str.capitalize()
str.isalpha and str.isdigit()
lower(str[i])
str.replace(char, newchar)
Question 18.Write a program to input any string and to find the number of words in the string.Answer:
str = “Honesty is the best policy” words = str.split() print len(words)
Question 19.Write a program to input n numbers and to insert any number in a particular position.Answer:
n=input(“Enter no. of values") num=[] for i in range (n): number=input(“Enter the number") num.append(number) newno = input(“Enter the number to be inserted”) pos = input(“Enter position”) num.insert(newno,pos) print num
Question 20.Write a program to input n numbers and to search any number from the list.Answer:
n=input(“Enter no. of values”) num=[] flag=0 for i in range (n): number=input(“Enter the number”) num. append(number) search = input(“Enter number to be searched") for i in range(n): if num[i]==search: print search,“found at position”,i flag=1 if flag==0: print search, “not found in list”
Question 21.Write a program to search input any customer name and display customer phone numberif the customer name is exist in the list.Answer:
def printlist(s): i=0 for i in range(len(s)): print i,s[i] i = 0 phonenumbers = [‘9840012345’,‘9840011111’,’ 9845622222’,‘9850012345’,‘9884412345’] flag=0 number = raw_input(“Enter the phone number to be searched") number = number.strip() try: i = phonenumbers.index(number) if i >= 0: flag=1 except ValueError: pass if(flag <>0): print “\nphone number found in Phonebook at index”, i else: print'\iphonenumbernotfoundin phonebook” print “\nPHONEBOOK” printlist(phonenumbers)
Question 22.Write a program to input n numbers and to reverse the set of numbers without using functions.Answer:
n=input(“Enter no. of values”) num=[] flag=0 for i in range (n): number=input(“Enter the number”) num. append(number) j=n-1 for i in range(n): if i<=n/2: num[i],num[j] = num[j],num[i] j=j-1 else: break print num
Question 23.Find and write the output of the following Python code: [CBSE Complementry-2016]
class Client: def init (self, ID = 1, NM=”Noname”) # constructor self.CID = ID self. Name = NM def Allocate (self, changelD, Title) : self.CID = self.CID + Changeld self.Name = Title + self. Name def Display (self) : print (self. CID). "#”, self. Name) C1 = Client () C2 = Client (102) C3 = Client (205, ‘’Fedrick”) C1 . Display () C2 . Display () C3 . Display () C2 . Allocate (4, "Ms.”) C3 .Allocate (2, "Mr.”) C1. Allocate (1, "Mrs.”) C1. Display () C2 . Display () C3 . Display ()
Answer:
CID Name — Fedrick 102 Mr. Fedrick 205 Mrs. Fedrick — Mr. & Mrs. Fedrick
Question 24.What will be the output of the following Python code considering the following set of inputs?
MAYA Your 5 Apples Mine2 412 Also, explain the try and except used in the code. Count = 0 while True : try: Number=int (raw input ("Input a Number :")) break Except valueError : Count=Count + 2 # For later versions of python, raw_input # Should be consider as input
mehtods:– DenCal () # Method to calcualte Density as People/Area– Add () # Method to allow user to enter values Dcode, DName, People, Area and Call DenCal () Mehtod– View () # Method to display all the data members also display a message “”High Population”if the Density is more than 8000.Answer:Output is below2 Re Enter Number10 Re Enter Number5 Input = Number3 Input = numberTry and except are used for handling exception in the Pythan code.
Question 25.Write a method in Python and display the prime numbers between 2 to N. Pass as argument to the methods.Answer:
def prime (N) : for a in range (2, N) Prime=1 for I in range (2, a): if a%i= = 0 : Prime = 0 if Prime = = 1: print a OR def prime (N) : for a in range (2, N): for I in range (2, a) : if a%i = = 0: break else : print a OR Any other correct code performing the same
Long Answer Type Questions (6 marks)
Question 1.Aastha wnats to create a program that accepts a string and display the characters in the reversein the same line using a Stack. She has created the following code, help her by completing thedefinitions on the basis of requirements given below:[CBSE SQP 2016]
Class mystack : def inin (self): selfe. mystr= # Accept a string self.mylist= # Convert mystr to a list # Write code to display while removing element from the stack. def display (self) : : :
Answer:
class mystack : def _init_ (self) : self.myster= rawjnput ("Enter the string”) self.mylist = list (self.mystr) def display (self) : x = len (self. mylist) if (x > 0) : for i in range (x) : print self.mylist.pop (), else : print "Stack is empty”
via Blogger https://ift.tt/3kkMk05
0 notes
margdarsanme · 4 years ago
Text
NCERT Class 12 Computer Science Chapter 1 Review of Python
NCERT Class 12 Computer Science Python Solutions for Chapter 1 :: Review of Python
TOPIC-1
Python Basics
Very Short Answer Type Questions(1 mark)
Question 1.Name the Python Library modules which need to be imported to invoke the following functions:
load ()
pow () [CBSE Delhi 2016]
Answer:
pickle
math
Question 2.Name the modules to which the following func-tions belong:
Uniform ()
fabs () [CBSE SQP 2016]
Answer:
random ()
math ()
Question 3.Differentiate between the round() and floor() functions with the help of suitable example.[CBSE Comptt. 2016]Answer:The function round() is used to convert a fractional number into whole as the nearest next whereas the function floor() is used convert to the nearest lower whole number, e.g.,round (5.8) = 6, round (4.1) = 5 and floor (6.9) = 6, floor (5.01) = 5
Short Answer Type Questions (2 marks):
Question 1.Out of the following, find those identifiers, which cannot be used for naming Variables or functions in a Python program:Total * Tax, While, Class, Switch, 3rd Row, finally, Column 31, Total. [CBSE Outside Delhi-2016]Answer:Total * Tax, class, 3rd Row, finally
Question 2.Name the Python Library modules which need to be imported to invoke the follwing functions :
sqrt()
dump() (CBSE Outside Delhi-2016)
Answer:
math
pickle
Question 3.Out of the following, find the identifiers, which cannot be used for naming Variable or Functions in a Python program: [CBSE Delhi 2016]_Cost, Price*Qty, float, switch, Address one, Delete, Number12, doAnswer:Price *Qty, float, Address one, do
Question 4.Out of the following find those identifiers, which can not be used for naming Variable or Functions in a Python Program:Days * Rent, For, A_price, Grand Total, do, 2Clients, Participantl, My cityAnswer:Illegal variables or functions name are as below: Days * Rent, do, 2Clients, For and Grant Total Because of being either keyword or including space or operator or starting with integar.
Question 5.Name the function / method required for [CBSE SQP 2015]
Finding second occurrence of m in madam.
get the position of an item in the list.
Answer:
find
index
Question 6.Which string method is used to implement the following:
To count the number of characters in the string.
To change the first character of the string in capital letter.
To check whether given character is letter or a number.
To change lowercase to uppercase letter.
Change one character into another character. [CBSE TextBook]
Answer:
len(str)
str.capitalize()
ch.isalnum()
str.upper()
str.replace(old,new)
Question 7.What is the difference between input() and raw_input()?Answer:raw_input() takes the input as a string whereas input() basically looks at what the user enters, and automatically determines the correct type. We use the inputQ function when you are expecting an integer from the end-user, and raw_input when you are expecting a string.
Question 8.What are the two ways of output using print()?Answer:Ordinarily, each print statement produces one line of output. You can end the print statement with a trailing ’ to combine the results of multiple print statements into a single line.
Question 9.Why does the expression 2 + 3*4 result in the value 14 and not the value 24?Answer:Operator precedence rules* make the expression to be interpreted as 2 + (3*4) hence the result is 14.
Question 10.How many times will Python execute the code inside the following while loop? You should answer the question without using the interpreter! Justify your answers.
i = 0 while i < 0 and i > 2 : print “Hello ...” i = i+1
Answer:0 times.
Question 11.How many times will Python execute the code inside the following while loop?
i = 1 while i < 10000 and i > 0 and 1: print “ Hello ...” i = 2 * i
Answer:14.
Question 12.Convert the following for loop into while loop, for i in range (1,100):
if i % 4 == 2 : print i, “mod”, 4 , “= 2”
Answer:
i=1 while i < 100: if i % 4 == 2: print i, “mod”, 4 , “= 2” i = i +1
Question 13.Convert the following for loop into while loop.
for i in range(10): for j in range(i): print '$', print"
Answer:
i=0 while i < 10: j=0 while j < i: print '$’ print"
Question 14.Rewrite the following for loop into while loop: [CBSE Text Book]
for a in range(25,500,25): print a
Answer:
a=25 while a < 500: print a a = a + 25
Question 15.Rewrite the following for loop into while loop: [CBSE Text Book]
for a in range(90, 9, -9): print a
Answer:
a = 90 while a > 9: print a a = a-9
Question 16.Convert the following while loop into for loop:
i = 0 while i < 100: if i % 2 == 0: print i, “is even” else: print i, “is odd” i = i + 1
Answer:
for i in range(100): if i % 2 == 0: print i, “is even” else : print i, “is odd”
Question 17.Convert the following while loop into for loop
char = "" print “Press Tab Enter to stop ...” iteration = 0 while not char == “\t” and not iteration > 99: print “Continue?” char = raw_input() iteration+ = 1
Answer:
char = "" print “Press Tab Enter to stop ...” for iteration in range(99): if not char == ‘\t’: print “Continue?” char = raw_input()
Question 18.Rewrite the following while loop into for loop:
i = 10 while i<250: print i i = i+50
Answer:
for i in range(10, 250, 50): print i
Question 19.Rewrite the following while loop into for loop:
i=88 while(i>=8): print i i- = 8
Answer:
for i in range(88, 9, -8) print i
Question 20.Write for statement to print the series 10,20,30, ……., 300Answer:
for i in range(10, 301, 10): print i
Question 21.Write for statement to print the series 105,98,91,… .7Answer:
for i in range(105, 8, -7): print i
Question 22.Write the while loop to print the series: 5,10,15,…100Answer:
i=5 while i <= 100: print i i = i + 5
Question 23.How many times is the following loop executed? [CBSE Text Book]for a in range(100,10,-10):print aAnswer:9 times.
Question 24.How many times is the following loop executed? [CBSE Text Book]
i = 100 while (i<=200): print i i + =20
Answer:6 times
Question 25.State whether the statement is True or False? No matter the underlying data type if values are equal returns true,
char ch1, ch2; if (ch1==ch2) print “Equal”
Answer:True. Two values of same data types can be equal.
Question 26.What are the logical operators of Python?Answer:or, and, not
Question 27.What is the difference between ‘/’ and ‘//’ ?Answer:
// is Integer or Floor division whereas / is normal division (eg) 7.0 // 2 → 3.0 7.0/2 → 3.5
Question 28.How can we import a module in Python?Answer:1. using import
Syntax: import[,,...] Example: import math, cmath
2. using from
Syntax: fromimport[, ,.. ,] Example: . from fib. import fib, fib2.
Question 29.What is the difference between parameters and arguments?Answer:
S.No.ParametersArguments1Values provided in function headerValues provided in function call.2(eg) def area (r):—> r is the parameter(eg) def main() radius = 5.0 area (radius)—> radius is the argument
Question 30.What are default arguments?Answer:Python allowes function arguments to have default values; if the function is called without the argument, the argument gets its default value
Question 31.What are keyword arguments?Answer:If there is a function with many parameters and we want to specify only some of them in function call,then value for such parameters can be provided by using their names instead of the positions. These are called keyword argument.
(eg) def simpleinterest(p, n=2, r=0.6) ' def simpleinterest(p, r=0.2, n=3)
Question 32.What are the advantages of keyword arguments?Answer:It is easier to use since we need not remember the order of the arguments.We can specify the values for only those parameters which we want, and others have default values.
Question 33.What does “in” do?Answer:“in” is a membership operator. It evaluates to true if it finds a variable/string in the specified sequence :Otherwise i+evaluates to false.
(eg) S = “Hello World" if “Hell” in S: print “True” will print True.
Question 34.What does “not in” do?Answer:“not in” is a membership operator. It evaluates to true if it does not finds a variable/stringin the specified sequence. Otherwise it evaluates to false,
(eg) S = “Hello World” if “Hell” not in S: print “False” will print False.
Question 35.What does “slice” do?Answer:The slice[n:m] operator extracts subparts from a string. It doesn’t include the character at index m.
(eg) S = “Hello World” print s[0:4] → Hell
Question 36.What is the use of negative indices in slicing?Answer:Python counts from the end (right) if negative indices are given.
(eg) S = “Hello” print S[:-3] >> He print S[-3:] >> llo
Question 37.Explain find() function?Answer:find (sub[,start[,end]])This function is used to search the first occurrence of the substring in the given string.It returns the index at which the substring starts. It returns -1 if the substring doesn’t occur in the string.
(eg) str = “computer” - str.findf("om”) → 1
Question 38.What are the differences between arrays and lists?Answer:An array holds fixed number of values. List is of variable-length – elements can be dynamically added or removedAn array holds values of a single type. List in Python can hold values of mixed data type.
Question 39.What is the difference between a tuple and a list?Answer:A tuple is immutable whereas a list is a mutable.A tuple cannot be changed whereas a list can be changed internally.A tuple uses parenthess (()) whereas a list uses square brackets ([]).tuple initialization: a = (2, 4, 5)list initialization: a = [2, 4, 5]
Question 40.Carefully observe the following python code and answer the question that follows:x=5def func2():x=3global xx=x+1print xprint xOn execution the above code produces the following output.63Explain the output with respect to the scope of the variables.Answer:Names declared with global keyword have to be referred at the file level. This is because the global scope.If no global statement is being used the variable with the local scope is accessed.Hence, in the above code the statement succeeding the statement global x informs Python to incrementthe global variable xHence, the output is 6 i.e. 5 + 1 which is also the value for global x.When x is reassingned with the value 3 the local x hides the global x and hence 3 printed.(2 marks for explaning the output) (Only 1 mark for explaining global and local namespace.)
Question 41.Explain the two strategies employed by Python for memory allocation. [CBSE SQP 2016]Answer:Pythonuses two strategies for memory allocation-(i) Reference counting(ii) Automatic garbage collectionReference Counting: works by counting the number of times an object is referenced by other in the system.When an object’s reference count reaches zero, Python collects it automatically.Automatic Garbage Collection: Python schedules garbage collection based upon a threshold of object allocations and object deallocations. When the number of allocations minus the number of deallocations are greater that the threshold number, the garbage collector is run and the unused blocks of memory is reclaimed.
TOPIC – 2Writing Python Programs
Question 1.Rewrite the following code in Python after removing all syntax errors(s). Underline each correction done in the code. [CBSE Delhi-2016]for Name in [Amar, Shveta, Parag]if Name [0] = ‘s’:Print (Name)Answer:
for Name in [“_Amar”, ”_Shveta_” , "_Parag_”] : if Name [0] E == ‘S’ : Print (Name)
Question 2.Rewrite the following code is Python after removing all syntax errors(s).Underline each correction done in the code. [CBSE Outside Delhi-2016]for Name in [Ramesh, Suraj, Priya]if Name [0] = ‘S’:Print (Name)Answer:
for Name in [“_Ramesh_”, “_Suraj_” , “_Priya_”] if Name [0] =_=‘S’ : print (Name)
Question 3.What will be the output of the following python code considering the following set of inputs?AMARTHREEA1231200Also, explain the try and except used in the code.Start = 0while True :Try:Number = int (raw input (“Enter Number”))breakexcept valueError : start=start+2print (“Re-enter an integer”)Print (start)Answer:Output:
Enter Number AMAR Re-enter an integer Enter Number THREE Re-enter an integer Enter Number A123 Re-enter an integer Enter Number 12006
Explanation : The code inside try makes sure that the valid number is entered by the user.When any input other an integer is entered, a value error is thrown and it prompts the user to enter another value.
Question 4.Give the output of following with justification. [CBSE SQP 2015]
x = 3 x+ = x-x print x
Answer:Output: 3Working:
x = 3 x = (x+ x-x ):x = 3 + 3 - 3 = 3
Question 5.What will be printed, when following Python code is executed? [CBSE SQP 2015]
class person: def init (self,id): self.id = id arjun = person(150) arjun. diet [‘age’] = 50 print arjun.age + len(arjun. diet )
Justify your answer.Answer:52arjun.age = 50arjun.dict has 2 attributes so length of it is 2. So total = 52.
Question 6.What would be the output of the following code snippets?print 4+9print “4+9”Answer:13 (addition), 49 (concatenation).
Question 7.Highlight the literals in the following programand also predict the output. Mention the types ofvariables in the program.
a=3 b='1' c=a-2 d=a-c e=“Kathy” f=‘went to party.’ g=‘with Sathy’ print a,g,e,f,a,g,“,”,d,g,“,”,c,g,“and his”,e,f
Answer:a, c,d = integerb, e,f,g = stringOutput: 3 with Sathy Kathy, went to party. 3 with Sathy, 2 with Sathy , 1 with Sathy and his Kathy, went to party.
Question 8.What is the result of 4+4/2+2?Answer:4 + (4/2) + 2 = 8.
Question 9.Write the output from the following code: [CBSE Text Book]
x= 10 y = 20 if (x>y): print x+y else: print x-y
Answer:– 10
Question 10.Write the output of the following code:print “Python is an \n interpreted \t Language”Answer:Python is an interpreted Language
Question 11.Write the output from the following code:
s = 0 for I in range(10,2,-2): s+=I print “sum= ",s
Answer:sum= 28
Question 12.Write the output from the following code: [CBSE TextBook]
n = 50 i = 5 s = 0 while i<n: s+ = i i+ = 10 print “i=”,i print “sum=”,s
Answer:
i= 15 i= 25 i= 35 i= 45 i= 55 sum= 125
Question 13.Write the output from the following code: [CBSE TextBook]
n = 50 i = 5 s = 0 while i<n: s+ = i i+ = 10 print “i=”,i print “sum=”,s
Answer:
i= 15 i= 25 i= 35 i= 45 i= 55 sum= 125
Question 14.Observe the following program and answer the question that follows:import randomx = 3N = random, randint (1, x)for 1 in range (N):print 1, ‘#’, 1 + 1a. What is the minimum and maximum number of times the loop will execute?b. Find out, which line of output(s) out of (i) to (iv) will not be expected from the program?i. 0#1ii. 1#2iii. 2#3iv. 3#4Answer:a. Minimum Number = 1Maximum number = 3b. Line iv is not expected to be a part of the output.
Question 15.Observe the following Python code carefully and obtain the output, which will appear on the screen after execution of it. [CBSE SQP 2016]
def Findoutput (): L = "earn" X = " " count = 1 for i in L: if i in ['a', 'e',' i', 'o', 'u']: x = x + 1. Swapcase () else: if (count % 2 ! = 0): x = x + str (len (L[:count])) else: x = x + 1 count = count + 1 print x Findoutput ()
Answer:EA3n
Question 16.Find and write the output of the following Python code:
Number = [9,18,27,36] for N in Numbers: print (N, "#", end = " ") print ()
Answer:
ElementStack of operatorsPostfix Expression1#001#(1#)(1#)2#(1#)(1#2#)1#(2#)(1#2#3#)2#(1#)1#3#(2#)1#2#(3#)1#2#3#
Question 17.What are the possible outcome(s) executed from the following code? Also,specify the maximum and import random. [CBSE Delhi 2016]
PICK=random.randint (0,3) CITY= ["DELHI", "MUMBAI", "CHENNAI", "KOLKATA"]; for I in CITY : for J in range (1, PICK) print (I, end = " ") Print ()
(i)(ii)DELHIDELHIDELHIMUMBAIMUMBAIDELHIMUMBAICHENNAICHENNAIDELHIMUMBAICEHNNAIKOLKATAKOLKATA(iii)(iv)DELHIDELHIMUMBAIMUMBAIMUMBAICHENNAIKOLKATAKOLKATAKOLKATAKOLKATA
Answer:Option (i) and (iii) are possible option (i) onlyPICKER maxval = 3 minval = 0
Question 18.Find and write the output of the following Python code : [CBSE Outside Delhi-2016]
Values = [10,20,30,40] for val in Values: for I in range (1, Val%9): print (I," * ", end= " ") print ()
Answer:
ElementStack of operatorsPostfix Expression1*001*(1.*)(1*)2*0(1*2*)1*(1,*)(1*2*3*)2*(2.*)1*3*01*2*(1.*)1*2*3*(2,* )(3,* )
Question 19.Write the output from the following code:
y = 2000 if (y%4==0): print “Leap Year” else: print “Not leap year”
Answer:Leap Year.
Question 20.What does the following print?
for i in range (1,10): for j in'range (1,10): print i * j, print
Answer:1 2 3 4 5 6 7 8 92 4 6 8 10 12 14 16 183 6 9 12 15 18 21 24 274 8 12 16 20 24 28 32 365 10 15 20 25 30 35 40 456 12 18 24 30 36 42 48 547 14 21 28 35 42 49 56 638 16 24 32 40 48 56 64 729 18 27 36 45 54 63 72 81
Question 21.What will be the output of the following statement? Also, justify the answer.
>> print ‘Radhsa’s dress is pretty’.
Answer:SyntaxError: invalid syntax.The single quote needs to be replaced by V to get the expected output.
Question 22.Give the output of the following statements :
>>> str=‘Honesty is the best policy’ >>> str.replace(‘o’,‘*’)
Answer:‘H*nesty is the best p*licy’.
Question 23.Give the output of the following statements :
>> str=‘Hello Python’ >>> str.istitle()
Answer:True.
Question 24.Give the output of the following statements:
>> str=‘Hello Python’ >>> print str.lstrip(“Hel”)
Answer:Hello Python
Question 25.Write the output for the following codes:
A={10:1000,20:2000,30:3000,40:4000,50:5000} print A.items() print A.keys() print A.values()
Answer:[(40,4000), (10,1000), (20,2000), (50,5000), (30,3000)] [40,10, 20, 50, 30] [4000,1000, 2000, 5000, 3000]
Question 26.Write the output from the following code:
t=(10,20,30,40,50) print len(t)
Answer:5
Question 27.Write the output from the following code:
t=(‘a’,‘b’,‘c’,‘A’,‘B’) print max(t) print min(t)
Answer:‘c’A’
Question 28.Find the output from the following code:
T=(10,30,2,50,5,6,100,65) print max(T) print min(T)
Answer:1002
Question 29.Write the output from the following code:
T1=(10,20,30,40,50) T2 =(10,20,30,40,50) T3 =(100,200,300) cmp(T1, T2) cmp(T2,T3) cmp(T3,T1)
Answer:0-11
Question 30.Write the output from the following code:
T1=(10,20,30,40,50) T2=(100,200,300) T3=T1+T2 print T3
Answer:(10,20,30,40,50,100,200,300)
Question 31.Find the output from the following code:
t=tuple() t = t +(‘Python’,) print t print len(t) t1=(10,20,30) print len(t1)
Answer:(‘Python’,)13
Question 32.Rewrite the following code in Python after remo¬ving all syntax error(s).Underline each correction done in the code.
for student in [Jaya, Priya, Gagan] If Student [0] = ‘S’: print (student)
Answer:for studednt in values [“Jaya”, “Priya”, “Gagan”]:if student [0] = = “S”print (student)
Question 33.Find and write the output of the following Python code:
Values = [11, 22, 33, 44] for V in Values: for NV in range (1, V%10): print (NV, V)
Answer:1, 112,223,334, 44
Question 34.What are the possible outcome(s) executed from the following code? Also, specify the maximum and minimum values that can be assigned to variable SEL.
import random SEL=random. randint (0, 3) ANIMAL = [“DEER”, “Monkey”, “COW”, “Kangaroo”]; for A in ANIMAL: for AAin range (1, SEL): print (A, end =“”) print ()
(i)(ii)(iii)(iv)DEERDEERDEERDEERDEERMONKEYMONKEYDELHIMONKEYMONKEYMONKEYMONKEYCOWCOWDELHIMONKEYCOWCOWKANGAROOKANGAROOKANGAROOKANGAROOKANGAROOKANGAROO
Answer:Maximum value of SEL is 3.The possible output is belowDEERMonkey MonkeyKangaroo Kangaroo KangarooThus (iv) is the correct option.
TOPIC-3Random Functions
Question 1.What are the possible outcome(s) executed from the following code ? Also specify the maximum and minimum values that can be assigned to variable PICKER. [CBSE Outside Delhi-2016]
import random PICKER = random randint (0, 3) COLOR = ["BLUE", "PINK", "GREEN", "RED"]: for I in COLOR : for J in range (1, PICKER): Print (I, end = " ") Print ()
(i)(ii)(iii) (iv)BLUEBLUEPINKSLUEBLUEPINKBLUEPINKPINKGREENPINKPINKGREENBLUEPINKGREENGREENREDGREENGREENREDBLUEPINKGREENREDREDRED
Answer:Option (i) and (iv) are possibleORoption (i) onlyPICKER maxval = 3 minval = 0
Question 2.What are the possible outcome(s) expected from the following python code? Also specifymaximum and minimum value, which we can have. [CBSE SQP 2015]
def main(): p = ‘MY PROGRAM’ i = 0 while p[i] != ‘R’: l = random.randint(0,3) + 5 print p[l],’-’, i += 1
(i) R – P – O – R –(ii) P – O – R – Y –(iii) O -R – A – G –(iv) A- G – R – M –Answer:Minimum value=5Maximum value=8So the only possible values are O, G, R, AOnly option (iii) is possible.
TOPIC-4Correcting The Errors
Question 1.Rewrite the following Python code after removing all syntax error(s). Underline the corrections done.[CBSE SQP 2015]
def main(): r = raw-input(‘enter any radius : ’) a = pi * math.pow(r,2) print “ Area = ” + a
Answer:
def main (): r = raw_input(‘enter any radius : ’) a = pi * math.pow(r,2) print “ Area = ”, a
Question 2.Rectify the error (if any) in the given statements.
>> str=“Hello Python” >>> str[6]=‘S’
Answer:
str[6] = ‘S’ is incorrect ‘str’ object does not support item assignment. str.replace(str[6],‘S’).
Question 3.Find the errors from the following code:T=[a,b,c]print TAnswer:NameError: name ‘a’ is not defined .T=[‘a’,‘b’,‘c’]
Question 4.Find the errors from the following code:for i in 1 to 100:print IAnswer:for i in range (1,100):print i
Question 5.Find the errors from the following code:
i=10 ; while [i<=n]: print i i+=10
Answer:
i=10 n=100 while (i<=n): print i i+=10
Question 6.Find the errors from the following code:
if (a>b) print a: else if (a<b) print b: else print “both are equal”
Answer:
if (a>b) // missing colon print a: else if (a<b) // missing colon // should be elif print b: else // missing colon print “both are equal"
Question 7.Find errors from the following codes:
c=dict() n=input(Enter total number) i=1 while i<=n: a=raw_input(“enter place”) b=raw_input(“enter number”) c[a]=b i=i+1 print “place”,“\t”,“number” for i in c: print i,“\t”,c[a[i]]
Answer:
c=dict() n=input(‘‘Enter total number”) i=1 while i<=n : a=raw_input(“enter place”) b=raw_inputf enter number”) c[a]=b i=i+1 print “place”,“\t”,“number” for i in c: print i,“\t”,c[i]
Question 8.Observe the following class definition and answer the question that follows : [CBSE SQP 2016]
class info: ips=0 def _str_(self): #Function 1 return "Welcome to the Info Systems" def _init_(Self): self. _ Sstemdate= " " self. SystemTime = " " def getinput (self): self . Systemdate = raw_input ("enter data") self , SystemTime = raw_Input ("enter data") Info, incrips () Estaiomethod # Statement 1 def incrips (): Info, ips, "times" I = Info () I. getinput () Print I. SystemTime Print I. _Systemdate # Statement 2
i. Write statement to invoke Function 1.ii. On Executing the above code, Statement 2 is giving an error explain.Answer:i. print Iii. The statement 2 is giving an error because _ Systemdate is a private variable and hence cannot to be printed outside the class.
TOPIC – 5Short Programs
Question 1.Write a program to calculate the area of a rectangle. The program should get the length and breadth ;values from the user and print the area.Answer:
length = input(“Enter length”) breadth = input(“Enter breadth”) print “Area of rectangle =”,length*breadth
Question 2.Write a program to calculate the roots of a quadratic equation.Answer:
import math a = input(“Enter co-efficient of x^2”) b = input(“Enter co-efficient of x”) c = inputfEnter constant term”) d = b*b - 4*a*c if d == 0: print “Roots are real and equal” root1 = root2 = -b / (2*a) elif d > 0: print “Roots are real and distinct” root1 = (- b + math.sqrt(d)) / (2*a) root2 = (-b - math.sqrt(d)) / (2*a) else: print “Roots are imaginary” print “Roots of the quadratic equation are”,root1,“and”,root2
Question 3.Write a program to input any number and to print all the factors of that number.Answer:
n = inputfEnter the number") for i in range(2,n): if n%i == 0: print i,“is a factor of’.n
Question 4.Write a program to input ,.any number and to check whether given number is Armstrong or not.(Armstrong 1,153,etc. 13 =1, 13+53 +33 =153)Answer:
n = inputfEnter the number”) savedn = n sum=0 while n > 0: a = n%10 sum = sum + a*a*a n = n/10 if savedn == sum: print savedn,“is an Armstrong Number” else: print savedn,”is not an Armstrong Number”
Question 5.Write a program to find all the prime numbers up to a given numberAnswer:
n = input("Enter the number”) i = 2 flag = 0 while (i < n): if (n%i)==0: flag = 1 print n,“is composite” break i = i+ 1 if flag ==0 : print n,“is prime”
Question 6.Write a program to convert decimal number to binary.Answer:
i=1 s=0 dec = int ( raw_input(“Enter the decimal to be converted:”)) while dec>0: rem=dec%2 s=s + (i*rem) dec=dec/2 i=i*10 print “The binary of the given number is:”,s raw_input()
Question 7.Write a program to convert binary to decimalAnswer:
binary = raw_input(“Enter the binary string”) decimal=0 for i in range(len(str(binary))): power=len (str (binary)) - (i+1) decimal+=int(str(binary)[i])*(2**power) print decimal
Question 8.Write a program to input two complex numbers and to find sum of the given complex numbers.Answer:
areal = input("Enter real part of first complex number”) aimg = input("Enter imaginary part of first complex number”) breal = input("Enter real part of second complex number”) bimg = input("Enter imaginary part of second complex number”) totreal = areal + breal totimg = aimg + bimg print “Sum of the complex numbers=",totreal, “+i”, totimg
Question 9.Write a program to input two complex numbers and to implement multiplication of the given complex numbers.Answer:
a = input("Enter real part of first complex number”) b = input("Enter imaginary part of first complex number”) c = input("Enter real part of second complex number”) d = input("Enter imaginary part of second complex number”) real= a*c - b*d img= a*d + b*c print “Product of the complex numbers=",real, “+i”,img
Question 10.Write a program to find the sum of all digits of the given number.Answer:
n = inputfEnter the number”) rev=0 while (n>0): a=n%10 sum = sum + a n=n/10 print “Sum of digits=”,sum
Question 11.Write a program to find the reverse of a number.Answer:
n = input("Enter the number”) rev=0 while (n>0): a=n%10 rev=(rev*10)+a n=n/10 print “Reversed number=”,rev
Question 12.Write a program to print the pyramid.12 23 3 34 4 4 45 5 5 5 5Answer:
for i in range(1,6): for j in range(1,i+1): print i, print
Question 13.Write a program to input username and password and to check whether the given username and password are correct or not.Answer:
import string usemame= raw_input(“Enter username”) password = raw_input(“Enter password”) if cmp(username.strip(),“XXX”)== 0: if cmp(password,”123”) == 0: print “Login successful” else: print “Password Incorrect” else: print “Username Incorrect”
Question 14.Write a generator function generatesq () that displays the squareroots of numbers from 100 to nwhere n is passed as an argument.Answer:
import math def generatesq (n) : for i in range (100, n) : yield (math, sqrt (i))
Question 15.Write a method in Python to find and display the prime number between 2 to n.Pass n as argument to the method.Answer:
def prime (N) : for a in range (2, N): for I in range (2, a): if N%i ==0 : break print a OR def prime (N): for a in range (2, N): for I in range (2, a) : if a%1= = 0 : break else : print a
Question 16.Write a program to input username and password and to check whether the given username and password are correct or not.Answer:
import string usemame= raw_input(“Enter username”) password = raw_input(“Enter password”) if cmp(usemame.strip(),“XXX”)== 0: if cmp(password,”123”) == 0: print “Login successful” else: print “Password Incorrect” else: print “Username Incorrect”
Question 17.Which string method is used to implement the following: [CBSE Text Book]
To count the number of characters in the string.
To change the first character of the string in capital letter.
To check whether given character is letter or a number.
To change lowercase to uppercase letter.
Change one character into another character.
Answer:
len(str)
str.title() or str.capitalize()
str.isalpha and str.isdigit()
lower(str[i])
str.replace(char, newchar)
Question 18.Write a program to input any string and to find the number of words in the string.Answer:
str = “Honesty is the best policy” words = str.split() print len(words)
Question 19.Write a program to input n numbers and to insert any number in a particular position.Answer:
n=input(“Enter no. of values") num=[] for i in range (n): number=input(“Enter the number") num.append(number) newno = input(“Enter the number to be inserted”) pos = input(“Enter position”) num.insert(newno,pos) print num
Question 20.Write a program to input n numbers and to search any number from the list.Answer:
n=input(“Enter no. of values”) num=[] flag=0 for i in range (n): number=input(“Enter the number”) num. append(number) search = input(“Enter number to be searched") for i in range(n): if num[i]==search: print search,“found at position”,i flag=1 if flag==0: print search, “not found in list”
Question 21.Write a program to search input any customer name and display customer phone numberif the customer name is exist in the list.Answer:
def printlist(s): i=0 for i in range(len(s)): print i,s[i] i = 0 phonenumbers = [‘9840012345’,‘9840011111’,’ 9845622222’,‘9850012345’,‘9884412345’] flag=0 number = raw_input(“Enter the phone number to be searched") number = number.strip() try: i = phonenumbers.index(number) if i >= 0: flag=1 except ValueError: pass if(flag <>0): print “\nphone number found in Phonebook at index”, i else: print'\iphonenumbernotfoundin phonebook” print “\nPHONEBOOK” printlist(phonenumbers)
Question 22.Write a program to input n numbers and to reverse the set of numbers without using functions.Answer:
n=input(“Enter no. of values”) num=[] flag=0 for i in range (n): number=input(“Enter the number”) num. append(number) j=n-1 for i in range(n): if i<=n/2: num[i],num[j] = num[j],num[i] j=j-1 else: break print num
Question 23.Find and write the output of the following Python code: [CBSE Complementry-2016]
class Client: def init (self, ID = 1, NM=”Noname”) # constructor self.CID = ID self. Name = NM def Allocate (self, changelD, Title) : self.CID = self.CID + Changeld self.Name = Title + self. Name def Display (self) : print (self. CID). "#”, self. Name) C1 = Client () C2 = Client (102) C3 = Client (205, ‘’Fedrick”) C1 . Display () C2 . Display () C3 . Display () C2 . Allocate (4, "Ms.”) C3 .Allocate (2, "Mr.”) C1. Allocate (1, "Mrs.”) C1. Display () C2 . Display () C3 . Display ()
Answer:
CID Name — Fedrick 102 Mr. Fedrick 205 Mrs. Fedrick — Mr. & Mrs. Fedrick
Question 24.What will be the output of the following Python code considering the following set of inputs?
MAYA Your 5 Apples Mine2 412 Also, explain the try and except used in the code. Count = 0 while True : try: Number=int (raw input ("Input a Number :")) break Except valueError : Count=Count + 2 # For later versions of python, raw_input # Should be consider as input
mehtods:– DenCal () # Method to calcualte Density as People/Area– Add () # Method to allow user to enter values Dcode, DName, People, Area and Call DenCal () Mehtod– View () # Method to display all the data members also display a message “”High Population”if the Density is more than 8000.Answer:Output is below2 Re Enter Number10 Re Enter Number5 Input = Number3 Input = numberTry and except are used for handling exception in the Pythan code.
Question 25.Write a method in Python and display the prime numbers between 2 to N. Pass as argument to the methods.Answer:
def prime (N) : for a in range (2, N) Prime=1 for I in range (2, a): if a%i= = 0 : Prime = 0 if Prime = = 1: print a OR def prime (N) : for a in range (2, N): for I in range (2, a) : if a%i = = 0: break else : print a OR Any other correct code performing the same
Long Answer Type Questions (6 marks)
Question 1.Aastha wnats to create a program that accepts a string and display the characters in the reversein the same line using a Stack. She has created the following code, help her by completing thedefinitions on the basis of requirements given below:[CBSE SQP 2016]
Class mystack : def inin (self): selfe. mystr= # Accept a string self.mylist= # Convert mystr to a list # Write code to display while removing element from the stack. def display (self) : : :
Answer:
class mystack : def _init_ (self) : self.myster= rawjnput ("Enter the string”) self.mylist = list (self.mystr) def display (self) : x = len (self. mylist) if (x > 0) : for i in range (x) : print self.mylist.pop (), else : print "Stack is empty���
from Blogger http://www.margdarsan.com/2020/09/ncert-class-12-computer-science-chapter_22.html
0 notes