├── Books-to-read.md ├── Interview-Questions.md └── README.md /Books-to-read.md: -------------------------------------------------------------------------------- 1 | ## Fluent Python: 2 | - ### List, Tuple,sets, dict, text vs bytes, First Class Functions, 3 | - ### Adv [Design pattern, function decorator and closures] 4 | - ### Obj & Classes: Mutability, References, Vector class, overriding class, overloading 5 | - ### Adv [Slicing, Hashing] 6 | - ### Interfaces: Python ABC library, digs, monkey patch 7 | - ### Control flow: Coroutines, Concurrency: Futures, Asyncio, 8 | - ### Adv[Dynamic Attributes, Attributes Descriptors, Metaprogramming] 9 | 10 | ## Machine Learning 11 | - ### Introduction to Machine Learning with Python, Oreilly 12 | - ### Machine Learning with Python Cookbook, Oreilly 13 | - ### Hands on Machine Learning with Scikit-Learn and Tensorflow, Oreilly 14 | 15 | ## Deep Learning 16 | - ### Deep Learning with Python, Manning 17 | - ### Python Deep Learning Projects, Packt Pub. 18 | - ### Deep Learning Cookbook, Oreilly 19 | -------------------------------------------------------------------------------- /Interview-Questions.md: -------------------------------------------------------------------------------- 1 | #### Why was the language called as Python? 2 | At the same time he began implementing Python, Guido van Rossum was also reading the published scripts from "Monty Python's Flying Circus" (a BBC comedy series from the seventies). 3 | 4 | 5 | **What is Python particularly good for? When is using Python the “right choice” for a project?** 6 | 7 | Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages. 8 | 9 | Python is a high-level general-purpose programming language that can be applied to many different classes of problems. 10 | 11 | The language comes with a large standard library that covers areas such as string processing like regular expressions, Unicode, calculating differences between files, Internet protocols like HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI programming, software engineering like unit testing, logging, profiling, parsing Python code, and operating system interfaces like system calls, file systems, TCP/IP sockets. 12 | 13 | Although likes and dislikes are highly personal, a developer who is “worth his or her salt” will highlight features of the Python language that are generally considered advantageous (which also helps answer the question of what Python is “particularly good for". Some of the more common valid answers to this question include: 14 | 15 | - Ease of use and ease of refactoring, thanks to the flexibility of Python’s syntax, which makes it especially useful for rapid prototyping. 16 | - More compact code, thanks again to Python’s syntax, along with a wealth of functionally-rich Python libraries (distributed freely with most Python language implementations). 17 | - A dynamically-typed and strongly-typed language, offering the rare combination of code flexibility while at the same time avoiding pesky implicit-type-conversion bugs. 18 | - It’s free and open source! Need we say more? 19 | 20 | With regard to the question of when using Python is the “right choice” for a project, the complete answer also depends on a number of issues orthogonal to the language itself, such as prior technology investment, skill set of the team, and so on. Although the question as stated above implies interest in a strictly technical answer, a developer who will raise these additional issues in an interview will always “score more points” with me since it indicates an awareness of, and sensitivity to, the “bigger picture” (i.e., beyond just the technology being employed). Conversely, a response that Python is always the right choice is a clear sign of an unsophisticated developer. 21 | 22 | #### Why Python is not that much of popular, when compared to other programming languages? 23 | 24 | Python is not so useful in web environment where the user interface is the browser. Hence, lot of people are using PHP for different design goals. Google is tightly connected with python as they make searching algorithms. 25 | 26 | #### What are the advantage and disadvantage of Python programming language? 27 | 28 | Python is more like java and bit cumbersome, but it leads to a better design. Python is an interpreted language, high level programming, pure object-oriented, high performance server side scripting language. 29 | 30 | It is not best for mobile application. Due to interpreter its execution speed is not up to mark as compared to compiler. 31 | 32 | #### What are some drawbacks of the Python language? 33 | 34 | For starters, if you know a language well, you know its drawbacks, so responses such as “there’s nothing I don’t like about it” or “it has no drawbacks” are very telling indeed. 35 | 36 | The two most common valid answers to this question (by no means intended as an exhaustive list) are: 37 | - The Global Interpreter Lock (GIL). CPython (the most common Python implementation) is not fully thread safe. In order to support multi-threaded Python programs, CPython provides a global lock that must be held by the current thread before it can safely access Python objects. As a result, no matter how many threads or processors are present, only one thread is ever being executed at any given time. In comparison, it is worth noting that the PyPy implementation discussed earlier in this article provides a stackless mode that supports micro-threads for massive concurrency. 38 | - Execution speed. Python can be slower than compiled languages since it is interpreted. (Well, sort of. See our earlier discussion on this topic.) 39 | 40 | 41 | #### We know Python is all the rage these days. But to be truly accepting of a great technology, you must know its pitfalls as well. Would you like to talk about this? 42 | 43 | Of course. To be truly yourself, you must be accepting of your flaws. Only then can you move forward to work on them. Python has its flaws too: 44 | 45 | Python’s interpreted nature imposes a speed penalty on it. While Python is great for a lot of things, it is weak in mobile computing, and in browsers. 46 | 47 | Being dynamically-typed, Python uses duck-typing (If it looks like a duck, it must be a duck). This can raise runtime errors. 48 | 49 | Python has underdeveloped database access layers. This renders it a less-than-perfect choice for huge database applications. 50 | 51 | And even after these pitfalls, of course. Being easy makes it addictive. Once a Python-coder, always a Python coder. 52 | 53 | So while it has problems, it is also a wonderful tool for a lot of things. 54 | 55 | **What are the key differences between Python 2 and 3?** 56 | ``` 57 | Division operator 58 | `print` function 59 | Unicode 60 | xrange 61 | Error Handling 62 | `_future_` module 63 | ``` 64 | 65 | Although Python 2 is formally considered legacy at this point,its use is still widespread enough that is important for a developer to recognize the differences between Python 2 and 3. 66 | 67 | - Here are some of the key differences that a developer should be aware of: 68 | 69 | - Text and Data instead of Unicode and 8-bit strings. Python 3.0 uses the concepts of text and (binary) data instead of Unicode strings and 8-bit strings. The biggest ramification of this is that any attempt to mix text and data in Python 3.0 raises a TypeError (to combine the two safely, you must decode bytes or encode Unicode, but you need to know the proper encoding, e.g. UTF-8) 70 | 71 | - This addresses a longstanding pitfall for naïve Python programmers. In Python 2, mixing Unicode and 8-bit data would work if the string happened to contain only 7-bit (ASCII) bytes, but you would get UnicodeDecodeError if it contained non-ASCII values. Moreover, the exception would happen at the combination point, not at the point at which the non-ASCII characters were put into the str object. This behavior was a common source of confusion and consternation for neophyte Python programmers. 72 | 73 | - `print` function. The print statement has been replaced with a print() function 74 | 75 | - `xrange` – buh-bye. xrange() no longer exists (range() now behaves like xrange() used to behave, except it works with values of arbitrary size) 76 | 77 | - API changes: 78 | - `zip()`, `map()` and `filter()` all now return iterators instead of lists. 79 | - `dict.keys()`, `dict.items()` and `dict.values()` now return 'views' instead of lists. 80 | - `dict.iterkeys()`, `dict.iteritems()` and `dict.itervalues()` are no longer supported. 81 | - Comparison operators. The ordering comparison operators (<, <=, >=, >) now raise a TypeError exception when the operands don’t have a meaningful natural ordering. Some examples of the ramifications of this include: 82 | - Expressions like 1 < '', 0 > None or len <= len are no longer valid 83 | - None < None now raises a TypeError instead of returning False 84 | - Sorting a heterogeneous list no longer makes sense. 85 | - All the elements must be comparable to each other 86 | 87 | #### What are some key differences to bear in mind when coding in Python vs. Java? 88 | 89 | Disclaimer #1. The differences between Java and Python are numerous and would likely be a topic worthy of its own (lengthy) post. Below is just a brief sampling of some key differences between the two languages. 90 | 91 | Disclaimer #2. The intent here is not to launch into a religious battle over the merits of Python vs. Java (as much fun as that might be!). Rather, the question is really just geared at seeing how well the developer understands some practical differences between the two languages. The list below therefore deliberately avoids discussing the arguable advantages of Python over Java from a programming productivity perspective. 92 | 93 | - With the above two disclaimers in mind, here is a sampling of some key differences to bear in mind when coding in Python vs. Java: 94 | 95 | - Dynamic vs static typing: One of the biggest differences between the two languages is that Java is restricted to static typing whereas Python supports dynamic typing of variables. 96 | 97 | - Static vs. class methods: A static method in Java does not translate to a Python class method. 98 | - In Python, calling a class method involves an additional 99 | memory allocation that calling a static method or function 100 | does not. 101 | - In Java, dotted names (e.g., foo.bar.method) are looked 102 | up by the compiler, so at runtime it really doesn’t matter 103 | how many of them you have. In Python, however, the lookups 104 | occur at runtime, so “each dot counts”. 105 | 106 | - Method overloading: Whereas Java requires explicit specification of multiple same-named functions with different signatures, the same can be accomplished in Python with a single function that includes optional arguments with default values if not specified by the caller. 107 | 108 | - Single vs. double quotes. Whereas the use of single quotes vs. double quotes has significance in Java, they can be used interchangeably in Python (but no, it won’t allow beginnning the same string with a double quote and trying to end it with a single quote, or vice versa!). 109 | 110 | - Getters and setters (not!). Getters and setters in Python are superfluous; rather, you should use the ‘property’ built-in (that’s what it’s for!). In Python, getters and setters are a waste of both CPU and programmer time. 111 | 112 | - Classes are optional. Whereas Java requires every function to be defined in the context of an enclosing class definition, Python has no such requirement. 113 | 114 | - Indentation matters… in Python. This bites many a newbie Python programmer. 115 | 116 | The Big Picture 117 | 118 | - An expert knowledge of Python extends well beyond the technical minutia of the language. A Python expert will have an in-depth understanding and appreciation of Python’s benefits as well as its limitations. Accordingly, here are some sample questions that can help assess this dimension of a candidate’s expertise: 119 | 120 | **What will be the output of the code below in Python 2? Explain your answer.** 121 | 122 | ```py 123 | def div1(x,y): 124 | print "%s/%s = %s" % (x, y, x/y) 125 | def div2(x,y): 126 | print "%s//%s = %s" % (x, y, x//y) 127 | 128 | div1(5,2) 129 | div1(5.,2) 130 | div2(5,2) 131 | div2(5.,2.) 132 | ``` 133 | Also, how would the answer differ in Python 3 (assuming, of course, that the above [print] statements were converted to Python 3 syntax)? 134 | 135 | - kjalfkjaslf 136 | 137 | 138 | 139 | **What is the difference between range and xrange? How has this changed over time?** 140 | - As follows: 141 | - `xrange` returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is. 142 | - For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. 143 | - The only difference is that range returns a Python list object and x range returns an xrange object. This means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function to use. 144 | - This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It’s a memory hungry beast. 145 | 146 | #### Here's a function (Provide a function). Optimize it for me. 147 | - 148 | 149 | **What will be the output of the code below?** 150 | 151 | ```py 152 | List = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] 153 | print(list[10:]) 154 | ``` 155 | - TypeError: 'type' object is not subscriptable 156 | if proper name given,it will print []. 157 | 158 | #### How do you iterate over a list and pull element indices at the same time? 159 | - as 160 | 161 | #### How do you enforce ordering for a dictionary-style object? 162 | - asfdfw 163 | 164 | #### How many ways can you append or concatenate strings? Which of these ways is fastest? Easiest to read? 165 | - fqffwv 166 | 167 | #### Write a code for downloading a CSV in Python2 and Python3. (Provide a link to CSV file) 168 | - jalfkslf 169 | 170 | #### I'm getting a maximum recursion depth error for a function. What does this mean? How can I mitigate the problem? 171 | - ka;lsk;as 172 | 173 | #### Here's a class hierarchy with some methods defined. When I call this function, what gets printed? 174 | - asdassadasd 175 | 176 | Apart from these technical questions, ask these following general questions to find out more about candidates Python skills 177 | 178 | #### What’s your favorite standard library module? 179 | - Bottle. 180 | 181 | #### Tell me something you don't like about Python. 182 | - PEP 572 to include ' := ' operator for assignment. 183 | 184 | #### What was the most interesting project you have participated in? Can you describe it and tell why you consider it to be so interesting? 185 | - College website using tornado 186 | - Annual days audition date,time,venue using redis,python,pandas,tweepy. 187 | 188 | #### Do you like to participate in the analysis, design and deployment phases of a project or do you prefer to concentrate on the pure development of well-described task? Why? 189 | - Ya for sure. To understand its whole life cycle these things are mandatory having development in focus. 190 | 191 | #### I have noticed you listed Skill X on your CV. What’s your opinion about it? 192 | - I am passionate about it. 193 | 194 | #### Do you remember any programming project decision you made that was a failure? Why do you think it was a mistake? Why did it happen? What did you learn from this experience? 195 | - as 196 | 197 | 198 | #### What is a method? 199 | A method is a function on some object x that you normally call as x.name(arguments...). Methods are defined as functions inside the class definition: 200 | ```py 201 | class C: 202 | def meth (self, arg): 203 | return arg*2 + self.attribute 204 | ``` 205 | 206 | #### How can I find the methods or attributes of an object? 207 | 208 | For an instance x of a user-defined class, dir(x) returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class. 209 | 210 | #### How do I call a method defined in a base class from a derived class that overrides it? 211 | 212 | If you're using new-style classes, use the built-in `super()` function: 213 | 214 | ``` 215 | class Derived(Base): 216 | def meth (self): 217 | super(Derived, self).meth() 218 | ``` 219 | If you're using classic classes: For a class definition such as 220 | `class Derived(Base):` ... you can call method meth() defined in Base (or one of Base's base classes) as Base.meth(self,arguments). Here, Base.meth is an unbound method, so you need to provide the self argument. 221 | 222 | #### How can I organize my code to make it easier to change the base class? 223 | 224 | You could define an alias for the base class, assign the real base class to it before your class definition, and use the alias throughout your class. Then all you have to change is the value assigned to the alias. Incidentally, this trick is also handy if you want to decide dynamically (e.g. depending on availability of resources) which base class to use. 225 | 226 | Example: BaseAlias = class Derived(BaseAlias): def meth(self): BaseAlias.meth(self). 227 | 228 | #### How do I find the current module name? 229 | A module can find out its own module name by looking at the predefined global variable `__name__`. If this has the value `'__main__'`, the program is running as a script. Many modules that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking `__name__`: 230 | 231 | ```py 232 | def main(): 233 | print('Running test...') 234 | if __name__ == '__main__': 235 | main() 236 | ``` 237 | `__import__('x.y.z')` 238 | returns Try: `__import__('x.y.z').y.z` 239 | ```py 240 | # For more realistic situations, you may have to do something like: 241 | m = __import__(s) 242 | for i in s.split(".")[1:]: m = getattr(m, i) 243 | ``` 244 | 245 | _Adv_ 246 | #### How do I access a module written in Python from C? 247 | 248 | You can get a pointer to the module object as follows: 249 | 250 | `module = PyImport_ImportModule("");` 251 | 252 | If the module hasn't been imported yet (i.e. it is not yet present in sys.modules), this initializes the module; otherwise it simply returns the value of ``sys.modules[""]``. Note that it doesn't enter the module into any namespace -- it only ensures it has been initialized and is stored in sys.modules. You can then access the module's attributes (i.e. any name defined in the module) as follows: attr = PyObject_GetAttrString(module, ""); Calling PyObject_SetAttrString() to assign to variables in the module also works. 253 | 254 | _Adv_ 255 | #### How do I interface to C++ objects from Python? 256 | 257 | Depending on your requirements, there are many approaches. To do this manually, begin by reading the "Extending and Embedding" document. Realize that for the Python run-time system, there isn't a whole lot of difference between C and C++ -- so the strategy of building a new Python type around a C structure (pointer) type will also work for C++ objects. 258 | 259 | _beg_ 260 | #### How do I convert a number to a string? 261 | 262 | To convert, e.g., the number 144 to the string '144', use the built-in function str(). If you want a hexadecimal or octal representation, use the built-in functions hex() or oct(). For fancy formatting, use the % operator on strings, e.g. "%04d" % 144 yields '0144' and "%.3f" % (1/3.0) yields '0.333'. See the library reference manual for details. 263 | 264 | _beg_ 265 | #### How is the Implementation of Python's dictionaries done? 266 | 267 | Python dictionary needs to be declared first: 268 | `dict = {}` 269 | 270 | Key value pair can be added as: 271 | `dict[key] = value` 272 | or 273 | `objDict.update({key:value})` 274 | 275 | Remove element by: 276 | `dict.pop(key)` 277 | 278 | Remove all: 279 | `objDict.clear()` 280 | 281 | A hash value of the key is computed using a hash function, The hash value addresses a location in an array of "buckets" or "collision lists" which contains the (key , value) pair. 282 | 283 | _int_ 284 | #### What is used to create Unicode string in Python? 285 | 286 | "u" should be added before the string 287 | 288 | `a = (u'Python')` 289 | `type(a) #will give you unicode` 290 | 291 | Add unicode before the string. Ex: unicode(text) resulting in text. 292 | 293 | 294 | _beg_ 295 | #### What is the built-in function used in Python to iterate over a sequence of numbers? 296 | 297 | Syntax: `range(start,end,step count)` 298 | 299 | Ex: 300 | ```py 301 | a = range(1,10,2) 302 | print (a) 303 | ``` 304 | Output: 305 | `[1, 3, 5, 7, 9]` 306 | 307 | If using to iterate 308 | ```py 309 | for i in range(1,10): 310 | print (i) 311 | ``` 312 | Output: 313 | > 314 | 1 315 | 2 316 | 3 317 | 4 318 | 5 319 | 6 320 | 7 321 | 8 322 | 9 323 | 324 | #### Does Python have a switch-case statement? 325 | 326 | Ans. In languages like C++, we have something like this: 327 | 328 | switch(name) 329 | { 330 | case ‘Ram’: 331 | cout<<”Monday”; 332 | break; 333 | case ‘Shiv’: 334 | cout<<”Tuesday”; 335 | break; 336 | default: 337 | cout<<”Hi, user”; 338 | } 339 | 340 | But in Python, we do not have a switch-case statement. Here, you may write a switch function to use. Else, you may use a set of if-elif-else statements. To implement a function for this, we may use a dictionary. 341 | 342 | ``` 343 | def switch(choice): 344 | switcher={ 345 | 'Ram':'Monday', 346 | 'Shiv':'Tuesday', 347 | print(switcher.get(choice,'Hi, user')) 348 | return 349 | switch('Shiv') 350 | Tuesday 351 | switch('Ram') 352 | Monday 353 | switch('Raghav') 354 | Hi, user 355 | } 356 | ``` 357 | 358 | Here, the get() method returns the value of the key. When no key matches, the default value (the second argument) is returned. 359 | 360 | #### Does python support switch or case statement in Python? If not what is the reason for the same? 361 | 362 | Dictionary can be used as case/switch. Actually there is no switch statement in the Python programming language but the is a similar construct that can do justice to switch that is the exception handling using try and except1,except2,except3.... and so on. 363 | 364 | #### What is the statement that can be used in Python if a statement is required syntactically but the program requires no action? 365 | 366 | `pass` keyword is used to do nothing but it fulfill the syntactical requirements. 367 | 368 | ```py 369 | try x[10]: 370 | print(x) 371 | except: 372 | pass 373 | ``` 374 | Use `pass` keyword over there like: 375 | ```py 376 | if a > 0: 377 | print("Hello") 378 | else: 379 | pass 380 | ``` 381 | 382 | 383 | 384 | #### What is used to represent Strings in Python. Is double quotes used for String representation or single quotes used for String representation in Python? 385 | 386 | Both works in Python. Most preferable way by PEP 8 is in double quotes 387 | 388 | #### Does Python support strongly for regular expressions? What are the other languages that support strongly for regular expressions? What are Regular Expressions ? 389 | 390 | Yes, Python Supports Regular Expressions Well. `re` is an in-buit library for the same. There is a lot of other languages that have good support to RegEx- Perl, Awk, Sed, Java etc. 391 | 392 | Regular expressions (called REs, or regexes, or regex patterns) are essentially a tiny, highly specialized programming language embedded inside Python and made available through the re module. Using this little language, you specify the rules for the set of possible strings that you want to match; this set might contain English sentences, or e-mail addresses, or TeX commands, or anything you like. You can then ask questions such as “Does this string match the pattern?”, or “Is there a match for the pattern anywhere in this string?”. You can also use REs to modify a string or to split it apart in various ways. 393 | 394 | Regular expression patterns are compiled into a series of bytecodes which are then executed by a matching engine written in C. For advanced use, it may be necessary to pay careful attention to how the engine will execute a given RE, and write the RE in a certain way in order to produce bytecode that runs faster. Optimization isn’t covered in this document, because it requires that you have a good understanding of the matching engine’s internals. 395 | 396 | #### How do you perform pattern matching in Python? Explain. 397 | 398 | Regular Expressions/REs/ regexes enable us to specify expressions that can match specific "parts" of a given string. For instance, we can define a regular expression to match a single character or a digit, a telephone number, or an email address, etc. The Python’s "re" module provides regular expression patterns and was introduce from later versions of Python 2.5. "re" module is providing methods for search text strings, or replacing text strings along with methods for splitting text strings based on the pattern defined. 399 | 400 | #### Write a regular expression that will accept an email id. Use the `re` module. 401 | 402 | Ans. 403 | ```py 404 | import re 405 | e = re.search(r'[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$' 'JaiRameshwar@gmail.com') 406 | e.group() 407 | ``` 408 | ‘Ramayanwashere@gmail.com’ 409 | 410 | To brush up on regular expressions, check Regular Expressions in Python. 411 | 412 | ### _Garbage Collector & Memory Manager_ 413 | 414 | #### What is Garbage Collection? 415 | The concept of removing unused or unreferenced objects from the memory location is known as a Garbage Collection. While executing the program, if garbage collection takes place then more memory space is available for the program and rest of the program execution becomes faster. 416 | 417 | Garbage collector is a predefined program, which removes the unused or unreferenced objects from the memory location. 418 | 419 | Any object reference count becomes zero then we call that object as a unused or unreferenced object Then no.of reference variables which are pointing the object is known as a reference count of the object. 420 | 421 | While executing the python program if any object reference count becomes zero, then internally python interpreter calls the garbage collector and garbage collector will remove that object from memory location. 422 | 423 | #### How is memory managed in Python? 424 | 425 | Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter. Like other programming language python also has garbage collector which will take care of memory management in python.Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space. The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code. 426 | 427 | Python has a private heap space to hold all objects and data structures. Being programmers, we cannot access it; it is the interpreter that manages it. But with the core API, we can access some tools. The Python memory manager controls the allocation. 428 | 429 | #### Why isn't all memory freed when Python exits? 430 | Objects referenced from the global namespaces of Python modules are not always deallocated when Python exits. This may happen if there are circular references. There are also certain bits of memory ... 431 | 432 | #### Whenever you exit Python, is all memory de-allocated? State why is it so. 433 | 434 | The answer here is no. The modules with circular references to other objects, or to objects referenced from global namespaces, aren’t always freed on exiting Python. 435 | Plus, it is impossible to de-allocate portions of memory reserved by the C library. 436 | 437 | Whenever Python exits, especially those Python modules which are having circular references to other objects or the objects that are referenced from the global namespaces are not always de-allocated or freed.It is impossible to de-allocate those portions of memory that are reserved by the C library.On exit, because of having its own efficient clean up mechanism, Python would try to de-allocate/destroy every other object. 438 | 439 | 440 | 441 | 442 | #### Is it possible to assign multiple var to values in list? 443 | 444 | The multiple assignment trick is a shortcut that lets you assign multiple variables with the values in a list in one line of code. So instead of doing this: 445 | 446 | ```py 447 | cat = ['fat', 'orange', 'loud'] 448 | size = cat[0] 449 | color = cat[1] 450 | disposition = cat[2] 451 | ``` 452 | 453 | Do this: 454 | ``` 455 | cat = ['fat', 'orange', 'loud'] 456 | size, color, disposition = cat 457 | ``` 458 | 459 | 460 | _Adv_ 461 | #### What is `__slots__` and when is it useful? 462 | Normally, all class objects have an `__dict__` which allows new attributes to be bound to a class instance at runtime. When a class is defined with `__slots__`, only attributes whose names are present in the `__slots__` sequence are allowed. 463 | This results in instances of this class not having an `__dict__` attribute and not being able to bind new attributes at run time.`__slots__` is useful because it eliminates 464 | 465 | `__slots__` allow us to explicitly declare data members (like properties) and deny the creation of `__dict__` and `__weakref__` (unless explicitly declared in __slots__ or available in a parent.) 466 | 467 | The space saved over using `__dict__` can be significant. 468 | 469 | object.__slots__ 470 | 471 | This class variable can be assigned a string, iterable, or sequence of strings with variable names used by instances. `__slots__` reserves space for the declared variables and prevents the automatic creation of `__dict__` and `__weakref__` for each instance. 472 | 473 | 3.3.2.4.1. Notes on using `__slots__` 474 | •When inheriting from a class without `__slots__`, the __dict__ and __weakref__ attribute of the instances will always be accessible. 475 | 476 | •Without a __dict__ variable, instances cannot be assigned new variables not listed in the __slots__ definition. Attempts to assign to an unlisted variable name raises AttributeError. If dynamic assignment of new variables is desired, then add '__dict__' to the sequence of strings in the __slots__ declaration. 477 | 478 | •Without a __weakref__ variable for each instance, classes defining __slots__ do not support weak references to its instances. If weak reference support is needed, then add '__weakref__' to the sequence of strings in the __slots__ declaration. 479 | 480 | •__slots__ are implemented at the class level by creating descriptors (Implementing Descriptors) for each variable name. As a result, class attributes cannot be used to set default values for instance variables defined by __slots__; otherwise, the class attribute would overwrite the descriptor assignment. 481 | 482 | •The action of a __slots__ declaration is not limited to the class where it is defined. __slots__ declared in parents are available in child classes. However, child subclasses will get a __dict__ and __weakref__ unless they also define __slots__ (which should only contain names of any additional slots). 483 | 484 | •If a class defines a slot also defined in a base class, the instance variable defined by the base class slot is inaccessible (except by retrieving its descriptor directly from the base class). This renders the meaning of the program undefined. In the future, a check may be added to prevent this. 485 | 486 | •Nonempty __slots__ does not work for classes derived from “variable-length” built-in types such as int, bytes and tuple. 487 | 488 | •Any non-string iterable may be assigned to __slots__. Mappings may also be used; however, in the future, special meaning may be assigned to the values corresponding to each key. 489 | 490 | •__class__ assignment works only if both classes have the same __slots__. 491 | 492 | •Multiple inheritance with multiple slotted parent classes can be used, but only one parent is allowed to have attributes created by slots (the other bases must have empty slot layouts) - violations raise TypeError. 493 | 494 | 495 | 496 | 497 | #### What are the built-in type does python provides? Among them which are Mutable and Immutable Data structures in Python? 498 | #### OR 499 | #### What Are The Types of Objects Support in Python Language? 500 | 501 | Python supports are two types are of objects. They are: 502 | 503 | Immutable built-in types: 504 | 505 | Strings 506 | Tuples 507 | Numbers 508 | 509 | Mutable built-in types: 510 | 511 | List 512 | Sets 513 | Dictionaries 514 | 515 | - Immutable Objects 516 | 517 | The objects which doesn’t allow to modify the contents of those objects are known as ‘Immutable Objects’ 518 | 519 | Before creating immutable objects with some content python interpreter verifies is already any object is available. In memory location with same content or not. 520 | 521 | If already object is not available then python interpreter creates new objects with that content and store that object address two reference variable. 522 | 523 | If already object is present in memory location with the same content creating new objects already existing object address will be given to the reference variable. 524 | 525 | _Program:_ 526 | ```py 527 | i=1000 528 | print(i) 529 | print(type(i)) 530 | print(id(i)) 531 | j=2000 532 | print(j) 533 | print(type(j)) 534 | print(id(j)) 535 | x=3000 536 | print(x) 537 | print(type(x)) 538 | print(id(x)) 539 | y=3000 540 | print(y) 541 | print(type(y)) 542 | print(id(y)) 543 | ``` 544 | 545 | `int, float, complex, bool, str, tuple` are immutable objects 546 | 547 | Immutable objects performance is high. 548 | 549 | Applying iterations on Immutable objects takes less time. 550 | 551 | All fundamentals types represented classes objects and tuple class objects are immutable objects. 552 | 553 | - Mutable Objects: 554 | 1. The Objects which allows to modify the contents of those objects are known as ‘Mutable Objects’ 555 | 2. We can create two different mutable objects with same content 556 | 557 | Program: 558 | ```py 559 | x=[10,20,30] 560 | print(x) 561 | print(type(x)) 562 | print(id(x)) 563 | y=[10,20,30] 564 | print(y) 565 | print(type(y)) 566 | print(id(y)) 567 | ``` 568 | Output: 569 | 570 | `List, set, dict` classes objects are mutable objects 571 | 572 | Mutable objects performance is low when compared to immutable objects 573 | Applying Iterations mutable objects takes huge time 574 | 575 | #### What is difference between tuple and list ? Where will you use tuple and where will you use list ? 576 | --- 577 | | List | Tuple| 578 | List objects are mutable objects Tuple objects are immutable Objects 579 | Applying iterations on list objects Applying iterations on tuple Objects takes longer time takes less time 580 | If the frequent operation is If the frequent operation is 581 | insertion or deletion of the retrieval of the elements elements then it is recommended then it is recommended to 582 | to use list use tuple 583 | List can’t be used as a ‘key’ Tuple can be used 584 | for the dictionary as a key for the dictionary if the tuple is storing only immutable elements 585 | Lists are slower than tuples. Tuples are faster than list. 586 | `list_1 = [10, ‘Chelsea’, 20]` `tup_1 = (10, ‘Chelsea’ , 20)` 587 | mylist = [1,3,3] mytuple = (1,3,3) 588 | mylist[1] = 2 mytuple[1] = 2 589 | 590 | 591 | 592 | #### Python is Call by Value or Call by Reference? How are arguments passed by value or by reference? 593 | 594 | Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable. 595 | 596 | #### Explain Python’s parameter-passing mechanism. 597 | - To pass its parameters to a function, Python uses pass-by-reference. If you change a parameter within a function, the change reflects in the calling function. This is its default behavior. 598 | 599 | - However, when we pass literal arguments like strings, numbers, or tuples, they pass by value. This is because they are immutable. 600 | 601 | 602 | 603 | 604 | #### What is the use of enumerate() in Python? 605 | 606 | #### What are `*args`, `**kwargs` ? 607 | 608 | In cases when we don’t know how many arguments will be passed to a function, like when we want to pass a list or a tuple of values, we use `*args`. 609 | 610 | ```py 611 | def func(*args): 612 | for i in args: 613 | print(i) 614 | 615 | func(3,2,1,4,7) 616 | ``` 617 | 3 618 | 2 619 | 1 620 | 4 621 | 7 622 | 623 | `**kwargs` takes keyword arguments when we don’t know how many there will be: 624 | 625 | ```py 626 | def func(**kwargs): 627 | for i in kwargs: 628 | print(i,kwargs[i]) 629 | 630 | func(a=1,b=2,c=7) 631 | ``` 632 | a.1 633 | b.2 634 | c.7 635 | 636 | The words `args` and `kwargs` are a convention, and we can use anything in their place. 637 | 638 | #### How can I pass optional or keyword parameters from one function to another? 639 | 640 | Collect the arguments using the * and ** specifier in the function's parameter list; this gives you the positional arguments as a tuple and the keyword arguments as a dictionary. You can then pass these arguments when calling another function by using `*` and `**` : 641 | 642 | ```py 643 | def f(x, *tup, **kwargs): 644 | kwargs['width']='14.3c' 645 | g(x, *tup, **kwargs) 646 | ``` 647 | 648 | In the unlikely case that you care about Python versions older than 2.0, use 'apply': 649 | 650 | ```python 651 | def f(x, *tup, **kwargs): 652 | kwargs['width']='14.3c' 653 | apply(g, (x,)+tup, kwargs) 654 | ``` 655 | 656 | 657 | #### How instance variables are different from class variables? 658 | 659 | #### Differentiate between "*.py" file and "*.pyc" file? 660 | 661 | #### Explain difference between Map vs Reduce Vs Filter ? 662 | 663 | #### What is lambda? What are Lambda Functions ?Explain lambda expressions. When would you use one? What is Anonymous Function? Why lambda forms in python does not have statements? What is the lambda operator? 664 | 665 | A function which doesn’t contain any name is known as a anonymous function lambda function, Lambda function we can assign to the variable & we can call the lambda function through the variable. 666 | 667 | Syntax: 668 | `Lambda arguments:expression` 669 | 670 | 671 | It is a single expression anonymous function often used as inline function. A lambda form in python does not have statements as it is used to make new function object and then return them at runtime. 672 | 673 | The lambda operator is used to create anonymous functions. It is mostly used in cases where one wishes to pass functions as parameters. or assign them to variable names. 674 | 675 | When we want a function with a single expression, we can define it anonymously. A lambda expression may take input and returns a value. To define the above function as a lambda expression, we type the following code in the interpreter: 676 | 677 | ```py 678 | (lambda a,b:a if a>b else b)(3,3.5) 679 | ``` 680 | `3.5` 681 | 682 | Here, a and b are the inputs. 683 | `a if a > b else b` is the expression to return. 684 | The arguments are 3 and 3.5. 685 | 686 | It is possible to not have any inputs here. 687 | 688 | `(lambda :print("Hi"))()` 689 | 690 | Hi 691 | 692 | Example: 693 | ```py 694 | myfunction = lambda x:x*x 695 | a = myfunction(10) 696 | print(a) 697 | ``` 698 | Output: 100 699 | 700 | - Why can't lambda forms in Python contain statements? 701 | 702 | Lambdas evaluates at run time and these do not need statements 703 | Lambda is a anonymous function, which does not have a name and no fixed number of arguments. Represented by keyword lambda followed by statement. 704 | Ex: 705 | ```py 706 | add = lambda a,b: a+b 707 | add(2,3) 708 | ``` 709 | output: 710 | `5` 711 | 712 | #### What is __init__ functions ? 713 | #### _OR_ In a class definition, what does the `__init__()` function do? 714 | #### _OR_ How do you create your own package in Python? 715 | 716 | It overrides the any initialization from an inherited class and is called when the class is instantiated. 717 | 718 | We know that a package may contain sub-packages and modules. A module is nothing but Python code. 719 | To create a package of our own, we create a directory and create a file `__init__.py` in it. We leave it empty. Then, in that package, we create a module(s) with whatever code we want. For a detailed explanation with pictures, refer to Python Packages. 720 | 721 | 722 | #### What are Generators ? 723 | 724 | #### What are Iterators ? 725 | 726 | #### Can generator be used to create Iterators ? Give example 727 | 728 | #### Can iterators be used to create generator ? 729 | 730 | #### What are iterators and generators? 731 | 732 | #### What is Method Resolution Order ? 733 | 734 | 735 | 736 | #### Differentiate between append() and extend() methods ? 737 | 738 | --- 739 | #### _Application Based_ 740 | #### What is Web Scraping? How do you achieve it in Python? 741 | We can use scrapy. 742 | 743 | #### Explain the use "with" statement in python? 744 | 745 | - In python generally "with" statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. "with" statement makes the exception handling simpler by providing cleanup activities. 746 | 747 | General form of with: 748 | ```py 749 | with open("filename", "mode") as file-var: 750 | ``` 751 | processing statements 752 | Note: no need to close the file by calling close() upon file-var.close() 753 | #### What are Middlewares ? 754 | #### What is Monkey patching ? Give example ? 755 | 756 | Dynamically modifying a class or module at run-time. 757 | 758 | ```py 759 | class A: 760 | def func(self): 761 | print("Hi") 762 | def monkey(self): 763 | print "Hi, monkey" 764 | m.A.func = monkey 765 | a = m.A() 766 | a.func() 767 | ``` 768 | Hi, monkey 769 | 770 | #### What's the difference between py2.x and py3.x ? 771 | #### Give examples of Python Framework ? 772 | 773 | #### How Python is interpreted. 774 | #### Explain dict. 775 | 776 | #### How to pass optional or keyword arguments. 777 | 778 | #### Explain indexing and slicing. 779 | 780 | 781 | 782 | #### Difference between str() and repr(). 783 | 784 | ======= advanced ====== 785 | #### What is Dynamic Typing ? 786 | #### Justify this statement : Everything is object in Python? 787 | 788 | 789 | 790 | 791 | #### Explain serialization and deserialization / Pickling and unpicking. 792 | Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling. 793 | 794 | To create portable serialized representations of Python objects, we have the module ‘pickle’. It accepts a Python object (remember, everything in Python is an object). It then converts it into a string representation and uses the dump() function to dump it into a file. We call this pickling. In contrast, retrieving objects from this stored string representation is termed 'unpickling'. 795 | 796 | The pickle module implements binary protocols for serializing and deserializing a Python object structure. "Pickling" is the process whereby a Python object hierarchy is converted into a byte stream, and "unpickling" is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as `serialization`, `marshalling`, or `flattening`; however, to avoid confusion, the terms used here are `pickling` and `unpickling`. 797 | 798 | ```py 799 | import json 800 | json_string = json.dumps([1, 2, 3, "a", "b"]) 801 | print(json_string) 802 | 803 | import pickle 804 | pickled_string = pickle.dumps([1, 2, 3, "a", "b"]) 805 | print(pickle.loads(pickled_string)) 806 | ``` 807 | Reference: 808 | [1] https://www.sanfoundry.com/python-questions-answers-pickle-module/ 809 | [2] https://docs.python-guide.org/scenarios/serialization/ 810 | 811 | 812 | #### What is list / dict compression. 813 | 814 | 815 | 816 | #### What are higher ordered functions? 817 | You have two choices: you can use nested scopes or you can use callable objects. For example, suppose you wanted to define linear(a,b) which returns a function f(x) that computes the value a*x+b. 818 | `Using nested scopes:` 819 | ```py 820 | def linear(a,b): 821 | def result(x): 822 | return a*x + b 823 | return result 824 | ``` 825 | Or 826 | 827 | `using a callable object:` 828 | ```py 829 | class linear: 830 | def __init__(self, a, b): 831 | self.a, self.b = a,b 832 | def __call__(self, x): 833 | return self.a * x + self.b 834 | ``` 835 | In both cases: 836 | 837 | `taxes = linear(0.3,2)` gives a callable object where 838 | 839 | `taxes(10e6) == 0.3 * 10e6 + 2. ` 840 | 841 | The callable object approach has the disadvantage that it is a bit slower and results in slightly longer code. However, note that a collection of callables can share their signature via inheritance: 842 | 843 | ```py 844 | class exponential(linear): 845 | __init__ inherited 846 | def __call__(self, x): 847 | return self.a * (x ** self.b) 848 | ``` 849 | Object can encapsulate state for several methods: 850 | ```py 851 | class counter: 852 | value = 0 853 | def set(self, x): 854 | self.value = x 855 | def up(self): 856 | self.value=self.value+1 857 | def down(self): 858 | self.value=self.value-1 859 | count = counter() 860 | 861 | inc, dec, reset = count.up, count.down, count.set 862 | ``` 863 | Here inc(), dec() and reset() act like functions which share the same counting variable. 864 | 865 | #### How do I copy a file? How to copy object in Python? Diff between shallow copy and deep copy? 866 | 867 | The shutil module contains a `copyfile()` function. 868 | 869 | A deep copy copies an object into another. This means that if you make a change to a copy of an object, it won’t affect the original object. In Python, we use the function deepcopy() for this, and we import the module copy. We use it like: 870 | ```py 871 | import copy 872 | b = copy.deepcopy (a) 873 | ``` 874 | A shallow copy, however, copies one object’s reference to another. So, if we make a change in the copy, it will affect the original object. For this, we have the function `copy()`, we use it like: 875 | 876 | ```py 877 | b = copy.copy(a) 878 | ``` 879 | 880 | - Differentiate between lists and tuples. 881 | 882 | The major difference is that a list is mutable, but a tuple is immutable. Examples: 883 | ```py 884 | 885 | ``` 886 | Traceback (most recent call last): 887 | File “”, line 1, in mytuple[1]=2 888 | TypeError: ‘tuple’ object does not support item assignment 889 | 890 | 891 | #### How to make array in python? 892 | import numpy 893 | 894 | #### How to generate random numbers. 895 | 896 | #### How to handle exceptions. 897 | 898 | #### When to use list/tuple/set/dict? 899 | 900 | #### What is virtualenv 901 | 902 | 903 | 904 | #### `with` statement and its usage. 905 | 906 | 907 | 908 | 909 | #### What is class and what is self. 910 | 911 | #### Explain isinstance() 912 | 913 | #### What is static method, class method and instance method? 914 | 915 | 916 | 917 | #### Explain map, filter,reduce and lambda. 918 | 919 | #### Difference between new styled classed and old styled classes. 920 | 921 | #### What is diff between Python and Java? 922 | 923 | #### What is context processor? 924 | 925 | #### What is exec() and eval ()? 926 | 927 | #### How to pass command line argument. 928 | 929 | #### What is yield ? 930 | 931 | #### What is ord() and chr()? 932 | 933 | #### What are Metaclasses? 934 | 935 | #### What is descriptor ? 936 | 937 | #### Any 10 python packages you have used. 938 | 939 | 940 | #### namespace vs scope ? 941 | 942 | #### What is MRO ? 943 | 944 | #### == vs is ? 945 | 946 | 947 | 2. Compare Java & Python 948 | 949 | | Criteria | Java | Python 950 | -------------------------------------- 951 | | Ease of use | Good | Very Good | 952 | |Speed of coding | Average | Excellent | 953 | |Data types |Static typed | Dynamically typed | 954 | |Data Science & | 955 | |machine learning| Average |Very Good | 956 | |applications | 957 | 958 | #### What is the purpose of PYTHONSTARTUP,PYTHONCASEOK,PYTHONHOME & PYTHONPATH environment variables? 959 | 960 | - PYTHONSTARTUP − It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH. 961 | 962 | - PYTHONCASEOK − It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it. 963 | 964 | - PYTHONHOME − It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy. 965 | 966 | - PYTHONPATH − It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer. 967 | 968 | 969 | #### Explain Inheritance in Python with an example. 970 | 971 | When one class inherits from another, it is said to be the child/ derived/sub class inheriting from the parent/base/super class. It inherits/gains all members (attributes and methods). Inheritance lets us reuse our code, and also makes it easier to create and maintain applications. 972 | 973 | Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability,makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived/child class. 974 | 975 | - They are different types of inheritance supported by Python: 976 | 977 | - Single Inheritance – where a derived class acquires the members of a single super class. 978 | 979 | _OR_ 980 | 981 | - Single Inheritance- A class inherits from a single base class. 982 | 983 | - Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 is inherited from base2. 984 | 985 | _OR_ 986 | - Multilevel Inheritance- A class inherits from a base class, which in turn, inherits from another base class. 987 | 988 | - Hierarchical inheritance – from one base class you can inherit any number of child classes 989 | 990 | _OR_ 991 | - Hierarchical Inheritance- Multiple classes inherit from a single base class. 992 | 993 | - Multiple inheritance – a derived class is inherited from more than one base class. 994 | 995 | _OR_ 996 | - Multiple Inheritance- A class inherits from multiple base classes. 997 | 998 | - Hybrid Inheritance- Hybrid inheritance is a combination of two or more types of inheritance. 999 | 1000 | #### What is Hierarchical Inheritance? 1001 | 1002 | The concept of inheriting the properties from one class into multiple classes separately is known as hierarchical inheritance. 1003 | 1004 | Example: 1005 | ```py 1006 | class x(object): 1007 | def m1(self): 1008 | print(“in m1 of x”) 1009 | 1010 | class y(x): 1011 | def m2(self): 1012 | print(“in m2 of y”) 1013 | 1014 | class z(x): 1015 | def m3(self): 1016 | print(“in m3 of z”) 1017 | y1=y() 1018 | y1.m1() 1019 | y1.m2() 1020 | a=y1.--hash--() 1021 | print(a) 1022 | z1=z() 1023 | z1.m1() 1024 | z1.m3() 1025 | b=z1.hash--() 1026 | print(b) 1027 | ``` 1028 | 1029 | Output: 1030 | ``` 1031 | M m1 of X 1032 | In m2 of Y 1033 | 2337815 1034 | In m1 of X 1035 | In m3 of Z 1036 | 2099735 1037 | ``` 1038 | 1039 | **Python supports Multi-Level Inheritance or Multiple Inheritance or Both?** 1040 | - Yes 1041 | #### Consider multiple inheritances here. 1042 | #### Suppose class C inherits from classes A and B as class C(A,B).Classes A and B both have their own versions of method func(). If we call func() from an object of class C, which version gets invoked? 1043 | 1044 | Ans. In our article on Multiple Inheritance in Python, we discussed Method Resolution Order (MRO). C does not contain its own version of func(). Since the interpreter searches in a left-to-right fashion, it finds the method in A, and does not go to look for it in B. 1045 | 1046 | #### Which methods/functions do we use to determine the type of instance and inheritance? 1047 | 1048 | Ans. Here, we talk about three methods/functions- `type(), isinstance() and issubclass()`. 1049 | 1050 | a. `type()`: This tells us the type of object we’re working with. 1051 | 1052 | type(3) 1053 | 1054 | 1055 | type(False) 1056 | 1057 | 1058 | 1059 | type(lambda :print("Hi")) 1060 | 1061 | 1062 | 1063 | type(type) 1064 | 1065 | 1066 | 1067 | b. isinstance() 1068 | 1069 | This takes in two arguments- a value and a type. If the value is of the kind of the specified type, it returns True. Else, it returns False. 1070 | 1071 | isinstance(3,int) 1072 | True 1073 | 1074 | isinstance((1),tuple) 1075 | False 1076 | 1077 | isinstance((1,),tuple) 1078 | True 1079 | 1080 | c. issubclass() 1081 | 1082 | This takes two classes as arguments. If the first one inherits from the second, it returns True. Else, it returns False. 1083 | 1084 | class A: pass 1085 | class B(A): pass 1086 | issubclass(B,A) 1087 | True 1088 | 1089 | issubclass(A,B) 1090 | False 1091 | 1092 | 1093 | 1094 | - Write a one-liner that will count the number of capital letters in a file. Your code should work even if the file is too big to fit in memory. 1095 | 1096 | Let us first write a multiple line solution and then convert it to one liner code. 1097 | ```py 1098 | with open(SOME_LARGE_FILE) as fh: 1099 | count = 0 1100 | text = fh.read() 1101 | for character in text: 1102 | if character.isupper(): 1103 | count += 1 1104 | ``` 1105 | 1106 | - Write a sorting algorithm for a numerical dataset in Python. 1107 | 1108 | The following code can be used to sort a list in Python: 1109 | ```py 1110 | list = ["1", "4", "0", "6", "9"] 1111 | list = [int(i) for i in list] 1112 | list.sort() 1113 | print(list) 1114 | ``` 1115 | 1116 | - How will you remove last object from a list? 1117 | 1118 | `list.pop(obj=list[-1])` − Removes and returns last object or obj from list. 1119 | 1120 | #### What are negative indexes and why are they used? 1121 | 1122 | Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth. 1123 | 1124 | The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ that is uses as first index and ‘1’ as the second index and the process goes on like that. 1125 | 1126 | The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number. 1127 | 1128 | The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order. 1129 | 1130 | Let’s take a list for this. 1131 | ```py 1132 | mylist=[0,1,2,3,4,5,6,7,8] 1133 | ``` 1134 | 1135 | A negative index, unlike a positive one, begins searching from the right. 1136 | ```py 1137 | mylist[-3] 1138 | ``` 1139 | 6 1140 | 1141 | This also helps with slicing from the back: 1142 | 1143 | ```py 1144 | mylist[-6:-1] 1145 | ``` 1146 | [3, 4, 5, 6, 7] 1147 | 1148 | 1149 | #### Explain split(), sub(), subn() methods of `re` module in Python. 1150 | - To modify the strings, Python’s "re" module is providing 3 methods. They are: 1151 | - split() – uses a regex pattern to "split" a given string into a list. 1152 | - sub() – finds all substrings where the regex pattern matches and then replace them with a different string. 1153 | - subn() – it is similar to sub() and also returns the new string along with the no. of replacements. 1154 | 1155 | 1156 | What is map function in Python? 1157 | 1158 | Map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given. #Follow the link to know more similar functions 1159 | - How to get indices of N maximum values in a NumPy array? 1160 | 1161 | We can get the indices of N maximum values in a NumPy array using the below code: 1162 | 1163 | ```py 1164 | import numpy as np 1165 | arr = np.array([1, 3, 2, 4, 5]) 1166 | print(arr.argsort()[-3:][::-1]) 1167 | ``` 1168 | - What is a Python module? 1169 | 1170 | A module is a Python script that generally contains import statements, functions, classes and variable definitions, and Python runnable code and it "lives" file with a ‘.py’ extension. zip files and DLL files can also be modules.Inside the module, you can refer to the module name as a string that is stored in the global variable name . 1171 | 1172 | - Name the File-related modules in Python? 1173 | 1174 | Python provides libraries / modules with functions that enable you to manipulate text files and binary files on file system. Using them you can create files, update their contents, copy, and delete files. The libraries are : os, os.path, and shutil. 1175 | 1176 | Here, 1177 | `os` and `os.path` – modules include functions for accessing the filesystem 1178 | `shutil` – module enables you to copy and delete the files. 1179 | 1180 | 1181 | 1182 | 1183 | - Explain all the file processing modes supported by Python? 1184 | 1185 | Python allows you to open files in one of the three modes. They are: 1186 | 1187 | `read-only` mode, `write-only` mode, `read-write` mode, and `append` mode by specifying the flags "r", "w", "rw", "a" respectively. 1188 | 1189 | A text file can be opened in any one of the above said modes by specifying the option "t" along with 1190 | 1191 | "r", "w", "rw", and "a", so that the preceding modes become "rt", "wt", "rwt", and "at".A binary file can be opened in any one of the above said modes by specifying the option "b" along with "r", "w", "rw", and "a" so that the preceding modes become "rb", "wb", "rwb", "ab". 1192 | 1193 | - How many kinds of sequences are supported by Python? What are they? 1194 | 1195 | Python supports 7 sequence types. They are str, list, tuple, unicode, byte array, xrange, and buffer. where xrange is deprecated in python 3.5.X. 1196 | 1197 | 1198 | 1199 | #### How to display the contents of text file in reverse order?How will you reverse a list? 1200 | 1201 | `list.reverse()` − Reverses objects of list in place, convert the given file into a list. Reverse the list by using `reversed()`. 1202 | E.g.: 1203 | ```py 1204 | for line in reversed(list(open("file-name","r"))): 1205 | print(line) 1206 | ``` 1207 | 1208 | - What is the difference between NumPy and SciPy? 1209 | 1210 | In an ideal world, NumPy would contain nothing but the array data type and the most basic operations: indexing, sorting, reshaping, basic element wise functions, et cetera. All numerical code would reside in SciPy. However, one of NumPy’s important goals is compatibility, so NumPy tries to retain all features supported by either of its predecessors. Thus NumPy contains some linear algebra functions, even though these more properly belong in SciPy. In any case, SciPy contains more fully-featured versions of the linear algebra modules, as well as many other numerical algorithms. If you are doing scientific computing with python, you should probably install both NumPy and SciPy. Most new features belong in SciPy rather than NumPy. 1211 | 1212 | - Which of the following is an invalid statement? 1213 | a) abc = 1,000,000 1214 | b) a b c = 1000 2000 3000 1215 | c) a,b,c = 1000, 2000, 3000 1216 | d) a_b_c = 1,000,000 1217 | 1218 | Answer: b 1219 | 1220 | - What is the output of the following? 1221 | ```py 1222 | try: 1223 | if '1' != 1: 1224 | raise 1225 | ``` 1226 | a) some Error has occured 1227 | b) some Error has not occured 1228 | c) invalid code 1229 | d) none of the above 1230 | 1231 | Answer: C 1232 | 1233 | - Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1] ? 1234 | 1235 | 25 1236 | 1237 | - How to open a file c:\scores.txt for writing? 1238 | 1239 | ``fileWriter = open("c:\\scores.txt", "w")`` 1240 | - Name few Python modules for Statistical, Numerical and scientific computations ? 1241 | 1242 | `numPy` – this module provides an array/matrix type, and it is useful for doing computations on arrays. 1243 | `scipy` – this module provides methods for doing numeric integrals, solving differential equations, etc 1244 | `pylab` – is a module for generating and saving plots 1245 | 1246 | - What is TkInter? 1247 | 1248 | TkInter is Python library. It is a toolkit for GUI development. It provides support for various GUI tools or widgets (such as buttons, labels, text boxes, radio buttons, etc) that are used in GUI applications. The common attributes of them include Dimensions, Colors, Fonts, Cursors, etc. 1249 | 1250 | - Is Python object oriented? what is object oriented programming? 1251 | 1252 | Yes. Python is Object Oriented Programming language. OOP is the programming paradigm based on classes and instances of those classes called objects. The features of OOP are: Encapsulation, Data Abstraction, Inheritance, Polymorphism. 1253 | 1254 | - Does Python supports interfaces like in Java? Discuss. 1255 | Python does not provide interfaces like in Java. Abstract Base Class (ABC) and its feature are provided by the Python’s "abc" module. Abstract Base Class is a mechanism for specifying what methods must be implemented by its implementation subclasses. The use of ABC’c provides a sort of "understanding" about methods and their expected behaviour. This module was made available from Python 2.7 version onwards. 1256 | 1257 | - What are Accessors, mutators, @property? 1258 | Accessors and mutators are often called getters and setters in languages like "Java". For example, if x is a property of a user-defined class, then the class would have methods called setX() and getX(). Python has an @property 'decorator' that allows you to ad getters and setters in order to access the attribute of the class. 1259 | 1260 | - Differentiate between append() and extend() methods.? 1261 | 1262 | Both append() and extend() methods are the methods of list. These methods are used to add the elements at the end of the list. 1263 | `append(element)` – adds the given element at the end of the list which has called this method. 1264 | `extend(another-list)` – adds the elements of another-list at the end of the list which is called the extend method. 1265 | 1266 | - Name few methods that are used to implement Functionally Oriented Programming in Python? 1267 | 1268 | Python supports methods (called iterators in Python3), such as filter(), map(), and reduce(), that are very useful when you need to iterate over the items in a list, create a dictionary, or extract a subset of a list. 1269 | - `filter()` – enables you to extract a subset of values based on conditional logic. 1270 | - `map()` – it is a built-in function that applies the function to each item in an iterable. 1271 | - `reduce()` – repeatedly performs a pair-wise reduction on a sequence until a single value is computed. 1272 | 1273 | - What is the output of the following? 1274 | ```python 1275 | x = ['ab', 'cd'] 1276 | print(len(map(list, x))) 1277 | ``` 1278 | A TypeError occurs as map has no len(). 1279 | 1280 | - What is the output of the following? 1281 | ```py 1282 | x = ['ab', 'cd'] 1283 | print(len(list(map(list, x)))) 1284 | ``` 1285 | The length of each string is 2. 1286 | 1287 | - Which of the following is not the correct syntax for creating a set? 1288 | a) set([[1,2],[3,4]]) 1289 | b) set([1,2,2,3,4]) 1290 | c) set((1,2,3,4)) 1291 | d) {1,2,3,4} 1292 | 1293 | A. 1294 | Explanation : The argument given for the set must be an iterable. 1295 | 1296 | - Explain a few methods to implement Functionally Oriented Programming in Python. 1297 | 1298 | Sometimes, when we want to iterate over a list, a few methods come in handy. 1299 | 1300 | `filter()`: Filter lets us filter in some values based on conditional logic. 1301 | ```py 1302 | list(filter(lambda x:x>5,range(8))) 1303 | ``` 1304 | Ans: [6, 7] 1305 | 1306 | `map()`: Map applies a function to every element in an iterable. 1307 | ```py 1308 | list(map(lambda x:x**2,range(8))) 1309 | ``` 1310 | Ans: [0, 1, 4, 9, 16, 25, 36, 49] 1311 | 1312 | `reduce()`: Reduce repeatedly reduces a sequence pair-wise until we reach a single value 1313 | 1314 | ```py 1315 | from functools import reduce 1316 | reduce(lambda x,y:x-y,[1,2,3,4,5]) 1317 | ``` 1318 | Ans: -13 1319 | 1320 | 1321 | 1322 | - Write a Python function that checks whether a passed string is palindrome Or not? 1323 | 1324 | Note: A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam , saas, nun. 1325 | 1326 | ```py 1327 | def isPalindrome(string): 1328 | left_pos = 0 1329 | right_pos = len(string) – 1 1330 | 1331 | while right_pos >= left_pos: 1332 | if not string[left_pos] == string[right_pos]: 1333 | return False 1334 | 1335 | left_pos += 1 1336 | right_pos -= 1 1337 | return True 1338 | print(isPalindrome(‘aza’)) 1339 | ``` 1340 | - Write a Python program to calculate the sum of a list of numbers. 1341 | ```py 1342 | def list_sum(num_List): 1343 | if len(num_List) == 1: 1344 | return num_List[0] 1345 | else: 1346 | return num_List[0] + list_sum(num_List[1:]) 1347 | 1348 | print(list_sum([2, 4, 5, 6, 7])) 1349 | ``` 1350 | Sample Output: 24 1351 | 1352 | - How to retrieve data from a table in MySQL database through Python code? Explain. 1353 | ```py 1354 | #import MySQLdb module as : 1355 | import MySQLdb 1356 | 1357 | #establish a connection to the database. 1358 | db = MySQLdb.connect("host"="local host", "database-user"="user-name", "password"="password", "database-name"="database") 1359 | 1360 | #initialize the cursor variable upon the established connection: 1361 | c1 = db.cursor() 1362 | 1363 | #retrieve the information by defining a required query string. 1364 | s = "Select * from dept" 1365 | 1366 | #fetch the data using fetch() methods and print it. 1367 | data = c1.fetch(s) 1368 | 1369 | #close the database connection. 1370 | db.close() 1371 | ``` 1372 | - Write a Python program to read a random line from a file. 1373 | ```py 1374 | import random 1375 | def random_line(fname): 1376 | lines = open(fname).read().splitlines() 1377 | return random.choice(lines) 1378 | print(random_line(‘test.txt’)) 1379 | ``` 1380 | - Write a Python program to count the number of lines in a text file. 1381 | 1382 | ```py 1383 | def file_lengthy(fname): 1384 | with open(fname) as f: 1385 | for i, l in enumerate(f): 1386 | pass 1387 | return i + 1 1388 | 1389 | print("Number of lines in the file: ",file_lengthy("test.txt")) 1390 | ``` 1391 | - When to use list comprehensions and when to avoid list comprehensions ? 1392 | 1393 | - What are Map, filter and reduce functions ? 1394 | - What are the different types of exceptions generated in python? 1395 | - How to write your own custom exception handling ? 1396 | - Difference between input and raw_input ? 1397 | - Why do we write `__name__` == `"__main__"` in a python script ? 1398 | 1399 | - Why does the exception handling have a finally block ? 1400 | - Does python provide thread safe multi-threading ? 1401 | - What do you mean by non blocking IO ? 1402 | 1403 | 1404 | 1405 | - What are the key features of Python? 1406 | 1407 | If it makes for an introductory language to programming, Python must mean something. These are its qualities: 1408 | > 1409 | - Interpreted. 1410 | - Dynamically-typed. 1411 | - Object-oriented 1412 | - Concise and simple 1413 | - Free 1414 | - Has a large community 1415 | 1416 | - Explain the ternary operator in Python. 1417 | 1418 | Unlike C++, we don’t have ?: in Python, but we have this: 1419 | 1420 | [on true] if [expression] else [on false] 1421 | 1422 | If the expression is True, the statement under [on true] is executed. Else, that under [on false] is executed. 1423 | 1424 | Below is how you would use it: 1425 | ex 1. 1426 | ```py 1427 | a,b=2,3 1428 | min=a if a 1505 | ```py 1506 | roots[9] 1507 | ``` 1508 | 3 1509 | 1510 | A dictionary is mutable, and we can also use a comprehension to create it. 1511 | ```py 1512 | roots={x**2:x for x in range(5,0,-1)} 1513 | roots 1514 | ``` 1515 | {25: 5, 16: 4, 9: 3, 4: 2, 1: 1} 1516 | 1517 | **How do you get a list of all the keys in a dictionary?** 1518 | 1519 | Be specific in these type of Python Interview Questions and Answers. 1520 | 1521 | For this, we use the function keys(). 1522 | ```py 1523 | mydict={'a':1,'b':2,'c':3,'e':5} 1524 | mydict.keys() 1525 | print(dict_keys) 1526 | ``` 1527 | ([‘a’, ‘b’, ‘c’, ‘e’]) 1528 | 1529 | #### Write Python logic to count the number of capital letters in a file. 1530 | ```py 1531 | import os 1532 | os.chdir('C:\\Users\\lifei\\Desktop') 1533 | with open('Today.txt') as today: 1534 | count = 0 1535 | for i in today.read(): 1536 | if i.isupper(): 1537 | count+=1 1538 | print(count) 1539 | ``` 1540 | 26 1541 | 1542 | #### How would you randomize the contents of a list in-place? 1543 | 1544 | For this, we’ll import the function `shuffle()` from the module `random`. 1545 | ```py 1546 | from random import shuffle 1547 | shuffle(mylist) 1548 | mylist 1549 | ``` 1550 | [3, 4, 8, 0, 5, 7, 6, 2, 1] 1551 | 1552 | #### Explain join() and split() in Python. 1553 | 1554 | `.join([])` It takes any iterables into this method. Join method is used to concatenate the elements of any list. `join()` lets us join characters from a string together by a character we specify. 1555 | ```py 1556 | ','.join('12345') 1557 | ``` 1558 | '1,2,3,4,5' 1559 | 1560 | `split()` lets us split a string around the character we specify. 1561 | ```py 1562 | '1,2,3,4,5'.split(',') 1563 | ``` 1564 | [‘1’, ‘2’, ‘3’, ‘4’, ‘5’] 1565 | 1566 | #### Is Python case-sensitive? 1567 | 1568 | A language is case-sensitive if it distinguishes between identifiers like myname and Myname. In other words, it cares about case- lowercase or uppercase. Let’s try this with Python. 1569 | ```py 1570 | myname='Ramayan' 1571 | Myname 1572 | ``` 1573 | Traceback (most recent call last): 1574 | File “”, line 1, in Myname 1575 | NameError: name ‘Myname’ is not defined 1576 | 1577 | As you can see, this raised a NameError. This means that Python is indeed case-sensitive. 1578 | 1579 | - How long can an identifier be in Python? 1580 | 1581 | In Python, an identifier can be of any length. Apart from that, there are certain rules we must follow to name one: 1582 | > 1583 | - It can only begin with an underscore or a character from A-Z or a-z. 1584 | - The rest of it can contain anything from the following: A-Z/a-z/_/0-9. 1585 | - Python is case-sensitive, as we discussed in the previous question. 1586 | - Keywords cannot be used as identifiers. 1587 | 1588 | Python has the following keywords: 1589 | `and def False import not True` 1590 | `as del finally in or try` 1591 | `assert elif for is pass while` 1592 | `break else from lambda print with ` 1593 | `class except global None raise yield` 1594 | `continue exec if nonlocal return` 1595 | 1596 | 1597 | Q.20. How do you remove the leading whitespace in a string? 1598 | 1599 | Leading whitespace in a string is the whitespace in a string before the first non-whitespace character. To remove it from a string, we use the method `lstrip()`. 1600 | ```py 1601 | ' Ram '.lstrip() 1602 | ``` 1603 | 'Ram ' 1604 | 1605 | As you can see, this string had both leading and trailing whitespaces. lstrip() stripped the string of the leading whitespace. If we want to strip the trailing whitespace instead, we use rstrip(). 1606 | ```py 1607 | ' Ram '.rstrip() 1608 | ``` 1609 | ' Ram' 1610 | 1611 | - How would you convert a string into lowercase? 1612 | 1613 | We use the lower() method for this. 1614 | ```py 1615 | 'Ramayan'.lower() 1616 | ``` 1617 | ‘ramayan’ 1618 | 1619 | To convert it into uppercase, then, we use upper(). 1620 | ```py 1621 | 'Ramayan'.upper() 1622 | ``` 1623 | 'RAMAYAN' 1624 | 1625 | Also, to check if a string is in all uppercase or all lowercase, we use the methods isupper() and islower(). 1626 | ```py 1627 | 'Ramayan'.isupper() 1628 | ``` 1629 | False 1630 | ```py 1631 | 'Ramayan'.isupper() 1632 | ``` 1633 | True 1634 | ```py 1635 | 'Ramayan'.islower() 1636 | ``` 1637 | True 1638 | 1639 | ```py 1640 | '$hrir@m'.islower() 1641 | ``` 1642 | True 1643 | ```py 1644 | '$HRIR@M'.isupper() 1645 | ``` 1646 | True 1647 | 1648 | So, characters like @ and $ will suffice for both cases. 1649 | 1650 | Also, istitle() will tell us if a string is in title case. 1651 | 1652 | ```py 1653 | 'Arrested Development'.istitle() 1654 | ``` 1655 | True 1656 | 1657 | - What is the pass statement in Python? 1658 | 1659 | There may be times in our code when we haven’t decided what to do yet, but we must type something for it to be syntactically correct. In such a case, we use the pass statement. 1660 | 1661 | ```py 1662 | def func(*args): 1663 | pass 1664 | ``` 1665 | 1666 | Similarly, the break statement breaks out of a loop. 1667 | ```py 1668 | for i in range(7): 1669 | if i==3: break 1670 | print(i) 1671 | ``` 1672 | 0 1673 | 1 1674 | 2 1675 | 1676 | Finally, the continue statement skips to the next iteration. 1677 | ```py 1678 | for i in range(7): 1679 | if i==3: continue 1680 | print(i) 1681 | ``` 1682 | 0 1683 | 1 1684 | 2 1685 | 4 1686 | 5 1687 | 6 1688 | 1689 | - What is a closure in Python? 1690 | 1691 | A closure is said to occur when a nested function references a value in its enclosing scope. The whole point here is that it remembers the value. 1692 | ```py 1693 | def A(x): 1694 | def B(): 1695 | print(x) 1696 | return B 1697 | 1698 | A(7)() 1699 | ``` 1700 | 1701 | 7 1702 | 1703 | - Explain the //, %, and ** operators in Python. 1704 | 1705 | The // operator performs floor division. It will return the integer part of the result on division. 1706 | ```py 1707 | 7//2 1708 | ``` 1709 | `3` 1710 | Normal division would return 3.5 here. 1711 | 1712 | Similarly, ** performs exponentiation. a**b returns the value of a raised to the power b. 1713 | ```py 1714 | 2**10 1715 | ``` 1716 | 1024 1717 | 1718 | Finally, % is for modulus. This gives us the value left after the highest achievable division. 1719 | ```py 1720 | 13 % 7 1721 | ``` 1722 | 6 1723 | ```py 1724 | 3.5 % 1.5 1725 | ``` 1726 | 0.5 1727 | 1728 | - How many kinds of operators do we have in Python? Explain arithmetic operators. 1729 | 1730 | This type of Python Interview Questions and Answers can decide your knowledge in Python. Answer the Python Interview Questions with some good Examples. 1731 | 1732 | Here in Python, we have 7 kinds of operators: arithmetic, relational assignment, logical, membership, identity, and bitwise. 1733 | 1734 | We have seven arithmetic operators. These allow us to perform arithmetic operations on values: 1735 | 1736 | Addition (+) This adds two values. 1737 | ```py 1738 | 7+8 1739 | 7-8 1740 | 7*8 1741 | 7/8 # 0.875 1742 | 7//8 # 0 1743 | ``` 1744 | - Explain relational operators in Python. 1745 | 1746 | Relational operators compare values. 1747 | > - Less than (<) If the value on the left is lesser, it returns True. 1748 | ```py 1749 | 'hi'<'Hi' 1750 | ``` 1751 | False 1752 | 1753 | Greater than (>) If the value on the left is greater, it returns True. 1754 | 1755 | 1.1+2.2>3.3 1756 | 1757 | True 1758 | 1759 | This is because of the flawed floating-point arithmetic in Python, due to hardware dependencies. 1760 | 1761 | Less than or equal to (<=) If the value on the left is lesser than or equal to, it returns True. 1762 | 1763 | 3.0<=3 1764 | 1765 | True 1766 | 1767 | Greater than or equal to (>=) If the value on the left is greater than or equal to, it returns True. 1768 | 1769 | True>=False 1770 | 1771 | True 1772 | 1773 | Equal to (==) If the two values are equal, it returns True. 1774 | 1775 | {1,3,2,2}=={1,2,3} 1776 | 1777 | True 1778 | 1779 | Not equal to (!=) If the two values are unequal, it returns True. 1780 | 1781 | True!=0.1 1782 | 1783 | True 1784 | 1785 | False!=0.1 1786 | 1787 | True 1788 | 1789 | - What are assignment operators in Python? 1790 | 1791 | This one is an Important Interview question in Python Interview. 1792 | 1793 | We can combine all arithmetic operators with the assignment symbol. 1794 | 1795 | a=7 1796 | a+=1 1797 | a 1798 | 1799 | 8 1800 | 1801 | a-=1 1802 | a 1803 | 1804 | 7 1805 | 1806 | a*=2 1807 | a 1808 | 1809 | 14 1810 | 1811 | a/=2 1812 | a 1813 | 1814 | 7.0 1815 | 1816 | a**=2 1817 | a 1818 | 1819 | 49.0 1820 | 1821 | a//=3 1822 | a 1823 | 1824 | 16.0 1825 | 1826 | a%=4 1827 | a 1828 | 1829 | 0.0 1830 | 1831 | - Explain logical operators in Python. 1832 | 1833 | We have three logical operators- and, or, not. 1834 | 1835 | False and True 1836 | 1837 | False 1838 | 1839 | 7<7 or True 1840 | 1841 | True 1842 | 1843 | not 2==2 1844 | 1845 | False 1846 | 1847 | Q.28. What are membership, operators? 1848 | 1849 | With the operators ‘in’ and ‘not in’, we can confirm if a value is a member in another. 1850 | 1851 | 'me' in 'disappointment' 1852 | True 1853 | 1854 | 'us' not in 'disappointment' 1855 | True 1856 | 1857 | Q.29. Explain identity operators in Python. 1858 | 1859 | This is one of the very commonly asked Python Interview Questions and answers it with examples. 1860 | The operators ‘is’ and ‘is not’ tell us if two values have the same identity. 1861 | 1862 | 10 is '10' 1863 | False 1864 | 1865 | True is not False 1866 | 1867 | True 1868 | 1869 | Q.30. Finally, tell us about bitwise operators in Python. 1870 | 1871 | These operate on values bit by bit. 1872 | 1873 | AND (&) This performs & on each bit pair. 1874 | 1875 | 0b110 & 0b010 1876 | 1877 | 2 1878 | 1879 | OR (|) This performs | on each bit pair. 1880 | 1881 | 3|2 1882 | 1883 | 3 1884 | 1885 | XOR (^) This performs an exclusive-OR operation on each bit pair. 1886 | 1887 | 3^2 1888 | 1889 | 1 1890 | 1891 | Binary One’s Complement (~) This returns the one’s complement of a value. 1892 | 1893 | ~2 1894 | 1895 | -3 1896 | 1897 | Binary Left-Shift (<<) This shifts the bits to the left by the specified amount. 1898 | 1899 | 1<<2 1900 | 1901 | 4 1902 | 1903 | Here, 001 was shifted to the left by two places to get 100, which is binary for 4. 1904 | 1905 | Binary Right-Shift (>>) 1906 | 1907 | 4>>2 1908 | 1909 | 1 1910 | 1911 | For more insight on operators, refer to Operators in Python. 1912 | 1913 | Q.31. How would you work with numbers other than those in the decimal number system? 1914 | 1915 | With Python, it is possible to type numbers in binary, octal, and hexadecimal. 1916 | 1917 | Binary numbers are made of 0 and 1. To type in binary, we use the prefix 0b or 0B. 1918 | 1919 | int(0b1010) 1920 | 1921 | 10 1922 | 1923 | To convert a number into its binary form, we use bin(). 1924 | 1925 | bin(0xf) 1926 | 1927 | ‘0b1111’ 1928 | 1929 | Octal numbers may have digits from 0 to 7. We use the prefix 0o or 0O. 1930 | 1931 | oct(8) 1932 | 1933 | ‘0o10’ 1934 | 1935 | Hexadecimal numbers may have digits from 0 to 15. We use the prefix 0x or 0X. 1936 | 1937 | hex(16) 1938 | 1939 | ‘0x10’ 1940 | 1941 | hex(15) 1942 | 1943 | ‘0xf’ 1944 | 1945 | 1946 | 1947 | - Why are identifier names with a leading underscore disparaged? 1948 | 1949 | Since Python does not have a concept of private variables, it is a convention to use leading underscores to declare a variable private. This is why we mustn’t do that to variables we do not want to make private. 1950 | 1951 | - How can you declare multiple assignments in one statement? 1952 | 1953 | There are two ways to do this: 1954 | ```py 1955 | a,b,c=3,4,5 #This assigns 3, 4, and 5 to a, b, and c resp. 1956 | a = b = c =3 #This assigns 3 to a, b, and c 1957 | ``` 1958 | 1959 | - What is tuple unpacking? 1960 | 1961 | First, let’s discuss tuple packing. It is a way to pack a set of values into a tuple. 1962 | ```py 1963 | mytuple=3,4,5 1964 | mytuple 1965 | ``` 1966 | (3, 4, 5) 1967 | 1968 | This packs 3, 4, and 5 into mytuple. 1969 | 1970 | Now, we will unpack the values from the tuple into variables x, y, and z. 1971 | ```py 1972 | x,y,z=mytuple 1973 | x+y+z 1974 | ``` 1975 | 1976 | - What data types does Python support? 1977 | 1978 | Python provides us with five kinds of data types: 1979 | 1980 | 1981 | ```py 1982 | a=7.0 1983 | title="Ramayan's Book" 1984 | colors=['red','green','blue'] 1985 | type(colors) 1986 | 1987 | name=('Ramayan','Sharma') 1988 | name[0]='Avery' 1989 | Traceback (most recent call last): 1990 | File “, line 1, in name[0]=’Avery’ 1991 | TypeError: ‘tuple’ object does not support item assignment 1992 | squares={1:1,2:4,3:9,4:16,5:25} 1993 | type(squares) 1994 | 1995 | type({}) 1996 | 1997 | squares={x:x**2 for x in range(1,6)} 1998 | squares 1999 | {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} 2000 | ``` 2001 | 2002 | Q2. What is a docstring? 2003 | 2004 | A docstring is a documentation string that we use to explain what a construct does. We place it as the first thing under a function, class, or a method, to describe what it does. We declare a docstring using three sets of single or double quotes. 2005 | 2006 | ```py 2007 | def sayhi(): 2008 | """ 2009 | The function prints Hi 2010 | """ 2011 | print("Hi") 2012 | 2013 | sayhi() 2014 | ``` 2015 | 2016 | Hi 2017 | 2018 | To get a function’s docstring, we use its `__doc__` attribute. 2019 | ```py 2020 | sayhi.__doc__ 2021 | ``` 2022 | '\n\tThis function prints Hi\n\t' 2023 | 2024 | A docstring, unlike a comment, is retained at runtime. 2025 | 2026 | Q.3. What is the PYTHONPATH variable? 2027 | 2028 | PYTHONPATH is the variable that tells the interpreter where to locate the module files imported into a program. Hence, it must include the Python source library directory and the directories containing Python source code. You can manually set PYTHONPATH, but usually, the Python installer will preset it. 2029 | 2030 | Q.4. What is slicing? 2031 | 2032 | These are the types of basic Python interview questions for freshers. 2033 | 2034 | Slicing is a technique that allows us to retrieve only a part of a list, tuple, or string. For this, we use the slicing operator []. 2035 | 2036 | ```py 2037 | (1,2,3,4,5)[2:4] 2038 | (3, 4) 2039 | [7,6,8,5,9][2:] 2040 | [8, 5, 9] 2041 | 'Hello'[:-1] 2042 | ‘Hell’ 2043 | ``` 2044 | 2045 | Q.5. What is a namedtuple? 2046 | 2047 | A namedtuple will let us access a tuple’s elements using a name/label. We use the function namedtuple() for this, and import it from collections. 2048 | 2049 | ```py 2050 | from collections import namedtuple 2051 | result=namedtuple('result','Physics Chemistry Maths') #format 2052 | Ramayan=result(Physics=86,Chemistry=95,Maths=86) #declaring the tuple 2053 | Ramayan.Chemistry 2054 | ``` 2055 | `95` 2056 | 2057 | As you can see, it let us access the marks in Chemistry using the Chemistry attribute of object Ramayan. 2058 | 2059 | Q.6. How would you declare a comment in Python? 2060 | 2061 | Unlike languages like C++, Python does not have multiline comments. All it has is octothorpe (#). Anything following a hash is considered a comment, and the interpreter ignores it. 2062 | 2063 | #line 1 of comment 2064 | #line 2 of comment 2065 | 2066 | In fact, you can place a comment anywhere in your code. You can use it to explain your code. 2067 | 2068 | Q.7. How would you convert a string into an int in Python? 2069 | 2070 | If a string contains only numerical characters, you can convert it into an integer using the int() function. 2071 | 2072 | int('227') 2073 | 2074 | 227 2075 | 2076 | Let’s check the types: 2077 | 2078 | type('227') 2079 | 2080 | 2081 | 2082 | type(int('227')) 2083 | 2084 | 2085 | 2086 | Q.8. How do you take input in Python? 2087 | 2088 | For taking input from user, we have the function input(). In Python 2, we had another function raw_input(). 2089 | 2090 | The input() function takes, as an argument, the text to be displayed for the task: 2091 | 2092 | a=input('Enter a number') 2093 | 2094 | Enter a number7 2095 | 2096 | But if you have paid attention, you know that it takes input in the form of a string. 2097 | 2098 | type(a) 2099 | 2100 | 2101 | 2102 | Multiplying this by 2 gives us this: 2103 | 2104 | a*=2 2105 | a 2106 | 2107 | ’77’ 2108 | 2109 | So, what if we need to work on an integer instead? 2110 | 2111 | We use the int() function for this. 2112 | 2113 | a=int(input('Enter a number')) 2114 | 2115 | Enter a number7 2116 | 2117 | Now when we multiply it by 2, we get this: 2118 | 2119 | a*=2 2120 | a 2121 | 2122 | `14` 2123 | 2124 | Q.9. What is a frozen set in Python? 2125 | 2126 | Answer these type of Python Interview Questions with Examples. 2127 | 2128 | First, let’s discuss what a set is. A set is a collection of items, where there cannot be any duplicates. A set is also unordered. 2129 | 2130 | myset={1,3,2,2} 2131 | myset 2132 | 2133 | `{1, 2, 3}` 2134 | 2135 | This means that we cannot index it. 2136 | 2137 | myset[0] 2138 | 2139 | Traceback (most recent call last): 2140 | File “”, line 1, in myset[0] 2141 | TypeError: ‘set’ object does not support indexing 2142 | 2143 | However, a set is mutable. A frozen set is immutable. This means we cannot change its values. This also makes it eligible to be used as a key for a dictionary. 2144 | 2145 | myset=frozenset([1,3,2,2]) 2146 | myset 2147 | 2148 | frozenset({1, 2, 3}) 2149 | 2150 | type(myset) 2151 | 2152 | 2153 | 2154 | Q.10. How would you generate a random number in Python? 2155 | 2156 | This kind of Python interview Questions and Answers can Prove your depth of knowledge. 2157 | 2158 | To generate a random number, we import the function random() from the module random. 2159 | 2160 | from random import random 2161 | random() 2162 | 2163 | `0.7931961644126482` 2164 | 2165 | Let’s call for help on this. 2166 | 2167 | help(random) 2168 | 2169 | Help on built-in function random: 2170 | 2171 | `random(…)` method of random.Random instance 2172 | 2173 | `random() -> x` in the interval [0, 1). 2174 | 2175 | This means that it will return a random number equal to or greater than 0, and less than 1. 2176 | 2177 | We can also use the function randint(). It takes two arguments to indicate a range from which to return a random integer. 2178 | ``` 2179 | from random import randint 2180 | randint(2,7) 2181 | ``` 2182 | 6 2183 | ``` 2184 | randint(2,7) 2185 | ``` 2186 | 5 2187 | 2188 | randint(2,7) 2189 | 2190 | 7 2191 | 2192 | randint(2,7) 2193 | 2194 | 6 2195 | 2196 | randint(2,7) 2197 | 2198 | 2 2199 | 2200 | Q.11. How will you capitalize the first letter of a string? 2201 | 2202 | Simply using the method capitalize(). 2203 | 2204 | 'Ramayan'.capitalize() 2205 | 2206 | ‘Ramayan’ 2207 | 2208 | type(str.capitalize) 2209 | 2210 | 2211 | 2212 | However, it will let other characters be. 2213 | 2214 | '$hrir@m'.capitalize() 2215 | 2216 | ‘$HRIR@M’ 2217 | 2218 | Q.12. How will you check if all characters in a string are alphanumeric? 2219 | 2220 | For this, we use the method isalnum(). 2221 | 2222 | 'Ramayan123'.isalnum() 2223 | 2224 | True 2225 | 2226 | 'Ramayan123!'.isalnum() 2227 | 2228 | False 2229 | 2230 | Other methods that we have include: 2231 | 2232 | '123.3'.isdigit() 2233 | 2234 | False 2235 | 2236 | '123'.isnumeric() 2237 | 2238 | True 2239 | 2240 | 'Ramayan'.islower() 2241 | 2242 | True 2243 | 2244 | 'Ramayan'.isupper() 2245 | 2246 | False 2247 | 2248 | 'Ramayan'.istitle() 2249 | 2250 | True 2251 | 2252 | ' '.isspace() 2253 | 2254 | True 2255 | 2256 | '123F'.isdecimal() 2257 | 2258 | False 2259 | 2260 | Q.13. What is the concatenation? 2261 | 2262 | This is very basic Python Interview Question, try not to make any mistake in this. 2263 | 2264 | Concatenation is joining two sequences. We use the + operator for this. 2265 | 2266 | '32'+'32' 2267 | ‘3232’ 2268 | 2269 | [1,2,3]+[4,5,6] 2270 | [1, 2, 3, 4, 5, 6] 2271 | 2272 | (2,3)+(4) 2273 | `Traceback (most recent call last): ` 2274 | `File “”, line 1, in (2,3)+(4)` 2275 | `TypeError: can only concatenate tuple (not “int”) to tuple` 2276 | 2277 | Here, 4 is considered an int. Let’s do this again. 2278 | 2279 | (2,3)+(4,) # (obj,) is way to declare single empty 2280 | (2, 3, 4) 2281 | 2282 | Q.14. What is a function? 2283 | 2284 | When we want to execute a sequence of statements, we can give it a name. Let’s define a function to take two numbers and return the greater number. 2285 | 2286 | ```py 2287 | def greater(a,b): 2288 | return a is a>b else b 2289 | greater(3,3.5) 2290 | ``` 2291 | `3.5` 2292 | 2293 | You can create your own function or use one of Python’s many built-in functions. 2294 | 2295 | 2296 | Q.16. What is recursion? 2297 | 2298 | When a function makes a call to itself, it is termed recursion. But then, in order for it to avoid forming an infinite loop, we must have a base condition. Let’s take an example. 2299 | ```py 2300 | def facto(n): 2301 | if n==1: return 1 2302 | return n*facto(n-1) 2303 | 2304 | facto(4) 2305 | ``` 2306 | `24` 2307 | 2308 | 2309 | 2310 | 3. Python Interview Questions for Experienced 2311 | 2312 | These are the Advanced Python Interview Questions and Answers for Experienced, however they can also refer the basic Python Interview Questions and Answers for Freshers for basic knowledge. 2313 | 2314 | Q.21. What does the function zip() do? 2315 | 2316 | One of the less common functions with beginners, zip() returns an iterator of tuples. 2317 | 2318 | list(zip(['a','b','c'],[1,2,3])) 2319 | 2320 | [(‘a’, 1), (‘b’, 2), (‘c’, 3)] 2321 | 2322 | Here, it pairs items from the two lists, and creates tuples with those. But it doesn’t have to be lists. 2323 | 2324 | list(zip(('a','b','c'),(1,2,3))) 2325 | 2326 | [(‘a’, 1), (‘b’, 2), (‘c’, 3)] 2327 | 2328 | Q.22. If you are ever stuck in an infinite loop, how will you break out of it? 2329 | 2330 | For this, we press Ctrl+C. This interrupts the execution. Let’s create an infinite loop to demonstrate this. 2331 | 2332 | def counterfunc(n): 2333 | while(n==7):print(n) 2334 | counterfunc(7) 2335 | 2336 | 7 2337 | 7 2338 | 7 2339 | 7 2340 | . 2341 | . 2342 | . 2343 | . 2344 | . 2345 | Traceback (most recent call last): 2346 | File “”, line 1, in counterfunc(7) 2347 | File “”, line 2, in counterfunc 2348 | while(n==7):print(n) 2349 | KeyboardInterrupt 2350 | 2351 | 2352 | Q.23. 2353 | 2354 | Q.24. With Python, how do you find out which directory you are currently in? 2355 | 2356 | To find this, we use the function/method getcwd(). We import it from the module os. 2357 | 2358 | import os 2359 | os.getcwd() 2360 | 2361 | ‘C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32’ 2362 | 2363 | type(os.getcwd) 2364 | 2365 | 2366 | 2367 | We can also change the current working directory with chdir(). 2368 | 2369 | os.chdir('C:\\Users\\lifei\\Desktop') 2370 | os.getcwd() 2371 | 2372 | ‘C:\\Users\\lifei\\Desktop’ 2373 | 2374 | Q.25. How will you find, in a string, the first word that rhymes with ‘cake’? 2375 | 2376 | For our purpose, we will use the function search(), and then use group() to get the output. 2377 | 2378 | import re 2379 | rhyme=re.search('.ake','I would make a cake, but I hate to bake') 2380 | rhyme.group() 2381 | 2382 | ‘make’ 2383 | 2384 | And as we know, the function search() stops at the first match. Hence, we have our first rhyme to ‘cake’. 2385 | 2386 | Q.27. What is Tkinter? 2387 | 2388 | Tkinter is a famous Python library with which you can craft a GUI. It provides support for different GUI tools and widgets like buttons, labels, text boxes, radio buttons, and more. These tools and widgets have attributes like dimensions, colors, fonts, colors, and more. 2389 | 2390 | You can also import the tkinter module. 2391 | 2392 | import tkinter 2393 | top=tkinter.Tk() 2394 | 2395 | This will create a new window for you: 2396 | 2397 | This creates a window with the title ‘My Game’. You can position your widgets on this. 2398 | 2399 | Follow this link to know more about Python Libraries 2400 | 2401 | Q.28. How is a .pyc file different from a .py file? 2402 | 2403 | While both files hold bytecode, .pyc is the compiled version of a Python file. It has platform-independent bytecode. Hence, we can execute it on any platform that supports the .pyc format. Python automatically generates it to improve performance(in terms of load time, not speed). 2404 | 2405 | Q.29. 2406 | 2407 | Q.30. How do you calculate the length of a string? 2408 | 2409 | This is simple. We call the function len() on the string we want to calculate the length of. 2410 | 2411 | len('Adi Shakara') 2412 | 2413 | 2414 | 2415 | Q.1. What does the following code output? 2416 | 2417 | def extendList(val, list=[]): 2418 | list.append(val) 2419 | return list 2420 | list1 = extendList(10) 2421 | list2 = extendList(123,[]) 2422 | list3 = extendList('a') 2423 | list1,list2,list3 2424 | 2425 | Ans. ([10, ‘a’], [123], [10, ‘a’]) 2426 | 2427 | You’d expect the output to be something like this: 2428 | 2429 | ([10],[123],[‘a’]) 2430 | 2431 | Well, this is because the list argument does not initialize to its default value ([]) every time we make a call to the function. Once we define the function, it creates a new list. Then, whenever we call it again without a list argument, it uses the same list. This is because it calculates the expressions in the default arguments when we define the function, not when we call it. 2432 | 2433 | Let’s revise the Basis of Python Programming 2434 | 2435 | #### What is a decorator? How do I define my own? 2436 | 2437 | Ans. A decorator is a function that adds functionality to another function without modifying it. It wraps another function to add functionality to it. A Python decorator is a specific change that we make in Python syntax to alter functions easily. 2438 | 2439 | ```py 2440 | def decor(func): 2441 | def wrap(): 2442 | print("$$$$$$$$$$$$$$$$$") 2443 | func() 2444 | print("$$$$$$$$$$$$$$$$$") 2445 | return wrap 2446 | 2447 | @decor 2448 | def sayhi(): 2449 | print("Hi") 2450 | 2451 | sayhi() 2452 | ``` 2453 | $$$$$$$$$$$$$$$$$ 2454 | Hi 2455 | $$$$$$$$$$$$$$$$$ 2456 | 2457 | Decorators are an example of metaprogramming, where one part of the code tries to change another. For more on decorators, read Python Decorators. 2458 | 2459 | #### What is decorator and its usage ? How to create custom decorator ? 2460 | 2461 | #### Why use function decorators? Give an example. 2462 | 2463 | A decorator is essentially a callable Python object that is used to modify or extend a function or class definition. 2464 | 2465 | One of the beauties of decorators is that a single decorator definition can be applied to multiple functions (or classes). Much can thereby be accomplished with decorators that would otherwise require lots of boilerplate (or even worse redundant!) code. 2466 | 2467 | Flask, for example, uses decorators as the mechanism for adding new endpoints to a web application. Examples of some of the more common uses of decorators include adding synchronization, type enforcement,logging, or pre/post conditions to a class or function. 2468 | 2469 | 2. Basic Python Programming Interview Questions 2470 | 2471 | Below are some Basic Python Programming Interview Questions and answers for freshers. 2472 | 2473 | 2474 | Q.4. How many arguments can the range() function take? 2475 | 2476 | Ans. The range() function in Python can take up to 3 arguments. Let’s see this one by one. 2477 | 2478 | a. One argument 2479 | 2480 | When we pass only one argument, it takes it as the stop value. Here, the start value is 0, and the step value is +1. 2481 | 2482 | list(range(5)) 2483 | 2484 | [0, 1, 2, 3, 4] 2485 | 2486 | list(range(-5)) 2487 | 2488 | [] 2489 | 2490 | list(range(0)) 2491 | 2492 | [] 2493 | 2494 | b. Two arguments 2495 | 2496 | When we pass two arguments, the first one is the start value, and the second is the stop value. 2497 | 2498 | list(range(2,7)) 2499 | 2500 | [2, 3, 4, 5, 6] 2501 | 2502 | list(range(7,2)) 2503 | 2504 | [] 2505 | 2506 | list(range(-3,4)) 2507 | 2508 | [-3, -2, -1, 0, 1, 2, 3] 2509 | 2510 | c. Three arguments 2511 | 2512 | Here, the first argument is the start value, the second is the stop value, and the third is the step value. 2513 | 2514 | list(range(2,9,2)) 2515 | 2516 | [2, 4, 6, 8] 2517 | 2518 | list(range(9,2,-1)) 2519 | 2520 | [9, 8, 7, 6, 5, 4, 3] 2521 | 2522 | 2523 | Q.6. How do you debug a program in Python? Answer in brief. 2524 | 2525 | Ans. To debug a Python program, we use the 2526 | module. This is the Python debugger; we will discuss it in a tutorial soon. If we start a program using pdb, it will let us step through the code. 2527 | 2528 | Q.7. List some pdb commands. 2529 | 2530 | Some pdb commands include- 2531 | > 2532 | — Add breakpoint 2533 | — Resume execution 2534 | — Debug step by step 2535 | — Move to next line 2536 | — List source code 2537 |

