Il 0% ha trovato utile questo documento (0 voti)
32 visualizzazioni23 pagine

Cs Viva Voce

Il documento contiene una serie di domande e risposte relative a Python, coprendo argomenti come tipi di dati, gestione degli errori, funzioni e strutture di controllo. Viene discusso il concetto di mutabilità, la differenza tra liste e tuple, e l'uso di docstring per la documentazione. Inoltre, si affrontano le funzioni built-in come help() e dir(), e si spiegano le differenze tra variabili locali e globali.

Caricato da

arpityadav0076
Copyright
© © All Rights Reserved
Per noi i diritti sui contenuti sono una cosa seria. Se sospetti che questo contenuto sia tuo, rivendicalo qui.
Formati disponibili
Scarica in formato PDF o leggi online su Scribd
Il 0% ha trovato utile questo documento (0 voti)
32 visualizzazioni23 pagine

Cs Viva Voce

Il documento contiene una serie di domande e risposte relative a Python, coprendo argomenti come tipi di dati, gestione degli errori, funzioni e strutture di controllo. Viene discusso il concetto di mutabilità, la differenza tra liste e tuple, e l'uso di docstring per la documentazione. Inoltre, si affrontano le funzioni built-in come help() e dir(), e si spiegano le differenze tra variabili locali e globali.

Caricato da