— Print an expression 2538 | 2539 | Q.8. What command do we use to debug a Python program? 2540 | 2541 | Ans. To start debugging, we first open the command prompt, and get to the location the file is at. 2542 | 2543 | Microsoft Windows [Version 10.0.16299.248] 2544 | 2545 | (c) 2017 Microsoft Corporation. All rights reserved. 2546 | 2547 | 2548 | 2549 | C:\Users\lifei> cd Desktop 2550 | 2551 | C:\Users\lifei\Desktop> 2552 | 2553 | Then, we run the following command (for file try.py): 2554 | 2555 | C:\Users\lifei\Desktop>python -m pdb try.py 2556 | 2557 | > c:\users\lifei\desktop\try.py(1)() 2558 | 2559 | -> for i in range(5): 2560 | 2561 | (Pdb) 2562 | 2563 | Then, we can start debugging. 2564 | 2565 | Q.9. What is a Counter in Python? 2566 | 2567 | Ans. The function Counter() from the module ‘collections’. It counts the number of occurrences of the elements of a container. 2568 | 2569 | from collections import Counter 2570 | Counter([1,3,2,1,4,2,1,3,1]) 2571 | 2572 | Counter({1: 4, 3: 2, 2: 2, 4: 1}) 2573 | 2574 | Python provides us with a range of ways and methods to work with a Counter. Read Python Counter. 2575 | 2576 | Q.10. What is NumPy? Is it better than a list? 2577 | Python Programming Interview Questions - Numpy vs List 2578 | 2579 | Python Programming Interview Questions – Numpy vs List 2580 | 2581 | Ans. NumPy, a Python package, has made its place in the world of scientific computing. It can deal with large data sizes, and also has a powerful N-dimensional array object along with a set of advanced functions. 2582 | 2583 | Yes, a NumPy array is better than a Python list. This is in the following ways: 2584 | 2585 | It is more compact. 2586 | It is more convenient. 2587 | It Is more efficiently. 2588 | It is easier to read and write items with NumPy. 2589 | 2590 | Read our latest tutorial on Python NumPy 2591 | 2592 | Q.11. How would you create an empty NumPy array? 2593 | 2594 | Ans. To create an empty array with NumPy, we have two options: 2595 | 2596 | a. Option 1 2597 | 2598 | import numpy 2599 | numpy.array([]) 2600 | 2601 | array([], dtype=float64) 2602 | 2603 | b. Option 2 2604 | 2605 | numpy.empty(shape=(0,0)) 2606 | 2607 | array([], shape=(0, 0), dtype=float64) 2608 | 2609 | 2610 | Q.12. What is PEP 8? 2611 | 2612 | Ans. PEP 8 is a coding convention that lets us write more readable code. In other words, it is a set of recommendations. 2613 | 2614 | Q.16. Explain the use of the ‘nonlocal’ keyword in Python. 2615 | 2616 | Ans. First, let’s discuss the local and global scope. By example, a variable defined inside a function is local to that function. Another variable defined outside any other scope is global to the function. 2617 | 2618 | Suppose we have nested functions. We can read a variable in an enclosing scope from inside he inner function, but cannot make a change to it. For that, we must declare it nonlocal inside the function. First, let’s see this without the nonlocal keyword. 2619 | 2620 | def outer(): 2621 | a=7 2622 | def inner(): 2623 | print(a) 2624 | inner() 2625 | outer() 2626 | 2627 | 7 2628 | 2629 | def outer(): 2630 | a=7 2631 | def inner(): 2632 | print(a) 2633 | a+=1 2634 | print(a) 2635 | inner() 2636 | 2637 | outer() 2638 | 2639 | Traceback (most recent call last): 2640 | File “”, line 1, in outer() 2641 | File “”, line 7, in outer inner() 2642 | File “”, line 4, in inner print(a) 2643 | UnboundLocalError: local variable ‘a’ referenced before assignment 2644 | 2645 | So now, let’s try doing this with the ‘nonlocal’ keyword: 2646 | 2647 | def outer(): 2648 | a=7 2649 | def inner(): 2650 | nonlocal a 2651 | print(a) 2652 | a+=1 2653 | print(a) 2654 | 2655 | inner() 2656 | 2657 | outer() 2658 | 2659 | 7 2660 | 2661 | 8 2662 | 2663 | Q.17. So, then, what is the global keyword? 2664 | 2665 | Ans. Like we saw in the previous question, the global keyword lets us deal with, inside any scope, the global version of a variable. 2666 | 2667 | The problem: 2668 | 2669 | a=7 2670 | def func(): 2671 | print(a) 2672 | a+=1 2673 | print(a) 2674 | 2675 | The solution: 2676 | 2677 | a=7 2678 | def func(): 2679 | global a 2680 | print(a) 2681 | a+=1 2682 | print(a) 2683 | func() 2684 | 2685 | 7 2686 | 2687 | 8 2688 | 2689 | Q.18. How would you make a Python script executable on Unix? 2690 | 2691 | Ans. For this to happen, two conditions must be met: 2692 | 2693 | The script file’s mode must be executable 2694 | The first line must begin with a hash(#). An example of this will be: #!/usr/local/bin/python 2695 | 2696 | Q.19. What functions or methods will you use to delete a file in Python? 2697 | 2698 | Ans. For this, we may use remove() or unlink(). 2699 | 2700 | import os 2701 | os.chdir('C:\\Users\\lifei\\Desktop') 2702 | os.remove('try.py') 2703 | 2704 | 2705 | When we go and check our Desktop, the file is gone. Let’s go make it again so we can delete it again using unlink(). 2706 | 2707 | os.unlink('try.py') 2708 | 2709 | 2710 | Both functions are the same, but unlink is the traditional Unix name for it. 2711 | 2712 | Q.20. What are accessors, mutators, and @property? 2713 | 2714 | Ans. What we call getters and setters in languages like Java, we term accessors and mutators in Python. In Java, if we have a user-defined class with a property ‘x’, we have methods like getX() and setX(). In Python, we have @property, which is syntactic sugar for property(). This lets us get and set variables without compromising on the conventions. For a detailed explanation on property, refer to Python property. 2715 | 2716 | 2717 | Q.22. Differentiate between the append() and extend() methods of a list. 2718 | 2719 | Ans. The methods append() and extend() work on lists. While append()adds an element to the end of the list, extend adds another list to the end of a list. 2720 | 2721 | Let’s take two lists. 2722 | 2723 | list1,list2=[1,2,3],[5,6,7,8] 2724 | 2725 | This is how append() works: 2726 | 2727 | list1.append(4) 2728 | list1 2729 | 2730 | [1, 2, 3, 4] 2731 | 2732 | And this is how extend() works: 2733 | 2734 | list1.extend(list2) 2735 | list1 2736 | 2737 | [1, 2, 3, 4, 5, 6, 7, 8] 2738 | 2739 | 2740 | 2741 | #### What do you mean by overriding methods? 2742 | 2743 | Ans. Suppose class B inherits from class A. Both have the method sayhello()- to each, their own version. B overrides the sayhello() of class A. So, when we create an object of class B, it calls the version that class B has. 2744 | 2745 | ```py 2746 | class A: 2747 | def sayhello(self): 2748 | print("Hello, I'm A") 2749 | class B(A): 2750 | def sayhello(self): 2751 | print("Hello, I'm B") 2752 | a=A() 2753 | b=B() 2754 | a.sayhello() 2755 | ``` 2756 | Hello, I’m A 2757 | ```py 2758 | b.sayhello() 2759 | ``` 2760 | Hello, I’m B 2761 | 2762 | Q.26. What is JSON? Describe in brief how you’d convert JSON data into Python data? 2763 | 2764 | Ans. JSON stands for JavaScript Object Notation. It is a highly popular data format, and it stores data into NoSQL databases. JSON is generally built on the following two structures: 2765 | 2766 | A collection of pairs 2767 | An ordered list of values. 2768 | 2769 | Python supports JSON parsers. In fact, JSON-based data is internally represented as a dictionary in Python. To convert JSON data into Python data, we use the load() function from the JSON module. 2770 | 2771 | - How can you implement functional programming and why would you? 2772 | - Explain ctypes and why you would use them? 2773 | - What is multiple inheritence and when should you use it? 2774 | - What is a meta class? 2775 | - What are properties and what's the point? 2776 | - What's the difference between 2.7+ and 3? 2777 | - What is a unicode string? 2778 | - What does the yield statement do? 2779 | - What is a generator? 2780 | - Why would I use one? 2781 | - What is polymorphism, when would I use it? 2782 | - How do you go about packaging python code? 2783 | - Is Python compiled?, If yes how so, if not how so. 2784 | - What does __some-variable__ mean? 2785 | - Should I import an entire module? 2786 | - What does dynamicly/duck typed mean? 2787 | - When would I not use Python? 2788 | - What is DRY, how can I apply it through OOP or FP? 2789 | - When would I use Python? 2790 | 2791 | 1. What are the differences between Python and Java ? 2792 | 2793 | Python Vs Java 2794 | Comparison Python Java 2795 | 2796 | Performance Speed Fast Not as much as Python 2797 | 2798 | Indentation Must be followed Using proper flower braces is enough 2799 | 2800 | Typing Dynamically typed Static typed 2801 | 2802 | Accessability Simple and compact Not as much as Python 2803 | 2804 | Platforms Not compatible to many Platform independent 2805 | 2806 | Database Access Weak compared to JAVA Strong (JDBC) 2807 | 2808 | Q2. How is Python executed? 2809 | 2810 | Python files are compiled to bytecode. which is then executed by the host. 2811 | Alternate Answer: 2812 | Type python .pv at the command line. 2813 | 2814 | Q3. What is the difference between .py and .pyc files? 2815 | 2816 | .py files are Python source files. .pyc files are the compiled bvtecode files that is generated by the Python compiler 2817 | 2818 | Q4. How do you invoke the Python interpreter for interactive use? 2819 | 2820 | python or pythonx.y where x.y are the version of the Python interpreter desired. 2821 | 2822 | Q5. How are Python blocks defined? 2823 | 2824 | By indents or tabs. This is different from most other languages which use symbols to define blocks. Indents in Python are significant. 2825 | 2826 | Q6. What is the Python interpreter prompt? 2827 | 2828 | Three greater-than signs: Also, when the int 2829 | erpreter is waiting for more input the prompt changes to three periods 2830 | 2831 | Q7. How do you execute a Python Script? 2832 | 2833 | From the command line, type python .py or pythonx.y 2834 | .py where the x.y is the version of the Python interpreter desired. 2835 | Learn how to use Python, from beginner basics to advanced techniques, with online video tutorials taught by industry experts. Enroll for Free Python Training Demo! 2836 | 2837 | Q8. Explain the use of try: except: raise, and finally: 2838 | 2839 | Try, except and finally blocks are used in Python error handling. Code is executed in the try block until an error occurs. One can use a generic except block, which will receive control after all errors, or one can use specific exception handling blocks for various error types. Control is transferred to the appropriate except block. In all cases, the finally block is executed. Raise may be used to raise your own exceptions. 2840 | 2841 | Q9. Illustrate the proper use of Python error handling. 2842 | 2843 | Code Example: 2844 | 2845 | try: 2846 | ….#This can be any code 2847 | except: 2848 | …# error handling code goes here 2849 | finally: 2850 | …# code that will be executed regardless of exception handling goes here. 2851 | 2852 | Q10. What happens if an error occurs that is not handled in the except block? 2853 | 2854 | The program tenuinates. and an execution trace is sent to sys.stderr. 2855 | 2856 | Q11. How are modules used in a Python program? 2857 | 2858 | Modules are brought in via the import statement. 2859 | 2860 | Q12. How do you create a Python function? 2861 | 2862 | Functions are defined using the def statement. An example might be def foo(bar): 2863 | 2864 | Q13. How is a Python class created? 2865 | 2866 | Classes are created using the class statement. An example might be 2867 | `class aa rdva rk(fooba r):` 2868 | 2869 | Q14. How is a Python class instantiated? 2870 | 2871 | The class is instantiated by calling it directly. An example might be: 2872 | `myclass = aardvark(5)` 2873 | 2874 | 2875 | 2876 | Q16. How does a function return values? 2877 | 2878 | Functions return values using the return statement. 2879 | 2880 | Q17. What happens when a function doesn’t have a return statement? Is this valid? 2881 | 2882 | Yes, this is valid. The function will then return a None object. The end of a function is defined by the block of code being executed (i.e., the indenting) not by any explicit keyword. 2883 | 2884 | 2885 | #### What is a namespace in Python? 2886 | 2887 | In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object. 2888 | 2889 | A namespace is a collection of names. It maps names to corresponding objects. When different namespaces contain objects with the same names, this avoids any name collisions. Internally, a namespace is implemented as a Python dictionary. 2890 | 2891 | On starting the interpreter, it creates a namespace for as long as we don’t exit. We have local namespaces, global namespaces, and a built-in namespace. 2892 | 2893 | #### Explain the differences between local and global namespaces. 2894 | 2895 | Local namespaces are created within a function. when that function is called. Global name spaces are created when the program starts. 2896 | 2897 | #### Name the four main types of namespaces in Python? 2898 | 2899 | Global, Local, Module and Class namespaces. 2900 | 2901 | #### When would you use triple quotes as a delimiter? 2902 | 2903 | Triple quotes ‘’”” or ‘“ are string delimiters that can span multiple lines in Python. Triple quotes are usually used when spanning multiple lines, or enclosing a string that has a mix of single and double quotes contained therein. 2904 | 2905 | 2906 | Q34. How to use GUI that comes with Python to test your code? 2907 | 2908 | That is just an editor and a graphical version of the interactive shell. You write or load code and run it, or type it into the shell. 2909 | There is no automated testing. 2910 | 2911 | 2912 | 2913 | Q36. How does the Python version numbering scheme work? 2914 | 2915 | Python versions are numbered A.B.C or A.B. 2916 | 2917 | A is the major version number. It is only incremented for major changes in the language. 2918 | 2919 | B is the minor version number, incremented for less earth-shattering changes. 2920 | 2921 | C is the micro-level. It is incremented for each bug fix release. 2922 | Not all releases are bug fix releases. 2923 | 2924 | In the run-up to a new major release, ‘A’ series of development releases are made denoted as alpha, beta, or release candidate. 2925 | 2926 | Alphas are early releases in which interfaces aren’t finalized yet; it’s not unexpected to see an interface change between two alpha releases. 2927 | 2928 | Betas are more stable, preserving existing interfaces but possibly adding new modules, and release candidates are frozen, making no changes except as needed to fix critical bugs. 2929 | 2930 | Alpha, beta and release candidate versions have an additional suffix. 2931 | 2932 | The suffix for an alpha version is “aN” for some small number N, 2933 | 2934 | The suffix for a beta version is “bN” for some small number N, 2935 | 2936 | And the suffix for a release candidate version is “cN” for some small number N. 2937 | 2938 | In other words, all versions labeled 2.0aN precede the versions labeled 2.0bN, which precede versions labeled 2.0cN, and those precede 2.0. 2939 | 2940 | You may also find version numbers with a “+” suffix, e.g. “2.2+”. These are unreleased versions, built directly from the subversion trunk. In practice, after a final minor release is made, the subversion trunk is incremented to the next minor version, which becomes the “a0” version, e.g. “2.4a0”. 2941 | 2942 | Q37. Where is math.py (socket.py, regex.py, etc.) source file? 2943 | 2944 | If you can’t find a source file for a module, it may be a built-in or dynamically loaded module implemented in C, C++ or other compiled language. In this case you may not have the source file or it may be something like mathmodule.c, somewhere in a C source directory (not on the Python Path). There are (at least) three kinds of modules in Python: 2945 | 2946 | - Modules written in Python (.py); 2947 | - Modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc); 2948 | - Modules written in C and linked with the interpreter; to get a list of these, type; 2949 | Import sys print sys.builtin_module_names; 2950 | 2951 | Q38. How do I make a Python script executable on UNIX? 2952 | 2953 | You need to do two things: 2954 | The script file’s mode must be executable and the first line must begin with “#!” followed by the path of the Python interpreter. 2955 | - The first is done by executing chmod +x scriptfile or perhaps chmod 755 ‘script’ file. 2956 | - The second can be done in a number of ways. 2957 | 2958 | The most straightforward way is to write: 2959 | `#!/usr/local/bin/python` 2960 | 2961 | as the very first line of your file, using the pathname for where the Python interpreter is installed on your platform. If you would like the script to be independent of where the Python interpreter lives, you can use the “env” program. Almost all UNIX variants support the following, assuming the python interpreter is in a directory on the users $PATH: 2962 | 2963 | `#! /usr/bin/env python` 2964 | 2965 | Don’t do this for CGI scripts. The __$PATH__ variable for CGI scripts is often minimal, so you need to use the actual absolute pathname of the interpreter. Occasionally, a user’s environment is so full that the /usr/bin/env program fails; or there’s no env program at all. In that case, you can try the following hack (due to Alex Rezinsky): 2966 | 2967 | ```py 2968 | #! /bin/sh 2969 | “””:” 2970 | exec python $0 ${1+”$@”} 2971 | “”” 2972 | ``` 2973 | The minor disadvantage is that this defines the script’s `__doc__`string. However, you can fix that by adding: 2974 | `__doc__ = “””…Whatever…”””` 2975 | 2976 | Q39. Why don’t my signal handlers work? 2977 | 2978 | The most common problem is that the signal handler is declared with the wrong argument list. It is called as: 2979 | handler (signum, frame) 2980 | So it should be declared with two arguments: 2981 | def handler(signum, frame): 2982 | 2983 | 2984 | 2985 | #### How do I find undefined g++ symbols __builtin_new or __pure_virtual? 2986 | 2987 | To dynamically load g++ extension modules, you must: 2988 | Recompile Python 2989 | Re-link it using g++ (change LINKCC in the python Modules Makefile) 2990 | Link your extension module using g++ (e.g., “g++ -shared -o mymodule.so mymodule.o”). 2991 | 2992 | Q42. How do I send mail from a Python script? 2993 | 2994 | Use the standard library module smtplib. Here’s a very simple interactive mail sender that uses it. This method will work on any host that supports an SMTP listener. 2995 | ```py 2996 | import sys, smtplib 2997 | fromaddr = raw_input(“From: “) 2998 | toaddrs = raw_input(“To: “).split(‘,’) 2999 | print “Enter message, end with ^D:” 3000 | msg = ” 3001 | while 1: 3002 | line = sys.stdin.readline() 3003 | if not line: 3004 | break 3005 | 3006 | msg = msg + line 3007 | 3008 | # The actual mail send 3009 | server = smtplib.SMTP(‘localhost’) 3010 | server.sendmail(fromaddr, toaddrs, msg) 3011 | server.quit() 3012 | ``` 3013 | A UNIX-only alternative uses send mail. The location of the send mail program varies between systems; sometimes it is /usr/lib/sendmail, sometime /usr/sbin/sendmail. The send mail manual page will help you out. Here’s some sample code: 3014 | 3015 | ```py 3016 | SENDMAIL = “/usr/sbin/sendmail” # sendmail location 3017 | import os 3018 | p = os.popen(“%s -t -i” % SENDMAIL, “w”) 3019 | p.write(“To: receiver@example.comn“) 3020 | p.write(“Subject: testn”) 3021 | p.write(“n”) # blank line separating headers from body 3022 | p.write(“Some textn”) 3023 | p.write(“some more textn”) 3024 | sts = p.close() 3025 | if sts != 0: 3026 | print (“Sendmail exit status”, sts) 3027 | ``` 3028 | Q43. How can I mimic CGI form submission (METHOD=POST)? I would like to retrieve web pages that are the result of posting a form. Is there existing code that would let me do this easily? 3029 | 3030 | Yes. Here’s a simple example that uses httplib: 3031 | ```py 3032 | #!/usr/local/bin/python 3033 | import httplib, sys, time 3034 | ### build the query string 3035 | qs = “First=Josephine&MI=Q&Last=Public” 3036 | ### connect and send the server a path 3037 | httpobj = httplib.HTTP(‘www.some-server.out-there’, 80) 3038 | httpobj.putrequest(‘POST’, ‘/cgi-bin/some-cgi-script’) 3039 | ### now generate the rest of the HTTP headers… 3040 | httpobj.putheader(‘Accept’, ‘*/*’) 3041 | httpobj.putheader(‘Connection’, ‘Keep-Alive’) 3042 | httpobj.putheader(‘Content-type’, ‘application/x-www-form-urlencoded’) 3043 | httpobj.putheader(‘Content-length’, ‘%d’ % len(qs)) 3044 | httpobj.endheaders() 3045 | httpobj.send(qs) 3046 | ### find out what the server said in response… 3047 | reply, msg, hdrs = httpobj.getreply() 3048 | if reply != 200: 3049 | sys.stdout.write(httpobj.getfile().read()) 3050 | ``` 3051 | Note that in general for URL-encoded POST operations, query strings must be quoted by using urllib.quote(). For example to send name=”Guy Steele, Jr.”: 3052 | ```py 3053 | from urllib import quote 3054 | x = quote(“Guy Steele, Jr.”) 3055 | print(x) 3056 | ‘Guy%20Steele,%20Jr.’ 3057 | query_string = “name=”+x 3058 | query_string 3059 | ‘name=Guy%20Steele,%20Jr.’ 3060 | ``` 3061 | Q44. Why is that none of my threads are not running? How can I make it work? 3062 | 3063 | As soon as the main thread exits, all threads are killed. Your main thread is running too quickly, giving the threads no time to do any work. 3064 | A simple fix is to add a sleep to the end of the program that’s long enough for all the threads to finish: 3065 | ```py 3066 | import threading, time 3067 | def thread_task(name, n): 3068 | for i in range(n): print name, i 3069 | for i in range(10) 3070 | ``` 3071 | 3072 | Q45. Installation of Python 3.6.1 3073 | 3074 | Download the required 3.6.1 python, executable installer file from the www.python.org.com website. 3075 | > 3076 | Installation Process: 3077 | Click on the downloaded executable installer 3078 | Click On ‘Run’ 3079 | Click on Customize Installation 3080 | Click on ‘Next’ 3081 | Select the installation location by clicking on browse button 3082 | Click on ‘Install’ 3083 | Click on ‘Yes’ 3084 | Click on ‘Close’ 3085 | 3086 | Path: Path is an environment variable of operating system by using e=which we can make it available the softwares which are installed in the directory to all other directions of the operating system. 3087 | To set Path: 3088 | > 3089 | Right click on my computer 3090 | Click on properties 3091 | Click on Advanced system setting 3092 | Click on advanced 3093 | Click on environment variables 3094 | Go to system variables, select ‘path’ 3095 | Click on ‘edit’ 3096 | Copy the installation folder location of python software in the begging of the variable value 3097 | Click on ‘OK’ 3098 | Now path setting is secured. 3099 | 3100 | 3101 | Q46. What Are The Implementation In Python Program? 3102 | 3103 | Python program can be implemented by two ways 3104 | > 3105 | 1. Interactive Mode (Submit statement by statement explicitly) 3106 | 2. Batch Mode (Writing all statements and submit all statements) 3107 | 3108 | In Interactive mode python command shell is required. It is available in installation of python cell. 3109 | 3110 | In Interactive mode is not suitable for developing the projects & Applications 3111 | 3112 | Interactive mode is used for predefined function and programs. 3113 | Example: 3114 | ```py 3115 | X=1000 3116 | Y=2000 3117 | X+Y 3118 | 3000 3119 | Quit(X+Y) 3120 | ``` 3121 | X, Y is not find. 3122 | Interactive mode is unfit for looping purpose. 3123 | 3124 | Interactive Mode: 3125 | The concept of submitting one by one python statements explicitly in the python interpreter is known as “Interactive Mode” 3126 | In Order to submit the one by one python statements explicitly to the python interpreter we use python command line shell. 3127 | Python command line shell is present in python software 3128 | We can open the python command line shell by executing python command on command prompt or terminal 3129 | Example: 3130 | c:/users/mindmajix>python 3131 | `3+4` 3132 | 7 3133 | 3134 | `‘mindmajix’*3` 3135 | ‘mindmajix mindmajix mindmajix’ 3136 | 3137 | `x=1000` 3138 | `y=2000` 3139 | `x+y` 3140 | 3000 3141 | Quit 3142 | x+y 3143 | c:/users/sailu>python 3144 | Error: name ‘X’ not defined 3145 | 3146 | Batch Mode: 3147 | In the concept of writing the group of python statements in a file, save the file with extension .py and submit that entire file to the python interpreter is known as Batch Mode. 3148 | 3149 | In Order to develop the python files we use editors or IDE’s 3150 | Different editors are notepad, notepad++, edit+,nano, VI, gedil and so on. 3151 | Open the notepad and write the following code: 3152 | 3153 | Example: 3154 | ```py 3155 | X=1000 3156 | Y=2000 3157 | print(x+y, x-y, x*y) 3158 | ``` 3159 | Save the file in D drive mindmajix python folder with the demo.py 3160 | Open command prompt and execute following commands: 3161 | 3162 | Python D:/mindmajix python/Demo.py 3163 | 3164 | 3000 3165 | 3166 | -1000 3167 | 3168 | 2000.000 3169 | 3170 | Save another method if we correctly set the path 3171 | 3172 | D: 3173 | 3174 | D:/>cd "mindmajix python" 3175 | 3176 | D:/mindmajix Python>python Demo.py 3177 | `3000` 3178 | `-1000` 3179 | `2000.000` 3180 | 3181 | Q47. What are The Data Types Supports in Python Language? 3182 | 3183 | - Numbers- Numbers use to hold numerical values. 3184 | 3185 | - Strings- A string is a sequence of characters. We declare it using single or double quotes. 3186 | 3187 | - Lists- A list is an ordered collection of values, and we declare it using square brackets. 3188 | 3189 | - Tuples- A tuple, like a list, is an ordered collection of values. The difference. However, is that a tuple is immutable. This means that we cannot change a value in it. 3190 | 3191 | - Dictionary- A dictionary is a data structure that holds key-value pairs. We declare it using curly braces. 3192 | 3193 | - We can also use a dictionary comprehension: 3194 | 3195 | Numbers: 3196 | Int 3197 | Float 3198 | Complex 3199 | Boolean 3200 | Operational: 3201 | Strings 3202 | List 3203 | Tuple 3204 | Set 3205 | Dictionary 3206 | 3207 | Every data type in python language is internally implemented as a class. Python language data types are categorized into two types. 3208 | 3209 | They are: 3210 | 3211 | Fundamental Types 3212 | Collection Types 3213 | 3214 | ### _Control Flow_ 3215 | 3216 | #### Explain Control flow statements. 3217 | 3218 | By default python program execution starts from first line, execute each and every statements only once and transactions the program if the last statement of the program execution is over. 3219 | Control flow statements are used to disturb the normal flow of the execution of the program. 3220 | 3221 | #### What are the two major loop statements? 3222 | 3223 | `for and while` 3224 | 3225 | #### Under what circumstances would one use a `while` statement rather than `for`? 3226 | 3227 | The while statement is used for simple repetitive looping and the for statement is used when one wishes to iterate through a list of items, such as database records, characters in a string, etc. 3228 | 3229 | #### What happens if output an `else` statement after after block? 3230 | 3231 | The code in the else block is executed after the for loop completes, unless a break is encountered in the for loop execution. in which case the else block is not executed. 3232 | 3233 | #### Explain the use of break and continue in Python looping. 3234 | 3235 | The break statement stops execution of the current loop. and transfers control to the next block. The continue statement ends the current block’s execution and jumps to the next iteration of the loop. 3236 | 3237 | #### When would you use a continue statement in a for loop? 3238 | 3239 | When processing a particular item was complete; to move on to the next, without executing further processing in the block. The continue statement says, “I’m done processing this item, move on to the next item.” 3240 | 3241 | #### When would you use a break statement in a for loop? 3242 | 3243 | When the loop has served its purpose. As an example. after finding the item in a list searched for, there is no need to keep looping. The break statement says, I’m done in this loop; move on to the next block of code.” 3244 | 3245 | #### What is the structure of a for loop? 3246 | 3247 | for in : … The ellipsis represents a code block to be executed, once for each item in the sequence. Within the block the item is available as the current item from the entire list. 3248 | 3249 | #### What is the structure of a while loop? 3250 | 3251 | while : … The ellipsis represents a code block to be executed. until the condition becomes false. The condition is an expression that is considered true unless it evaluates to o, null or false. 3252 | 3253 | #### Use a for loop and illustrate how you would define and print the characters in a string out, one per line. 3254 | ``` 3255 | myString = “I Love Python” 3256 | for myChar hi myString: 3257 | print(myChar) 3258 | ``` 3259 | #### Given the string “I LoveQPython” use afor loop and illustrate printing each character tip to, but not including the Q. 3260 | ``` 3261 | inyString = "I Love Pijtlzon" 3262 | for myCizar in myString: 3263 | fmyC’har == 3264 | break 3265 | print(myChar) 3266 | ``` 3267 | #### Given the string “I Love Python” print out each character except for the spaces, using a for loop. 3268 | 3269 | inyString = I Love Python” 3270 | for myCizar in myString: 3271 | fmyChar == ‘’ ‘’: 3272 | continue 3273 | print myChar 3274 | 3275 | #### Illustrate how to execute a ioop ten times. 3276 | i=1 3277 | while i < 10: 3278 | 3279 | 3280 | ### _Data Types_ 3281 | 3282 | #### What is a Tuple? 3283 | 3284 | - Tuple Objects can be created by using parenthesis or by calling tuple function or by assigning multiple values to a single variable 3285 | - Tuple objects are immutable objects 3286 | - Incision order is preserved 3287 | 3288 | - Duplicate elements are allowed 3289 | 3290 | - Heterogeneous elements are allowed 3291 | 3292 | - Tuple supports both positive and negative indexing 3293 | 3294 | - The elements of the tuple can be mutable or immutable 3295 | ```py 3296 | #Example: 3297 | x=() 3298 | print(x) 3299 | print(type(x)) 3300 | print(len(x)) 3301 | y-tuple() 3302 | print(y) 3303 | print(type(y)) 3304 | print(len(y)) 3305 | z=10,20 3306 | print(z) 3307 | print(type(z)) 3308 | print(len(z)) 3309 | p=(10,20,30,40,50,10,20,10) Insertion & duplicate 3310 | print(p) 3311 | q=(100, 123.123, True, “mindmajix”) Heterogeneous 3312 | print(q) 3313 | Output: 3314 | 3315 | ``` 3316 | 3317 | #### What is the Dictionary? 3318 | 3319 | - Dictionary objects can be created by using curly braces{} or by calling dictionary function. 3320 | 3321 | - Dictionary objects are mutable objects. 3322 | 3323 | - Dictionary represents key value base. 3324 | 3325 | - Each key value pair of Dictionary is known as a item. 3326 | 3327 | - Dictionary keys must be immutable. 3328 | 3329 | - Dictionary values can be mutable or immutable. 3330 | 3331 | - Duplicate keys are not allowed but values can be duplicate. 3332 | 3333 | - Insertion order is not preserved. 3334 | 3335 | - Heterogeneous keys and heterogeneous values are allowed. 3336 | 3337 | #### How do you create a dictionary which can preserve the order of pairs? 3338 | 3339 | #### Can you use mutable Data Structure as key in Dictionaries ? 3340 | 3341 | 3342 | #### How to Search Path of Modules? 3343 | 3344 | By default python interpreter search for the imported modules in the following locations: 3345 | 3346 | - Current directory (main module location) 3347 | - Environment variable path 3348 | - Installation dependent directory 3349 | - If the imported module is not found in the any one of the above locations. Then python interpreter gives error. 3350 | - Built-in attributes of a module: 3351 | - By default for each and every python module some properties are added internally and we call those properties as a built-in-attribute of a module 3352 | 3353 | #### What are the Packages? 3354 | 3355 | Package is nothing but a folder or dictionary which represents collection of modules. 3356 | 3357 | A package can also contain sub packages. 3358 | 3359 | We can import the modules of the package by using package 3360 | name.module name or name.subpackage name.module name 3361 | 3362 | #### What is File Handling? 3363 | 3364 | File is a named location on the disk, which stores the data in permanent manner. 3365 | Python language provides various functions and methods to provide the communication between python programs and files. 3366 | Python programs can open the file, perform the read or write operations on the file and close the file 3367 | We can open the files by calling open function of built-in-modules 3368 | At the time of opening the file, we have to specify the mode of the file 3369 | Mode of the file indicates for what purpose the file is going to be opened(r,w,a,b) 3370 | 3371 | #### What are the Runtime Errors? 3372 | 3373 | The errors which occurs after starting the execution of the programs are known as runtime errors. Runtime errors can occur because of: 3374 | 3375 | Invalid Input 3376 | Invalid Logic 3377 | Memory issues 3378 | Hardware failures and so on 3379 | 3380 | With respect to every reason which causes to runtime error correspoing runtime error representation class is available 3381 | Runtime error representation classes technically we call as a exception classes. 3382 | While executing the program if any runtime error is occur corresponding runtime error representation class object is created 3383 | Creating runtime error representation class object is technically known as a rising exception 3384 | While executing the program if any exception is raised, then internally python interpreter verify any code is implemented to handle raised exception or not 3385 | If code is not implemented to handle raised exception then program will be terminated abnormally 3386 | 3387 | #### What is Abnormal Termination? 3388 | 3389 | The concept of terminating the program in the middle of its execution without executing last statement of the main module is known as a abnormal termination 3390 | Abnormal termination is undesirable situation in programming languages. 3391 | 3392 | #### What is `try` Block? 3393 | 3394 | A block which is preceded by the try keyword is known as a try block 3395 | Syntax: 3396 | try{ 3397 | //statements that may cause an exception 3398 | } 3399 | 3400 | The statements which causes to run time errors and other statements which depends on the execution of run time errors statements are recommended to represent in try block 3401 | While executing try block statement if any exception is raised then immediately try block identifies that exception, receive that exception and forward that exception to except block without executing remaining statements to try block. 3402 | 3403 | #### What is the Difference Between Methods & Constructors? 3404 | 3405 | Methods 3406 | - Method name can be any name. 3407 | - With respect to one object one method can be called for ‘n’ members of lines 3408 | - Methods are used to represent business logic to perform the operations 3409 | 3410 | Constructor 3411 | - Constructor will be executed automatically whenever we create a object. 3412 | - With respect to one object one constructor can be executed only once 3413 | - Constructors are used to define & initialize the non static variable 3414 | 3415 | #### What is the Encapsulation? 3416 | 3417 | The concept of binding or grouping related data members along with its related functionalities is known as a Encapsulation. 3418 | 3419 | 3420 | 3421 | #### Executing DML Commands Through Python Programs? 3422 | 3423 | DML (Data Modification Language) Commands are used to modify the data of the database objects 3424 | Whenever we execute DML Commands the records are going to be modified temporarily. 3425 | 3426 | Whenever we run “rollback” command the modified records will come back to its original state. 3427 | 3428 | To modify the records of the database objects permanently we use “commit” command 3429 | 3430 | After executing the commit command even though we execute “rollback” command, the modified records will not come back to its original state. 3431 | 3432 | Create the emp1 table in the database by using following command 3433 | `Create table emp1 as select * from emp;` 3434 | 3435 | Whenever we run the DML commands through the python program, then the no.of records which are modified because of that command will be stored into the rowcount attribute of cursor object. 3436 | After executing the DML Command through the python program we have to call commit method of cursor object. 3437 | 3438 | ### _Multithreading_ 3439 | 3440 | #### What is Threads Life Cycle? 3441 | 3442 | Threads Life Cycle 3443 | 3444 | - Creating the object of a class which is overwriting run method of thread class is known as a creating thread. 3445 | - Whenever thread is created then we call thread is in new state or birth state thread. 3446 | - Whenever we call the start method on the new state threads then those threads will be forwarded for scheduling. 3447 | - The threads which are forwarded for scheduling are known as ready state threads 3448 | - Whenever scheduling time occurs, ready state thread starts execution. 3449 | - The threads which are executing are known as running state threads 3450 | Whenever sleep fun or join methods are called on the running state threads then immediately those threads will wait. 3451 | - The threads which are waiting are known as waiting state threads 3452 | Whenever waiting time is over or specified thread execution is over - then immediately waiting state threads are forwarded for scheduling. 3453 | - If running state threads execution is over then immediately those threads execution will be terminated 3454 | -The threads which execution is terminated are known as dead state threads. 3455 | 3456 | #### What is scheduling? 3457 | 3458 | Among multiple threads: 3459 | - which thread as to start the execution first, 3460 | - How much time the thread as to execute after allocated time 3461 | is over, 3462 | - which thread as to continue the execution next this comes under scheduling. Scheduling is highly dynamic 3463 | 3464 | 3465 | #### for loop is implemented in python language as follows: 3466 | ```py 3467 | for element in iterable: 3468 | iter-obj=iter(iterable) 3469 | while true: 3470 | try: 3471 | element=next(iter_obj) 3472 | except(slop iteration) 3473 | break 3474 | ``` 3475 | For loop takes the given object, convert that object in the form of iterable object & gets the one by one element form the iterable object. 3476 | 3477 | While getting the one by value element from the iterable object if stop iteration exception is raised then for loop internally handle that exception 3478 | 3479 | 3480 | Q68. OS Module 3481 | 3482 | OS Module is a predefined module and which provides various functions and methods to perform the operating system related activities, such as creating the files, removing the files, creating the directories removing the directories, executing the operating system related commands, etc. 3483 | Example: 3484 | ```py 3485 | import os 3486 | cwd=os.getwd() 3487 | print(“1”, cwd) 3488 | os.chdir(“samples”) 3489 | print(“2”, os.getcwd()) 3490 | os.chdir(os.pardir) 3491 | print(“3”,os.getcwd()) 3492 | ``` 3493 | Output: 3494 | 3495 | 3496 | 3497 | #### What Are Applications of Python? 3498 | 3499 | Applications of Python 3500 | 3501 | - Automation App 3502 | - Data Analytics 3503 | - Scientific App 3504 | - Web App 3505 | - Web Scrapping 3506 | - Test Cases 3507 | - Network with IOT 3508 | - Admin Script 3509 | - GUI 3510 | - Gaming 3511 | - Animation 3512 | 3513 | 3514 | #### What is PEP 8? 3515 | 3516 | PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable. 3517 | 3518 | #### How Python is interpreted? 3519 | 3520 | Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed. 3521 | 3522 | #### What are the tools that help to find bugs or perform static analysis? 3523 | 3524 | PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard. 3525 | 3526 | 3527 | 3528 | - What is pass in Python? 3529 | 3530 | Pass means, no-operation Python statement, or in other words it is a place holder in compound statement, where there should be a blank left and nothing has to be written there. 3531 | 3532 | - In Python what are iterators? 3533 | 3534 | In Python, iterators are used to iterate a group of elements, containers like list. 3535 | 3536 | 3537 | - In Python what is slicing? 3538 | 3539 | A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known as slicing. 3540 | 3541 | - What are generators in Python? 3542 | 3543 | The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function. 3544 | Python generator produces a sequence of values to iterate on. This way, it is kind of an iterable. We define a function that ‘yields’ values one by one, and then use a for loop to iterate on it. 3545 | ``` 3546 | def squares(n): 3547 | i=1 3548 | while(i<=n): 3549 | yield i**2 3550 | i+=1 3551 | for i in squares(7): 3552 | print(i) 3553 | ``` 3554 | 3555 | 1 3556 | 4 3557 | 9 3558 | 16 3559 | 25 3560 | 36 3561 | 49 3562 | 3563 | #### So, what is an iterator, then? 3564 | 3565 | An iterator returns one object at a time to iterate on. To create an iterator, we use the iter() function. 3566 | 3567 | odds=iter([1,3,5]) 3568 | 3569 | Then, we call the next() function on it every time we want an object. 3570 | 3571 | next(odds) 3572 | 1 3573 | 3574 | next(odds) 3575 | 3 3576 | 3577 | next(odds) 3578 | 5 3579 | 3580 | And now, when we call it again, it raises a StopIteration exception. This is because it has reached the end of the values to iterate on. 3581 | 3582 | next(odds) 3583 | 3584 | Traceback (most recent call last): 3585 | File “”, line 1, in next(odds) 3586 | StopIteration 3587 | 3588 | #### we asked you about generators and iterators, and you gave us the right answers. But don’t they sound similar? 3589 | 3590 | - They do, but there are subtle differences: 3591 | 3592 | - For a generator, we create a function. For an iterator, we use in-built functions `iter()` and `next()`. 3593 | 3594 | - For a generator, we use the keyword ‘yield’ to yield/return an object at a time. 3595 | 3596 | - A generator may have as many ‘yield’ statements as you want. 3597 | 3598 | - A generator will save the states of the local variables every time ‘yield’ will pause the loop. 3599 | 3600 | 3601 | - An iterator does not use local variables; it only needs an iterable to iterate on. 3602 | 3603 | - Using a class, you can implement your own iterator, but not a generator. 3604 | 3605 | - Generators are fast, compact, and simpler. 3606 | 3607 | - Iterators are more memory-efficient. 3608 | 3609 | 3610 | - How can you copy an object in Python? 3611 | 3612 | To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them. 3613 | 3614 | 3615 | 3616 | - How you can convert a number to a string? 3617 | 3618 | In order to convert a number into a string, use the inbuilt function str(). If you want a octal or hexadecimal representation, use the inbuilt function oct() or hex(). 3619 | 3620 | - What is module and package in Python? 3621 | 3622 | In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes. 3623 | 3624 | The folder of Python program is a package of modules. A package can have modules or subfolders. 3625 | 3626 | - Mention what are the rules for local and global variables in Python? 3627 | 3628 | Local variables: If a variable is assigned a new value anywhere within the function's body, it's assumed to be local. 3629 | 3630 | Global variables: Those variables that are only referenced inside a function are implicitly global. 3631 | 3632 | - How can you share global variables across modules? 3633 | 3634 | To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules. 3635 | 3636 | - Explain how can you make a Python Script executable on Unix? 3637 | 3638 | To make a Python Script executable on Unix, you need to do two things, 3639 | 3640 | Script file's mode must be executable and 3641 | the first line must begin with # ( #!/usr/local/bin/python) 3642 | 3643 | - Explain how to delete a file in Python? 3644 | 3645 | By using a command os.remove (filename) or os.unlink(filename) 3646 | 3647 | - Explain how can you generate random numbers in Python? 3648 | 3649 | To generate random numbers in Python, you need to import command as 3650 | ```py 3651 | import random 3652 | random.random() 3653 | ``` 3654 | 3655 | This returns a random floating point number in the range (0,1) 3656 | 3657 | - Explain how can you access a module written in Python from C? 3658 | 3659 | You can access a module written in Python from C by following method, 3660 | 3661 | Module = =PyImport_ImportModule(""); 3662 | 3663 | - Mention the use of // operator in Python? 3664 | 3665 | It is a Floor Divisionoperator , which is used for dividing two operands with the result as quotient showing only digits before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0. 3666 | 3667 | - Mention five benefits of using Python? 3668 | - Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc. 3669 | - Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically 3670 | - Provide easy readability due to use of square brackets 3671 | - Easy-to-learn for beginners 3672 | - Having the built-in data types saves programming time and effort from declaring variables 3673 | 3674 | - Mention the use of the split function in Python? 3675 | 3676 | The use of the split function in Python is that it breaks a string into shorter strings using the defined separator. It gives a list of all words present in the string. 3677 | 3678 | - Mention what is the difference between Django, Pyramid, and Flask? 3679 | 3680 | Flask is a "microframework" primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use. 3681 | 3682 | Pyramid are build for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable. 3683 | 3684 | Like Pyramid, Django can also used for larger applications. It includes an ORM. 3685 | 3686 | - You are having multiple Memcache servers running Python, in which one of the memcacher server fails, and it has your data, will it ever try to get key data from that one failed server? 3687 | 3688 | The data in the failed server won't get removed, but there is a provision for auto-failure, which you can configure for multiple nodes. Fail-over can be triggered during any kind of socket or Memcached server level errors and not during normal client errors like adding an existing key, etc. 3689 | 3690 | - Explain how you can minimize the Memcached server outages in your Python Development? 3691 | 3692 | - When one instance fails, several of them goes down, this will put larger load on the database server when lost data is reloaded as client make a request. To avoid this, if your code has been written to minimize cache stampedes then it will leave a minimal impact 3693 | - Another way is to bring up an instance of Memcached on a new machine using the lost machines IP address 3694 | - Code is another option to minimize server outages as it gives you the liberty to change the Memcached server list with minimal work 3695 | - Setting timeout value is another option that some Memcached clients implement for Memcached server outage. When your Memcached server goes down, the client will keep trying to send a request till the time-out limit is reached 3696 | 3697 | - Explain what is Dogpile effect? How can you prevent this effect? 3698 | 3699 | Dogpile effect is referred to the event when cache expires, and websites are hit by the multiple requests made by the client at the same time. 3700 | This effect can be prevented by using semaphore lock. In this system when value expires, first process acquires the lock and starts generating new value. 3701 | 3702 | - Explain how Memcached should not be used in your Python project? 3703 | 3704 | Memcached common misuse is to use it as a data store, and not as a cache. Never use Memcached as the only source of the information you need to run your application. Data should always be available through another source as well. Memcached is just a key or value store and cannot perform query over the data or iterate over the contents to extract information. 3705 | Memcached does not offer any form of security either in encryption or authentication 3706 | 3707 | 3708 | #### What is List Comprehensions feature of Python used for? 3709 | 3710 | List comprehensions help to create and manage lists in a simpler and clearer way than using `map()`, `filter()` and `lambda`. Each list comprehension consists of an expression followed by a for clause, then zero or more for or if clauses. 3711 | 3712 | #### What are lambda expressions, list comprehensions and generator expressions? What are the advantages and appropriate uses of each? 3713 | 3714 | **Lambda expressions** are a shorthand technique for creating single line, anonymous functions. Their simple, inline nature often – though not always – leads to more readable and concise code than the alternative of formal function declarations. On the other hand, their terse inline nature, by definition, very much limits what they are capable of doing and their applicability. Being anonymous and inline, the only way to use the same lambda function in multiple locations in your code is to specify it redundantly. 3715 | 3716 | **List comprehensions** provide a concise syntax for creating lists. List comprehensions are commonly used to make lists where each element is the result of some operation(s) applied to each member of another sequence or iterable. They can also be used to create a subsequence of those elements whose members satisfy a certain condition. In Python, list comprehensions provide an alternative to using the built-in map() and filter() functions. 3717 | 3718 | As the applied usage of lambda expressions and list comprehensions can overlap, opinions vary widely as to when and where to use one vs. the other. One point to bear in mind, though, is that a list comprehension executes somewhat faster than a comparable solution using map and lambda (some quick tests yielded a performance difference of roughly 10%). This is because calling a lambda function creates a new stack frame while the expression in the list comprehension is evaluated without doing so. 3719 | 3720 | **Generator expressions** are syntactically and functionally similar to list comprehensions but there are some fairly significant differences between the ways the two operate and, accordingly, when each should be used. In a nutshell, iterating over a generator expression or list comprehension will essentially do the same thing, but the list comprehension will create the entire list in memory first while the generator expression will create the items on the fly as needed. Generator expressions can therefore be used for very large (and even infinite) sequences and their lazy (i.e., on demand) generation of values results in improved performance and lower memory usage. It is worth noting, though, that the standard Python list methods can be used on the result of a list comprehension, but not directly on that of a generator expression. 3721 | 3722 | - Consider the two approaches below for initializing an array and the arrays that will result. How will the resulting arrays differ and why should you use one initialization approach vs. the other? 3723 | 3724 | ```py 3725 | # INITIALIZING AN ARRAY -- METHOD 1 3726 | ... 3727 | x = [[1,2,3,4]] * 3 3728 | x 3729 | [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]] 3730 | 3731 | 3732 | # INITIALIZING AN ARRAY -- METHOD 2 3733 | ... 3734 | y = [[1,2,3,4] for _ in range(3)] 3735 | y 3736 | [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]] 3737 | 3738 | # WHICH METHOD SHOULD YOU USE AND WHY? 3739 | ``` 3740 | **Ans:** 3741 | While both methods appear at first blush to produce the same result, there is an extremely significant difference between the two. Method 2 produces, as you would expect, an array of 3 elements, each of which is itself an independent 4-element array. In method 1, however, the members of the array all point to the same object. This can lead to what is most likely unanticipated and undesired behavior as shown below. 3742 | 3743 | ```py 3744 | # MODIFYING THE x ARRAY FROM THE PRIOR CODE SNIPPET: 3745 | x[0][3] = 99 3746 | x 3747 | [[1, 2, 3, 99], [1, 2, 3, 99], [1, 2, 3, 99]] 3748 | 3749 | # UH-OH, DON’T THINK YOU WANTED THAT TO HAPPEN! 3750 | ... 3751 | # MODIFYING THE y ARRAY FROM THE PRIOR CODE SNIPPET: 3752 | y[0][3] = 99 3753 | y 3754 | [[1, 2, 3, 99], [1, 2, 3, 4], [1, 2, 3, 4]] 3755 | # THAT’S MORE LIKE WHAT YOU EXPECTED! 3756 | ... 3757 | ``` 3758 | 3759 | Q: What will be printed out by the second append() statement below? 3760 | ```py 3761 | def append(list=[]): 3762 | # append the length of a list to the list 3763 | list.append(len(list)) 3764 | return list 3765 | 3766 | append(['a','b']) 3767 | ['a', 'b', 2] 3768 | ``` 3769 | append() # calling with no arg uses default list value of [][0] 3770 | 3771 | append() # but what happens when we AGAIN call append with no arg? 3772 | 3773 | **Ans:** 3774 | When the default value for a function argument is an expression, the expression is evaluated only once, not every time the function is called. Thus, once the list argument has been initialized to an empty array, subsequent calls to append without any argument specified will continue to use the same array to which list was originally initialized. This will therefore yield the following, presumably unexpected, behavior: 3775 | 3776 | append() # first call with no arg uses default list value of [][0] 3777 | append() # but then look what happens...[0, 1] 3778 | append() # successive calls keep extending the same default list! 3779 | [0, 1, 2] 3780 | append() # and so on, and so on, and so on... 3781 | [0, 1, 2, 3] 3782 | 3783 | - How might one modify the implementation of the `append` method in the previous question to avoid the undesirable behavior described there? 3784 | 3785 | The following alternative implementation of the append method would be one of a number of ways to avoid the undesirable behavior described in the answer to the previous question: 3786 | 3787 | ```py 3788 | def append(list=None): 3789 | if list is None: 3790 | list = [] 3791 | # append the length of a list to the list 3792 | list.append(len(list)) 3793 | return list 3794 | append() 3795 | [0] 3796 | append() 3797 | [0] 3798 | ``` 3799 | Q: How can you swap the values of two variables with a single line of Python code? 3800 | 3801 | Consider this simple example: 3802 | ``` 3803 | x = 'X' 3804 | y = 'Y' 3805 | ``` 3806 | In many other languages, swapping the values of x and y requires that you to do the following: 3807 | ``` 3808 | tmp = x 3809 | x = y 3810 | y = tmp 3811 | x, y 3812 | ('Y', 'X') 3813 | ``` 3814 | 3815 | But in Python, makes it possible to do the swap with a single line of code (thanks to implicit tuple packing and unpacking) as follows: 3816 | ``` 3817 | x,y = y,x 3818 | x,y 3819 | ('Y', 'X') 3820 | ``` 3821 | Q: What will be printed out by the last statement below? 3822 | ```py 3823 | flist = [] 3824 | for i in range(3): 3825 | flist.append(lambda: i) 3826 | 3827 | [f() for f in flist] # what will this print out? 3828 | ``` 3829 | In any closure in Python, variables are bound by name. Thus, the above line of code will print out the following: 3830 | [2, 2, 2] 3831 | Presumably not what the author of the above code intended? 3832 | 3833 | A workaround is to either create a separate function or to pass the args by name; e.g.: 3834 | ```py 3835 | flist = [] 3836 | for i in range(3): 3837 | flist.append(lambda i = i : i) 3838 | 3839 | [f() for f in flist] 3840 | [0, 1, 2] 3841 | ``` 3842 | 3843 | #### Is Python interpreted or compiled? 3844 | 3845 | As noted in Why Are There So Many Pythons?, this is, frankly, a bit of a trick question in that it is malformed. Python itself is nothing more than an interface definition (as is true with any language specification) of which there are multiple implementations. Accordingly, the question of whether “Python” is interpreted or compiled does not apply to the Python language itself; rather, it applies to each specific implementation of the Python specification. 3846 | 3847 | Further complicating the answer to this question is the fact that, in the case of CPython (the most common Python implementation), the answer really is "sort of both". Specifically, with CPython, code is first compiled and then interpreted. More precisely, it is not precompiled to native machine code, but rather to bytecode. While machine code is certainly faster, bytecode is more portable and secure. The bytecode is then interpreted in the case of CPython (or both interpreted and compiled to optimized machine code at runtime in the case of PyPy). 3848 | 3849 | #### What are some alternative implementations to CPython? When and why might you use them? 3850 | 3851 | One of the more prominent alternative implementations is Jython, a Python implementation written in Java that utilizes the Java Virtual Machine (JVM). While CPython produces bytecode to run on the CPython VM, Jython produces Java bytecode to run on the JVM. 3852 | 3853 | Another is IronPython, written in C# and targeting the .NET stack. IronPython runs on Microsoft’s Common Language Runtime (CLR). 3854 | 3855 | As also pointed out in Why Are There So Many Pythons?, it is entirely possible to survive without ever touching a non-CPython implementation of Python, but there are advantages to be had from switching, most of which are dependent on your technology stack. 3856 | 3857 | Another noteworthy alternative implementation is PyPy whose key features include: 3858 | 3859 | - Speed. Thanks to its Just-in-Time (JIT) compiler, Python programs often run faster on PyPy. 3860 | - Memory usage. Large, memory-hungry Python programs might end up taking less space with PyPy than they do in CPython. 3861 | - Compatibility. PyPy is highly compatible with existing python code. It supports cffi and can run popular Python libraries like Twisted and Django. 3862 | - Sandboxing. PyPy provides the ability to run untrusted code in a fully secure way. 3863 | - Stackless mode. PyPy comes by default with support for stackless mode, providing micro-threads for massive concurrency. 3864 | 3865 | #### What is unittest in Python? What’s your approach to unit testing in Python? 3866 | 3867 | A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections etc. 3868 | 3869 | The most fundamental answer to this question centers around Python’s unittest testing framework. Basically, if a candidate doesn’t mention unittest when answering this question, that should be a huge red flag. 3870 | 3871 | `unittest` supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework. The unittest module provides classes that make it easy to support these qualities for a set of tests. 3872 | 3873 | Assuming that the candidate does mention unittest (if they don’t, you may just want to end the interview right then and there!), you should also ask them to describe the key elements of the unittest framework; namely, test fixtures, test cases, test suites and test runners. 3874 | 3875 | A more recent addition to the unittest framework is mock. mock allows you to replace parts of your system under test with mock objects and make assertions about how they are to be used. mock is now part of the Python standard library, available as unittest.mock in Python 3.3 onwards. 3876 | 3877 | The value and power of mock are well explained in An Introduction to Mocking in Python. As noted therein, system calls are prime candidates for mocking: whether writing a script to eject a CD drive, a web server which removes antiquated cache files from /tmp, or a socket server which binds to a TCP port, these calls all feature undesired side-effects in the context of unit tests. Similarly, keeping your unit-tests efficient and performant means keeping as much “slow code” as possible out of the automated test runs, namely filesystem and network access. 3878 | 3879 | [Note: This question is for Python developers who are also experienced in Java.] 3880 | 3881 | 3882 | 3883 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # python_interview_preparation --------------------------------------------------------------------------------