arpityadav0076
Copyright
© © All Rights Reserved
Per noi i diritti sui contenuti sono una cosa seria. Se sospetti che questo contenuto sia tuo, rivendicalo qui.
Formati disponibili
Scarica in formato PDF o leggi online su Scribd
Sei sulla pagina 1/ 23
Viva VV —_Yoce Questions 1, Hows Python translated to its objet ini code ? 01 g fer e Sa My ‘i terete [2nauage That is, the code executes line by an » e © code line 'y line int " into machine |, Aye © an intermediate language and Ee ta one ar : then “xecuted, So, if error occurs in one line of the following lines of the cod. erore Tesuming the conversion and execution of 2. Which built-in types does Python provide ? Ans. Python's built in types are : Numbers and complex numbers), Strings, Lists, Sets, 3, [Name mutable and immutable built-in data types of Python. Ans, Python's Mutable built-in types are : Lists, Sets, Dictionaries, (integers, Booleans, floating point numbers Tuples, Dictionaries, Python's Immutable built-in types are : Strings, Tuples, Numbers, 4. What is case sensitivity ? Is Python case-sensitive ? if it treats uppercase letters and lowercase letters ike name, Name and NAME are different in a case Python is a case sensitive language. 5. (What iS pass statement of Python ? Ans. Pass is a no-operation Python statement. It is written whe demands a statement but logic demands no-action. 6. (What is the difference between list and tuple ? Ans. Lists and tuples, both are sequence of elements but the difference between them is that lists are mutable types while tuples are not. 7. What is slicing in Python ? Ans. It is the selecting of a sub-sequence or a sequence of elements contained in Sequences like list, tuple, strings etc. 8, (AMaRatinetpiarese of Gomiments and indentation in a program ? Ans, Comments let one insert programmer related information, Indentation makes the program readable and presentable. re the syntax —————=<—————— 322 TH COMPUTER SCIENCE (Python) - Xi! MOVE FAST WITH COMPUTER SCIENCE (PINOT) — eee Tere 9, What is docstring in Python ? Ans. A docstring is a Python. documentation string. Docstrings are Used documenting Python functions, modules and classes. Docstrings are Witen triple-quoted strings. Docstrings written in program code are ignored by the py, interpreter. 10. What is the purpose of docstrings in Python ? ‘Ans. In Python, the docstring is a triple quoted string used for documentat purpose, written in program code ~ in Python functions, modules, classes, Der, given in docstrings are listed through help( 11. Ina program, both docstrings ‘and comments are not processed by the Python interpreter, 1 do docstrings and comments mean the same thing? If not, how are docstrings different fr comments ? ‘Ans. Both docstrings and comments are ignored by the interpreter, ic, these a not considered for execution purpose. In that sense both comments and docstrings a the same. BUT docstrings are not just comments. The information given in docstrings treated as documentation for the program/module, which we can access using help( ) function. 12. What is the usage of help( ) and dir( ) function in Python? ‘Ans. Both the functions help( ) and dir( ), are accessible from the Python interpreter and are used for viewing a consolidated dump of built-in functions. > The help() function is used to display the documentation text and also faciita ‘us to see the help related to modules, keywords, and attributes. > The dir() function is used to display the defined symbols. 13. What is negative index in Python ? ‘Ans, Python sequences can have indexes of both types : positive and negative, Wi positive indexes begin from 0 for the first element and go till size-1 for the last elemen the negative index is a backward indexing where -1 is for the last element and it mov backwards with -size index for the first element. List Elements’ two way indexing Lst = [47, True, “good”, 4.59] 14, What does [:: -1} do? Ans. [:: -1] is used to reverse the order of an array or a sequence. For example : >>> list =[1, 2, ,3, 4, 5] WA VOCE Questions 323 pantsaxeversed copy of ordered dat, a or list remains Unchanged, *Utures stich ay an array or a list, oe of dtal-2) from the tat at a FE = 2 (negative 2° indeyy «#08 93/0) . Ass 'ndex) index, ig and ; is index is 3 in give. q index f t present at this index is 3 in given list. So, the poids! Output will be 3, into an int in Python 2 i‘ aon string contains only numeric, ‘al characters we se int() function, however, we cannot conve sig integer in Python. ee peti convert number to a string 2 fl ‘ans. To convert a number into a string, we can use the at or hexadecimal representation, we can use the inby ‘of I/ operator in Python 2 Ans. The // operator is a floor division Operator. It gives the integer quotient reulting from the division of two numbers While discarding the remainder or fractional part. flow do you check whether the two variables are B ‘Ans. In Python, we have an ‘Operator ¢; satiables are pointing to the same object, Fo >>> a= “Computer” »>c=a mais True We can confirm this by checkin; foris to return True, both objects >» ida) 47173368 >>> id(c) 47173368 Wak ie aijerence between deep and shallow copy 2 ___ Ans. Shallow copy just creates a new label Separate memory holdin; Sequence are reflected i feo the right. The can convert it into an integer Tt alphabetic and alphanumeric inbuilt function str( ). For uilt function oct( ) or hex( ) nS Pointing to the same object in Python ? alled ‘is’ , which returns true if the two r example, 8 the id’s (memory address) of both these objects. must be pointing to same memory address. for a sequence or object. It does not ig duplicate copy of elements. Changes made in original in shallow copy. Be ==P©OPy creates a separate memory area and then creates labels foreach ele lus deep copy is also called the true copy. Changes made in ori Sequence are not reflected in deep copy. ment ginal “end” argument in print() in Python? i line in the end, ie, the By default the print( ) function always prints a newl ; ‘ Output will oe on the next line (default behaviour). To seem Viour, i ion accepts an optional parameter known as the is “ eo eee the end character in a print statement ur choice using this parameter. 324 MOVE FAST WITH COMPUTER SCIENCE (Python) — Xi So if we change the end’s value as space then space will ‘be printed at the end g print()’s output and next output will continue in the same line. For example, print("My") print ("world") will give output as My World While the code print(“My”, end=¢? ) print (“world”) will give output as My World 22. What is for-else and while-else in Python ? Ans. Python provides an interesting way of handling loops by providing a provisi to write else block in case the loop is not satisfying the condition. So, else clause of a | can be thought of as the false-part of the while loop i.,, it gets executed when the while loop’s condition is false. For the for loop, it executes when for loop ends normally. 23. How do you programmatically know the version of Python you are using ? Ans. The version property under sys module will give the version of Python tha we are using. >>> import sys >>> sys.version 24. What is the role of len( ) function in Python ? ‘Ans. The len( ) determines the length of an a sequence, e.g., for a string “Ms world”, the len() would yield the result as 8 >>> string = "My world” >>> len(string) 8 | 25. ‘What is the role of chr( ) function in Python? Ans. The chr() returns the string storing a character whose Unicode value is to it in integer form. For example, the chr(97) will return the string ‘a’. >>> chr(98) VIVA VOCE QUESTIONS 325 7 What is a tuple in Python ? ‘Ans. A tuple is a sequence or a collection type data structure in Python which is immutable. The elements of tuples are enclosed in parentheses, ¢.8-, T1= (3, 5, 7,9) The tuples are immutable, i.e., their elements cannot be changed in place. 2B. What is a dictionary in Python ? ‘Ans. A dictionary is a data structure known as an associative array in Python which stores a collection of objects in the form of key:value pairs. The collection is a set of keys having a single associated value. A Dictionary is also known as a hash, a map, or a hashmap in other programming languages. 9, (How will you remove the last object from a list 2 Ans. Using the index -1, we can access the last element of a list. Thus, in a list namely mylist, following code list.pop(obj = mylist[-1]) will remove and return last element fromthe list. 30. {Differentiate between append( ) and extend( ) methods. Ans. Both append( ) and extend( ) methods are the methods of lists. Both these methods add the elements at the end of the list. But append( ) adds single element, while extend( ) can add a list of elements, i.e., append(element) ~ adds the given element at the end of the list which has called this method. extend(another-list) ~ adds the elements of another-list at the end of the list which is called the extend method. 31. ‘What is Index Out of Range error ? ‘Ans, When the value passed to the index operator is greater than the actual size of the tuple or list, Index Out of Range error is thrown by Python. >>> a= [11,21,31,41]#ais alist >>> a[3] a1 >>> a[4] Traceback (most recent call last): IndexError: list index out of range >>>b=(1,3,5) #bisatuple >>> b[4] Traceback (most recent call last): IndexError: tuple index out of range 326 MOVE FAST WITH COMPUTER SCIENCE (Python) ~ Xil 32. Consider the given Python code fragment : A = 15, 20, 25 In the above assignment operation, what is the data type of ‘A’ ? Ans. The data type of A is tuple, because when we assign a BroUup Of com, separated values to a single name, Python creates a tuple out of it. This type assignment is called “Tuple Packing”. 33. Consider the below given Python code fragment. >>> A= 101, 202, 303, 404 >>> a,b,c, d=A What is the value assigned to the variable d ? Ans. 404 34. Why is following code giving error (TypeError)? What could be the reason ? >>>a, b,c, d=R Ans. For the given statement to work, R must be a sequence or iterable with variables in it, otherwise (e.g,, if R is an integer or a float value) the above statemen will produce error. 35. The previous question's assigning tuple elements to individual variables what is this type assignment called ? Ans. This type of assignment is called ‘Tuple Unpacking’. 36. (What is the use of the dictionary in Python ? Ans. A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated (or mapped) to a value. Thus, to store values that come in pairs and are associated with one another, dictionaries are used. 37. “How do you add elements to a dictionary in Python ? Ans. We can add elements by modifying the dictionary with a fresh key and then set the value to it. 38. How do you get all keys from a Python dictionary ? Ans, To get all keys from a dictionary, we can use keys( ) method with the dictionary name. 39. How do you get all values from a Python dictionary ? Ans. To get all values from a dictionary, we can use values( ) method with the dictionary name. 40. How do you delete elements ofa dictionary in Python? Ans. There are two ways of doing this : (i) by using the del( ) method. (ii) by use is the pop( ) function, _ ier ere ea en VIVA VOCE QUESTIONS 327 |p, Differentiate betveen a run-time error and syntax error. Give one example of each. ' Ans. A run-time errors that occurs during execution of a program. The compilation of the program 2 not affected with it. For example, ‘File could not be opened’ ‘Not enough memory available’ are run time errors, A Syntax error is that when statements are wrongly written violating rules of the programming language. For example MAX + 2 = DMAX is a syntax error as an expression can not appear on the left side of an assignment operator. 43. Name some standard Python errors that may occur. Ans. TypeError Occurs when the expected type doesn’t match with the given type of a variable. Valuetrror When an expected value is not given- if you are expecting 4 elements in a list and you gave 2. NameError Occurs when trying to access a variable or a function that is not defined. IndexError Accessing an invalid index of a sequence will throw an IndexError. KeyError When an invalid key is used to access a value in the dictionary. "44, Is it mandatory for a Python function to return a value ? \ Ans. It is not at all necessary for a function to return any value. 45. The void functions are non-returning functions, i.e. they do not return a value to their caller. a void function intimate its caller that is returning no value? Ans. The void functions return a legal empty/missing-value object, None, to their caller to signify it. 46. What are different ways of argument matching in Python functions? ‘Ans. In python functions, the arguments can be matched in these ways : = Positional matching. It is normal way of matching arguments wherein arguments are matched left to right, ie, arguments are matched by their position or order of placement. = Keyword/named argument matching. In this way of argument matching, arguments are matched by the argument name, irrespective of their position in function call statement. > Default argument matching. This type of argument matching takes place only ifthe function call passes fewer values that the required parameters. In such a case, the missing arguments get the default values already defined in function 8 MOVE FAST WITH COMPUTER SCIENCE (Python) ~ Xil Ans. Normal argument : positional matching for argumer Keyword arguments : both arguments are matched names. Function | Normal argument : name will be matched any positional or named argument. Parameter a, if given in function call, will be mat. any by positional or named argument, but if ski default argument matching, will be performed. It will cause error as positional arguments must follow keyword arguments, 48. What is the name of function? Ans. Python names the top level segment as_main_. top level segment in a program, i, the segment which is not part of 49. In a program, if there are five different functions defined, wherefrom Python will s executing ? Ans. Python always starts the execution of a program from the top level segm named as _main__, irrespective of number of functions defined in the program, 50. EE defined in a program, but not called through _main__ section, will it i 2 Ans. A function defined but not invoked (directly or indirectly) from _ main. will never be executed. In order for a function to be called, it must be called either directly or indi (when its caller is called through _main__and then its caller calls it) from _main segment. 51. Cana function have multiple return statements in it ? Ans. Yes, a function can have multiple return statements in it. 52. Cana Python function return multiple values? Ans. Yes, a Python function can retui mm multiple values by giving comma separat values in the return statement., eg., returna,b, c,d 5? _ Ans, The functions returning some legal values are called fruitful functions void functions, the functions not returning any legal value are called non-fruit 329 a —_— Ans. A variable define, A : 8 function j it has local scope. A varigty,° {Pelion ig locally available to the function and hence le defined across all parts of a program ang ith, seh side all functions ig globally available pe, BS. Ja which order does Python resolve q Scope 'd inside "8 global scop name when s. Python resolves ? accessed 2 : f 1 ees “sed as per LEGB order (i) It first looks am (i) If not found ronment, environment, then it looks for the name in its enclosing, (iii) If not found in enclosing s ‘ environment, 'B Scope, then it looks for the name in its global (iv) If not found in global Scope, tl i environment, Pe then it looks for the n, 57. What are modules in Python > Ans. The Python Modules definitions. A file containing module name would be abc. We use modules to break down large organized files. Furthermore, modules provi 58. How do you import modules in Python? Ans, We can import the definitions inside a module to another module by using the import command. refer to a file co ntaining Python statements and function Python code, for eg., abe.py, is called a module and its Programs into small manageable and ide reusability of code. To import a module namely abe, we can t >>> import abc 59. Whal’s the difference between “import module” and “fro Ans. The import statement, e.g, 'ype the following : mt module import *” statements? import sys creates a new namespace by the name “ function/definition defined in it, name>, sys” into your module and to access each of the you need to use qualified name as sys. import command ? felts from module import command adds all the names/def current namespace, any similar name will simply get overwritten 61. What are Python packages ? Ans. Python packages are namespaces 62. Which file must added to directory structure importable package ? Ans. __init__.py 63. What is the difference between “r” and “r+” file modes ? Ans. The “r’ mode opens a file beginning of the file. This is the def ane “r+” mode opens a file for both reading and ‘writing. The file pointer placed a the beginning of the file. initions in, 4 containing multiple modules, Of your module files in order to make it for reading only. The file pointer is placed at ti ault mode, 64. What is the difference between “w” and “w+" file modes? 55. What is the difference between “q” a” and “at” file modes ? Ans. The “a” mode opens a file for appending. The file file if the file exists. That is, the file is in the append mode. If the file does not exist, if creates a new file for writing, The “at” mode opens a file for both appending and reading. The file pointer is at th end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing, °6. What are common file processing modes supported by Python 2 Ans. Python provides three modes to open files. The read-only, write-only, tead-write and append mode. ‘v is used to open a file in Tead-only mode, ‘w’ is used to Open a file in write-only mode, ‘rw’ is used to open in reading and write mode, ‘a’ is used to open a file in append mode. If the mode is not specified, by default file opens in read-only mode. Opens a file for reading. It is the default mode. Opens a file for writing, If the file contains data, data would be lost. Otherwise a new file is created, Opens a file for reading, write mode. It means updating mode Opens for writing, append to the end of the fil, ifthe file exists. Y VIVA VOCE QUESTIONS 331 i file contains only one line and the file is read using readline( ) function in one program g. readlines( ) in another program? What would be the difference in two programs? (@ a= open(“sanple. txt”) .readline() © \ ‘Ans. The readline( ) will read the line of text from file and return the result in form | _, ofastring while readlines( ) will read the line of text from the file and return the result Nin the form of alist. \ tbe writen in file is aoailable in the form of alist, which function would you use 10 ite it into a file? Ans. writelines() print (type(a)) a= open("sample.txt") .readlines() print(type(a)) 69, Ifdata to be written in a file is available in the form ofa string, which function would you use to write it into a file? Ans. bl write() ! ws m an, Which Command will you use Yo read “n” number of Characters from a file using the file object sim? Ans. id .read(n) ling 71. Which command will you use to read the entire contents of a file as a string using the file abject ? a Ans. bi .read() 72, Which’ command will you use to read the next line of a file using the file object ? Ans. .readline() 73. Which command will you use to read the remaining lines ofa file using the file object ? Ans. .readlines() 4. é following are the file modes of both writing and reading in Python files ? “ @) w+ ()w (0) we (@) w+ Ans. wb+ and w+ modes “w+” opens a text file for both writing and reading. It overwrites the existing file if _ the file exists. If the file does not exist, it creates a new file for reading and writing, “wb” opens a file for both writing and reading in binary format, overwrites the file if the file exists. If the file does not exist, it creates a new file for reading and 332 75. 76. 81. Ye 85. bie : . What is pickling 2 . What is unpickling 2 ' Which pickle module function allows you to perform the pickling process ? . Which pickle module function allows you to perform the unpickling process ? . What are delimiters in the context of csv files ? MOVE FAST WITH COMPUTER SCIENCE (Python) ~ Xil What is the difference between r+ and w+ modes ? Ans, In mode r+, the file pointer is initially placed at the be, mode w+, the pointer is at the end of the file, when. opened. What are two forms of text files ? Ans. The text files are of following types : (i) Regular Text files. These are the text files whi as typed. Here the newline character ends a place. i) Delimited Text files. In these text files, the values, i.e., after each value, Binning ofthe file ang ch store the text in the same line and the text translations tj a specific character is stored to separg &8, a tab or a comma after every value Ans. It is the process of convertin, ig Python object hierarchy into a byte stream that it can be written into a binary fil le. Ans. Unpickling is the inverse of Picklin (Pickled) file, is converted into a replica of the original object, 1g where a byte stream stored in a bin, mn object hierarchy. Unpickling produces the ex Ans. pickle.dump( ) function. Ans. pickle.load( ) function. What are csv files ? Ans. A CSV file (Comma Sey tabular data. As the name su; value, but other than comm: Are csv files the text files ? Ans. Yes, All CSV files are plain text files wherei in different data items stored with Separator/delimiter character embedded in between. parated Values) is a type of plain text file that hol iggests, CSVs generally use commas to separate each dal ‘a, it supports other separators too. Ans. In csv files, the character or symbol used to separate the data items is called delimiter, which is mostly a comma. However, Commas aren’t the only way separate data ; other delimiters could be a tab (\b, colon (: ), or semi-colon ( ; ). What are tso files? Are they type of csv files ? Ans. When a tab character is used to se TSV files (Tab Separated Values files), Yes, TSV files are a type of CSV files where the delimiter used is the tab character. WO iar oes ton provide ous and wor whee fs ? Ans. The csv module/library. parate the values stored, these are call VIVA VOCE QUESTIONS 333 ? ina program, if a function calls itself (whether directly oF indirectly), it is ¢ recursion. And the function calling itself is called recursive function ¢.8 ae jre two examples of recursion : jo i def AC)? (ii) def BC): AC) c() def C() BC) aan secs and recursive case? What is their role in a recursive programm? Aa Ina recursive solution, the Base cases are predetermined solutions for the aamplest versions of the problem : if the given problem is a base case, no further omputation is necessary to get the result. ‘The recursi recursive step iS aset of rules that eventually reduces all versi ase cases when applied repeatedly. ve case is the one that calls the function again with a new set of values. ions of the problem to one of the 3. Wg base case so important in a recursive function ? ‘Ans. The base case, in a recursive case, represents a pre-known case whose solution is also preknown. This case is very important because upon reac! recursive function occurs as base case does not invol fetus a pre-known result, In the absence of base case, endlessly. Therefore, the execution of base case is necessary for th recursive function. 5. Wiken does infinite recursion occur ? ‘Ans. Infinite recursion is when a recursive function executes itself again and again, endlessly. This happens when either the base case is missing or it is not reachable. |. Compare iteration and recursion. ‘Ans. In iteration, the code is executed repeatedly using the same memory space. That is, the memory space allocated once, is used for each pass of the loop. (On the other hand in recursion, since it involves function call at each step, fresh memory is allocated for each recursive call. For this reason i.e., because of function call overheads, the recursive function runs slower than its iterative counterpart. . When would a recursive solution make more sense than iterative solution? ‘Ans. Recursion is a way of arriving at a solution by breaking down the input into smaller and smaller pieces until it can no longer be broken down. The final output is calculated by putting together the output of these calls with the “smaller” inputs, Ifthe input of a question consists of sub-problems where each of the sub-problem can be solved using the same logic with a different value, then, it’s a good indication that recursion is needed. (OUR HPaHRD and PeeUrSive solutions, which one is slowerifaster and why ? ie: Pere ; ‘Ans, Out of the two, the iterative version is faster comparatively. The iterative works with same memory every time while recursive version has to call a new for every new value. This additional function call overheads make its hing at base case, the termination of ke the function again, rather it the recursive function executes e termination of the 4 MOVE FAST WITH COMPUTER SCIENCE (Python) ~ Xil 93. What is an algorithm ? Ans. An algorithm is any well-defined computational procedure which aim, find a solution of a given problem, An algorithm takes some values as input Produces some result as output. An algorithm is thus a sequence of computati steps that transform the input into the output. 4. What is a Stack ? Ans. Stack is a linear data structure which the order LIFO (Last In First Out) FILO (First In Last Out) for accessing elements. - Name some common applications of stacks ? Ans. Common Applications of Stacks : > Infix to Postfix Conversion using Stack > Evaluation of Postfix Expression > Reverse a String using Stack = Implement two stacks in an array = Check for balanced parentheses in an expression 96. What is a Queue ? Ans. Queue is a linear structure which follows the order is First In First Out (FIF to access elements. 97. Name some common applications of queues ? Ans. Common Applications of queues : > First come first served queues/lines > Resource sharing among multiple consumers = Using shared printer with multiple computers ™ Call center phone system attending multiple calls waiting/on-hold > Airports sharing a runway for flights in waiting > CPU being shared among jobs having similar priority 98. Describe the similarities and differences between queues and stacks. Ans. Similarities : 1. Both queues and stacks are special cases of linear lists. 2. Both can be implemented as arrays or linked lists. Differences : 1. A stack is a LIFO list, a queue is a FIFO list. 2. There are no variations of stack, a queue, however, may be circular deque. 99. What is a network? i Ans. A network is a set of devices that are connected by a physical link or two me “more networks are connected by one or more nodes, Example of a network is . The Internet connects the millions of people across the world.

Potrebbero piacerti anche