├── 350interview.txt └── README.md /350interview.txt: -------------------------------------------------------------------------------- 1 | 2 | Python Interview Questions and Answers by Pythonlife 3 | 4 | 5 | 6 | 1. What is Python? What are the benefits of using Python? 7 | Ans: Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source. 8 | 9 | 10 | 11 | 12 | 13 | 2. What is PEP 8? 14 | Ans: PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable. 15 | 16 | 17 | 18 | 19 | 20 | 21 | 3. What is pickling and unpickling? 22 | Ans: 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. 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 4. How Python is interpreted? 32 | Ans: 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. 33 | 34 | 35 | 36 | 37 | 38 | 39 | 5. How memory is managed in Python? 40 | Ans: 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 takes care of this Python private heap. 41 | 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. 42 | 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. 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 6. What are the tools that help to find bugs or perform static analysis? 52 | Ans: 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. 53 | 54 | 55 | 56 | 57 | 58 | 7. What are Python decorators? 59 | Ans: A Python decorator is a specific change that we make in Python syntax to alter functions easily. 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 8. What is the difference between list and tuple? 69 | Ans: The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries. 70 | 71 | 72 | 73 | 74 | 75 | 76 | 9. How are arguments passed by value or by reference? 77 | Ans: 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. 78 | 79 | 80 | 81 | 82 | 83 | 10. What is Dict and List comprehensions are? 84 | Ans: They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable. 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 11. What are the built-in type does python provides? 94 | Ans: There are mutable and Immutable types of Pythons built in types Mutable built-in types 95 | List Sets 96 | Dictionaries Immutable built-in types 97 | Strings Tuples Numbers 98 | 99 | 100 | 101 | 12. What is namespace in Python? 102 | Ans: 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. 103 | 104 | 105 | 106 | 107 | 108 | 13. What is lambda in Python? 109 | Ans: It is a single expression anonymous function often used as In-line function. 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 14. Why lambda forms in python does not have statements? 119 | Ans: A lambda form in python does not have statements as it is used to make new function object and then return them at runtime. 120 | 121 | 122 | 123 | 15. What is pass in Python? 124 | Ans: 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. 125 | 126 | 127 | 128 | 129 | 130 | 16. In Python what are iterators? 131 | Ans: In Python, iterators are used to iterate a group of elements, containers like list. 132 | 133 | 134 | 135 | 17. What is unit test in Python? 136 | Ans: 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. 137 | 138 | 139 | 140 | 141 | 18. In Python what is slicing? 142 | Ans: A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known as slicing. 143 | 144 | 145 | 146 | 19. What are generators in Python? 147 | Ans: The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function. 148 | 149 | 150 | 151 | 20. What is docstring in Python? 152 | Ans: A Python documentation string is known as docstring, it is a way of documenting Python functions, modules and classes. 153 | 154 | 155 | 156 | 157 | 21. How can you copy an object in Python? 158 | Ans: 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. 159 | 160 | 161 | 162 | 22. What is negative index in Python? 163 | Ans: 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. 164 | 165 | 166 | 167 | 23. How you can convert a number to a string? 168 | Ans: 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(). 169 | 170 | 171 | 172 | 173 | 24. What is the difference between Xrange and range? 174 | Ans: Xrange returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is. 175 | 176 | 177 | 178 | 179 | 25. What is module and package in Python? 180 | Ans: In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes. 181 | The folder of Python program is a package of modules. A package can have modules or subfolders. 182 | 183 | 184 | 185 | 186 | 26. Mention what are the rules for local and global variables in Python? 187 | Ans: Local variables: If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be local. 188 | 189 | Global variables: Those variables that are only referenced inside a function are implicitly global. 190 | 191 | 192 | 193 | 194 | 195 | 27. How can you share global variables across modules? 196 | Ans: 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. 197 | 198 | 199 | 200 | 201 | 202 | 203 | 28. Explain how can you make a Python Script executable on Unix?To make a Python Script executable on Unix, you need to do two things, 204 | Ans: Script file’s mode must be executable and 205 | the first line must begin with # ( #!/usr/local/bin/python) 206 | 207 | 208 | 209 | 210 | 211 | 212 | 29. Explain how to delete a file in Python? 213 | Ans: By using a command os.remove (filename) or os.unlink(filename) 214 | 215 | 216 | 217 | 218 | 219 | 30. Explain how can you generate random numbers in Python? 220 | Ans: To generate random numbers in Python, you need to import command as import random 221 | random.random() 222 | This returns a random floating point number in the range [0,1) 223 | 224 | 225 | 226 | 227 | 228 | 229 | 31. Explain how can you access a module written in Python from C? 230 | Ans: You can access a module written in Python from C by following method, Module = =PyImport_ImportModule(“”); 231 | 232 | 233 | 234 | 235 | 236 | 237 | 32. Mention the use of // operator in Python? 238 | Ans: 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. 239 | 240 | 241 | 242 | 243 | 33. Mention five benefits of using Python? 244 | Ans: Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc. 245 | Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically 246 | Provide easy readability due to use of square brackets Easy-to-learn for beginners 247 | Having the built-in data types saves programming time and effort from declaring variables 248 | 249 | 250 | 251 | 252 | 253 | 254 | 34. Mention the use of the split function in Python? 255 | Ans: 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. 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 35. Explain what is Flask & its benefits? 264 | Ans: Flask is a web micro framework for Python based on “Werkzeug, Jinja 2 and good intentions” BSD licensed. Werkzeug and jingja are two of its dependencies. 265 | 266 | 267 | 268 | 269 | 270 | 271 | Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries. It makes the framework light while there is little dependency to update and less security bugs. 272 | 273 | 274 | 275 | 276 | 277 | 36. Mention what is the difference between Django, Pyramid, and Flask? 278 | Ans: Flask is a “micro framework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use. 279 | 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. 280 | 281 | Like Pyramid, Django can also used for larger applications. It includes an ORM. 282 | 283 | 284 | 285 | 286 | 287 | 288 | 37. Mention what is Flask-WTF and what are their features? 289 | Ans: Flask-WTF offers simple integration with WTForms. Features include for Flask WTF are 290 | Integration with wtforms Secure form with csrf token Global csrf protection Internationalization integration Recaptcha supporting 291 | File upload that works with Flask Uploads 292 | 293 | 294 | 295 | 296 | 297 | 298 | 38. Explain what is the common way for the Flask script to work? 299 | Ans: The common way for the flask script to work is… 300 | Either it should be the import path for your application Or the path to a Python file 301 | 302 | 303 | 304 | 305 | 306 | 307 | 39. Explain how you can access sessions in Flask? 308 | Ans: A session basically allows you to remember information from one request to another. In a flask, it uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key. 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 40. Is Flask an MVC model and if yes give an example showing MVC pattern for your application? 317 | Ans: Basically, Flask is a minimalistic framework which behaves same as MVC framework. So MVC is a perfect fit for Flask, and the pattern for MVC we will consider for the following example 318 | 319 | 320 | from flask import Flaskapp = Flask(_name_) 321 | @app.route(“/”) 322 | 323 | Def hello(): 324 | 325 | return “Hello World” 326 | 327 | app.run(debug = True) 328 | 329 | In this code your, 330 | Configuration part will be 331 | from flask import Flask 332 | 333 | app = Flask(_name_) 334 | 335 | View part will be 336 | @app.route(“/”) 337 | 338 | Def hello(): 339 | 340 | return “Hello World” 341 | 342 | While you model or main part will be 343 | app.run(debug = True) 344 | 345 | 346 | 347 | 348 | 349 | 350 | 41. What type of a language is python? Interpreted or Compiled? 351 | Ans: Beginner’s Answer: 352 | Python is an interpreted, interactive, objectoriented programming language. 353 | Expert Answer: 354 | Python is an interpreted language, as opposed to a compiled one, though the 355 | distinction can be blurry because of the presence of the bytecode compiler. This means 356 | that source files can be run directly without explicitly creating an executable which is 357 | then run. 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 42. What do you mean by python being an “interpreted language”? (Continues from previous question) 366 | Ans: An interpreted languageis a programming languagefor which most of its 367 | implementations execute instructions directly, without previously compiling a program 368 | into machinelanguageinstructions. In context of Python, it means that Python program 369 | runs directly from the source code. 370 | 371 | 372 | 373 | 374 | 375 | 376 | 43. What is python’s standard way of identifying a block of code? 377 | Ans: Indentation. 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 44. Please provide an example implementation of a function called “my_func” that returns the square of a given variable “x”. (Continues from previous question) 386 | Ans: 387 | defmy_func(x): 388 | returnx**2 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 45. Is python statically typed or dynamically typed? 397 | Ans: Dynamic. 398 | In a statically typed language, the type of variables must be known (and usually 399 | declared) at the point at which it is used. Attempting to use it will be an error. In a 400 | dynamically typed language, objects still have a type, but it is determined at runtime. 401 | You are free to bind names (variables) to different objects with a different type. So long 402 | as you only perform operations valid for the type the interpreter doesn’t care what type 403 | they actually are. 404 | 405 | 406 | 407 | 408 | 409 | 46. Is python strongly typed or weakly typed language? 410 | Ans: Strong. 411 | In a weakly typed language a compiler / interpreter will sometimes change the 412 | type of a variable. For example, in some languages (like JavaScript) you can add 413 | strings to numbers ‘x’ + 3 becomes ‘x3’. This can be a problem because if you have 414 | made a mistake in your program, instead of raising an exception execution will continue 415 | but your variables now have wrong and unexpected values. In a strongly typed 416 | language (like Python) you can’t perform operations inappropriate to the type of the 417 | object attempting to add numbers to strings will fail. Problems like these are easier to 418 | diagnose because the exception is raised at the point where the error occurs rather than 419 | at some other, potentially far removed, place. 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 47. Create a unicode string in python with the string “This is a test string”? 428 | Ans: some_variable=u’Thisisateststring’ 429 | Or 430 | some_variable=u”Thisisateststring” 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 48. What is the python syntax for switch case statements? 439 | Ans: Python doesn’t support switchcase statements. You can use ifelse statements 440 | for this purpose. 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 49. What is a lambda statement? Provide an example. 452 | Ans: A lambda statement is used to create new function objects and then return them at 453 | runtime. Example: 454 | my_func=lambdax:x**2 455 | creates a function called my_func that returns the square of the argument 456 | passed. 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 50.What are the rules for local and global variables in Python? 466 | Ans: If a variable is defined outside function then it is implicitly global. If variable is 467 | assigned new value inside the function means it is local. If we want to make it global we 468 | 469 | need to explicitly define it as global. Variable referenced inside the function are implicit 470 | global 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 51.What is the output of the following program? 480 | Ans: 481 | 482 | #!/usr/bin/python 483 | deffun1(a): 484 | print’a:’,a 485 | a=33; 486 | print’locala:’,a 487 | a=100 488 | fun1(a) 489 | print’aoutsidefun1:’,a 490 | Ans. Output: 491 | a:100 492 | locala:33 493 | aoutsidefun1:100 494 | 495 | 496 | 497 | 498 | 499 | 500 | 501 | 502 | 503 | 504 | 52.What is the output of the following program? 505 | Ans: 506 | 507 | #!/usr/bin/python 508 | deffun2(): 509 | globalb 510 | print’b:’,b 511 | b=33 512 | print’globalb:’,b 513 | b=100 514 | fun2() 515 | print’boutsidefun2′,b 516 | Ans. Output: 517 | b:100 518 | globalb:33 519 | boutsidefun2:33 520 | 521 | 522 | 523 | 524 | 525 | 526 | 53. What is the output of the following program? 527 | Ans: 528 | 529 | #!/usr/bin/python 530 | 531 | deffoo(x,y): 532 | globala 533 | a=42 534 | x,y=y,x 535 | b=33 536 | b=17 537 | c=100 538 | print(a,b,x,y) 539 | a,b,x,y=1,15,3,4 540 | foo(17,4) 541 | print(a,b,x,y) 542 | 543 | Ans.Output: 544 | 4217417 545 | 421534 546 | 547 | 54.What is the output of the following program? 548 | Ans: 549 | 550 | #!/usr/bin/python 551 | deffoo(x=[]): 552 | x.append(1) 553 | returnx 554 | foo() 555 | foo() 556 | 557 | Output: 558 | [1] 559 | [1,1] 560 | 561 | 55. What is the purpose of #!/usr/bin/pythonon the first line in the above 562 | code? Is there any advantage? 563 | Ans: By specifying #!/usr/bin/pythonyou specify exactly which interpreter will be 564 | used to run the script on a particular system. This is the hardcoded path to the python 565 | interpreter for that particular system. The advantage of this line is that you can use a 566 | specific python version to run your code. 567 | 568 | 56.What is the output of the following program? 569 | Ans: 570 | 571 | list=[‘a’,’b’,’c’,’d’,’e’] 572 | printlist[10] 573 | Ans. Output: 574 | IndexError.Or Error. 575 | 576 | 57.What is the output of the following program? 577 | Ans: 578 | 579 | list=[‘a’,’b’,’c’,’d’,’e’] 580 | printlist[10:] 581 | Ans. Output: 582 | [] 583 | Theabovecodewilloutput[],andwillnotresultinanIndexError. 584 | As one would expect, attempting to access a member of a list using an index that 585 | exceeds the number of members results in an IndexError. 586 | 587 | 58. What does this list comprehension do: 588 | Ans: 589 | 590 | [x**2forxinrange(10)ifx%2==0] 591 | Ans. Creates the following list: 592 | [0,4,16,36,64] 593 | 594 | 59. Do sets, dictionaries and tuples also support comprehensions? 595 | Ans: Sets and dictionaries support it. However tuples are immutable and have 596 | generators but not comprehensions. 597 | Set Comprehension: 598 | r={xforxinrange(2,101) 599 | ifnotany(x%y==0foryinrange(2,x))} 600 | Dictionary Comprehension: 601 | {i:jfori,jin{1:’a’,2:’b’}.items()} 602 | since 603 | {1:’a’,2:’b’}.items()returnsalistof2-Tuple.iisthefirstelement 604 | oftuplejisthesecond. 605 | 606 | 60.What are some mutable and immutable datatypes/datastructures in 607 | python? 608 | Ans: 609 | Mutable Types Immutable Types 610 | 611 | Dictionary number 612 | List boolean 613 | string 614 | tuple 615 | 616 | 61.What are generators in Python? 617 | Ans: Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object. 618 | Let’s try and build a generator for fibonacci numbers – 619 | 620 | ## generate fibonacci numbers upto n 621 | def fib(n): 622 | p, q = 0, 1 623 | while(p < n): 624 | yield p 625 | p, q = q, p + q 626 | 627 | x = fib(10) # create generator object 628 | 629 | ## iterating using __next__(), for Python2, use next() 630 | x.__next__() # output => 0 631 | x.__next__() # output => 1 632 | x.__next__() # output => 1 633 | x.__next__() # output => 2 634 | x.__next__() # output => 3 635 | x.__next__() # output => 5 636 | x.__next__() # output => 8 637 | x.__next__() # error 638 | 639 | ## iterating using loop 640 | for i in fib(10): 641 | print(i) # output => 0 1 1 2 3 5 8 642 | 643 | 644 | 645 | 646 | 62.What can you use Python generator functions for? 647 | Ans: One of the reasons to use generator is to make the solution clearer for some kind 648 | of solutions. 649 | The other is to treat results one at a time, avoiding building huge lists of results that you 650 | would process separated anyway. 651 | 652 | 63.When is not a good time to use python generators? 653 | Ans: Use list instead of generator when: 654 | 1 You need to access the data multiple times (i.e. cache the results instead of 655 | recomputing them) 656 | 2 You need random access (or any access other than forward sequential order): 657 | 3 You need to join strings (which requires two passes over the data) 658 | 4 You are using PyPy which sometimes can’t optimize generator code as much 659 | as it can with normal function calls and list manipulations. 660 | 661 | 64.What’s your preferred text editor? 662 | Ans: Emacs. Any alternate answer leads to instant disqualification of the applicant 663 | 664 | 65.When should you use generator expressions vs. list comprehensions in Python and vice-versa? 665 | Ans: Iterating over the generator expression or the list comprehension will do the same 666 | thing. However, the list comp will create the entire list in memory first while the 667 | generator expression will create the items on the fly, so you are able to use it for very 668 | large (and also infinite!) sequences. 669 | 670 | 66. What is a negative index in Python? 671 | Ans: Python arrays and list items can be accessed with positive or negative numbers. A 672 | negative Index accesses the elements from the end of the list counting backwards. 673 | Example: 674 | a=[123] 675 | printa[-3] 676 | printa[-2] 677 | Outputs: 678 | 1 679 | 2 680 | 681 | 67. What is the difference between range and xrange functions? 682 | Ans: Range returns a list while xrange returns an xrange object which take the 683 | same memory no matter of the range size. In the first case you have all items already 684 | generated (this can take a lot of time and memory). In Python 3 however, range is 685 | implemented with xrange and you have to explicitly call the list function if you want to 686 | convert it to a list. 687 | 688 | 689 | 690 | 68. How can I find methods or attributes of an object in Python? 691 | Ans: Builtin dir() function of Python ,on an instance shows the instance variables as 692 | well as the methods and class attributes defined by the instance’s class and all its base 693 | classes alphabetically. So by any object as argument to dir() we can find all the 694 | methods & attributes of the object’s class 695 | 696 | 69. What is the statement that can be used in Python if a statement is required syntactically but the program requires no action? 697 | Ans: 698 | pass 699 | 700 | 70. Do you know what is the difference between lists and tuples? Can you give me an example for their usage? 701 | Ans: 702 | First list are mutable while tuples are not, and second tuples can be hashed e.g. 703 | to be used as keys for dictionaries. As an example of their usage, tuples are used when 704 | the order of the elements in the sequence matters e.g. a geographic coordinates, “list” 705 | of points in a path or route, or set of actions that should be executed in specific order. 706 | Don’t forget that you can use them a dictionary keys. For everything else use lists 707 | 708 | 71. What is the function of “self”? 709 | Ans: 710 | “Self” is a variable that represents the instance of the object to itself. In most of 711 | the object oriented programming languages, this is passed to the methods as a hidden 712 | parameter that is defined by an object. But, in python it is passed explicitly. It refers to 713 | separate instance of the variable for individual objects. The variables are referred as 714 | “self.xxx”. 715 | 716 | 72. How is memory managed in Python? 717 | Ans: 718 | Memory management in Python involves a private heap containing all 719 | Python objects and data structures. Interpreter takes care of Python heap and 720 | the programmer has no access to it. The allocation of heap space for Python 721 | objects is done by Python memory manager. The core API of Python provides 722 | some tools for the programmer to code reliable and more robust program. Python 723 | also has a builtin garbage collector which recycles all the unused memory. 724 | The gc module defines functions to enable /disable garbage collector: 725 | gc.enable() Enables automatic garbage collection. 726 | gc.disable()-Disables automatic garbage collection 727 | 728 | 73. What is __init__.py? 729 | Ans: 730 | It is used to import a module in a directory, which is called package import. 731 | 732 | 74. Print contents of a file ensuring proper error handling? 733 | Ans: 734 | try: 735 | withopen(‘filename’,’r’)asf: 736 | printf.read() 737 | exceptIOError: 738 | print”Nosuchfileexists” 739 | 740 | 75 How do we share global variables across modules in Python? 741 | Ans: 742 | We can create a config file and store the entire global variable to be 743 | shared across modules in it. By simply importing config, the entire global variable 744 | defined will be available for use in other modules. 745 | For example I want a, b & c to share between modules. 746 | config.py : 747 | a=0 748 | b=0 749 | c=0 750 | module1.py: 751 | importconfig 752 | config.a=1 753 | config.b=2 754 | config.c=3 755 | print”a,b&resp.are:”,config.a,config.b,config.c 756 | 757 | output of module1.py will be 758 | 123 759 | 760 | 76. Does Python support Multithreading? 761 | Ans: Yes 762 | Medium 763 | 764 | 77. How do I get a list of all files (and directories) in a given directory in Python? 765 | Ans: Following is one possible solution there can be other similar ones: 766 | import os 767 | for dirname,dirnames,filenames in os.walk(‘.’): 768 | #printpathtoallsubdirectoriesfirst. 769 | forsubdirnameindirnames: 770 | printos.path.join(dirname,subdirname) 771 | #printpathtoallfilenames. 772 | forfilenameinfilenames: 773 | printos.path.join(dirname,filename) 774 | #Advancedusage: 775 | #editingthe’dirnames’listwillstopos.walk()fromrecursing 776 | intothere. 777 | if’.git’indirnames: 778 | #don’tgointoany.gitdirectories. 779 | dirnames.remove(‘.git’) 780 | 781 | 78. How to append to a string in Python? 782 | Ans: The easiest way is to use the += operator. If the string is a list of character, join() 783 | function can also be used. 784 | 785 | 79. How to convert a string to lowercase in Python? 786 | Ans: use lower() function. 787 | Example: 788 | s=’MYSTRING’ 789 | prints.lower() 790 | 791 | 80. How to convert a string to lowercase in Python? 792 | Ans: Similar to the above question. use upper() function instead. 793 | 794 | 81. How to check if string A is substring of string B? 795 | Ans: The easiest way is to use the in operator. 796 | >>> ‘abc’ in ‘abcdefg’ 797 | True 798 | 799 | 82. Find all occurrences of a substring in Python 800 | Ans: There is no simple builtin string function that does what you’re looking for, but 801 | you could use the more powerful regular expressions: 802 | >>>[m.start()forminre.finditer(‘test’,’testtesttesttest’)] 803 | [0,5,10,15]//thesearestartingindicesforthestring 804 | 805 | 83. What is GIL? What does it do?Talk to me about the GIL. How does it impact concurrency in Python? What kinds of applications does it impact more than others? 806 | Ans: Python’s GIL is intended to serialize access to interpreter internals from different 807 | threads. On multicore systems, it means that multiple threads can’t effectively make 808 | use of multiple cores. (If the GIL didn’t lead to this problem, most people wouldn’t care 809 | about the GIL it’s only being raised as an issue because of the increasing prevalence 810 | of multicore systems.) 811 | Note that Python’s GIL is only really an issue for CPython, the reference 812 | implementation. Jython and IronPython don’t have a GIL. As a Python developer, you 813 | don’t generally come across the GIL unless you’re writing a C extension. C extension 814 | writers need to release the GIL when their extensions do blocking I/O, so that other 815 | threads in the Python process get a chance to run. 816 | 817 | 84. Print the index of a specific item in a list? 818 | Ans: use the index() function 819 | >>>[“foo”,”bar”,”baz”].index(‘bar’) 820 | 1 821 | . 822 | 823 | 85.How do you iterate over a list and pull element indices at the same time? 824 | Ans: You are looking for the enumerate function. It takes each element in a sequence 825 | (like a list) and sticks it’s location right before it. For example: 826 | 827 | >>>my_list=[‘a’,’b’,’c’] 828 | >>>list(enumerate(my_list)) 829 | [(0,’a’),(1,’b’),(2,’c’)] 830 | Note that enumerate() returns an object to be iterated over, so wrapping it in list() just 831 | helps us see what enumerate() produces. 832 | An example that directly answers the question is given below 833 | my_list=[‘a’,’b’,’c’] 834 | fori,charinenumerate(my_list): 835 | printi,char 836 | The output is: 837 | 0a 838 | 1b 839 | 2c 840 | 841 | 86. How does Python’s list.sort work at a high level? Is it stable? What’s the runtime? 842 | Ans: In early pythonversions, the sort function implemented a modified version of 843 | quicksort. However, it was deemed unstable and as of 2.3 they switched to using an 844 | adaptive mergesort algorithm. 845 | 846 | 87. What does the list comprehension do: 847 | Ans: 848 | my_list=[(x,y,z)forxinrange(1,30)foryinrange(x,30)forzin 849 | range(y,30)ifx**2+y**2==z**2] 850 | It creates a list of tuples called my_list, where the first 2 elements are the 851 | perpendicular sides of right angle triangle and the third value ‘z’ is the hypotenuse. 852 | [(3,4,5),(5,12,13),(6,8,10),(7,24,25),(8,15,17),(9,12,15), 853 | (10,24,26),(12,16,20),(15,20,25),(20,21,29)] 854 | 855 | 88. How can we pass optional or keyword parameters from one function to another in Python? 856 | Ans: 857 | Gather the arguments using the * and ** specifiers in the function’s parameter list. This 858 | gives us positional arguments as a tuple and the keyword arguments as a dictionary. 859 | Then we can pass these arguments while calling another function by using * and **: 860 | deffun1(a,*tup,**keywordArg): 861 | … 862 | keywordArg[‘width’]=’23.3c’ 863 | … 864 | Fun2(a,*tup,**keywordArg) 865 | 866 | 867 | 868 | 89. Python How do you make a higher order function in Python? 869 | Ans: 870 | A higherorder function accepts one or more functions as input and returns a new 871 | function. Sometimes it is required to use function as data To make high order function , 872 | we need to import functools module The functools.partial() function is used often for 873 | high order function. 874 | 875 | 90. What is map? 876 | Ans: 877 | The syntax of map is: 878 | map(aFunction,aSequence) 879 | The first argument is a function to be executed for all the elements of the iterable given 880 | as the second argument. If the function given takes in more than 1 arguments, then 881 | many iterables are given. 882 | 883 | 91. Tell me a very simple solution to print every other element of this list? 884 | Ans: 885 | 886 | L=[0,10,20,30,40,50,60,70,80,90] 887 | L[::2] 888 | 889 | 92. Are Tuples immutable? 890 | Ans: Yes. 891 | 892 | 93. Why is not all memory freed when python exits? 893 | Ans: Objects referenced from the global namespaces of Python modules are not 894 | always deallocated when Python exits. This may happen if there are circular 895 | references. There are also certain bits of memory that are allocated by the C library that 896 | are impossible to free (e.g. a tool like the one Purify will complain about these). Python 897 | is, however, aggressive about cleaning up memory on exit and does try to destroy every 898 | single object. If you want to force Python to delete certain things on deallocation, you 899 | can use the at exit module to register one or more exit functions to handle those 900 | deletions. 901 | 902 | 94. What is Java implementation of Python popularly know? 903 | Ans: Jython. 904 | 905 | 95. What is used to create unicode strings in Python? 906 | Ans: 907 | Add u before the string. 908 | u ‘mystring’ 909 | 910 | 96. What is a docstring? 911 | Ans: 912 | docstring is the documentation string for a function. It can be accessed by 913 | function_name.__doc__ 914 | 915 | 97. Given the list below remove the repetition of an element. 916 | Ans: 917 | words=[‘one’,’one’,’two’,’three’,’three’,’two’] 918 | A bad solution would be to iterate over the list and checking for copies somehow and 919 | then remove them! 920 | 921 | A very good solution would be to use the set type. In a Python set, duplicates are not 922 | allowed. 923 | So, list(set(words)) would remove the duplicates. 924 | 925 | 98. Print the length of each line in the file ‘file.txt’ not including any 926 | whitespaces at the end of the lines? 927 | Ans: 928 | withopen(“filename.txt”,”r”)asf1: 929 | printlen(f1.readline().rstrip()) 930 | rstrip() is an inbuilt function which strips the string from the right end of spaces or tabs 931 | (whitespace characters). 932 | 933 | 99. What is wrong with the code? 934 | Ans: 935 | 936 | func([1,2,3])#explicitlypassinginalist 937 | func() #usingadefaultemptylist 938 | deffunc(n=[]): 939 | #dosomethingwithn 940 | printn 941 | 942 | This would result in a NameError. The variable n is local to function func and 943 | can’t be accessesd outside. So, printing it won’t be possible. 944 | 945 | 100. What does the below mean? 946 | Ans: 947 | 948 | s = a + ‘[‘ + b + ‘:’ + c + ‘]’ 949 | 950 | seems like a string is being concatenated. Nothing much can be said without 951 | knowing types of variables a, b, c. Also, if all of the a, b, c are not of type string, 952 | TypeError would be raised. This is because of the string constants (‘[‘ , ‘]’) used in the 953 | statement. 954 | 101. What are Python decorators? 955 | Ans: 956 | A Python decorator is a specific change that we make in Python syntax to alter 957 | functions easily. 958 | 959 | 102. What is namespace in Python? 960 | Ans: 961 | In Python, every name introduced has a place where it lives and can be hooked 962 | for. This is known as namespace. It is like a box where a variable name is mapped to 963 | the object placed. Whenever the variable is searched out, this box will be searched, to 964 | get corresponding object. 965 | 966 | 103. Explain the role of repr function. 967 | Ans: 968 | Python can convert any value to a string by making use of two functions repr() or 969 | str(). The str() function returns representations of values which are humanreadable, 970 | while repr() generates representations which can be read by the interpreter. repr() 971 | returns a machinereadable representation of values, suitable for an exec command. 972 | Following code sniipets shows working of repr() & str() : 973 | deffun(): 974 | y=2333.3 975 | x=str(y) 976 | z=repr(y) 977 | print”y:”,y 978 | print”str(y):”,x 979 | print”repr(y):”,z 980 | fun() 981 | ————- 982 | output 983 | y:2333.3 984 | str(y):2333.3 985 | repr(y):2333.3000000000002 986 | 987 | 104. What is LIST comprehensions features of Python used for? 988 | Ans: 989 | LIST comprehensions features were introduced in Python version 2.0, it creates 990 | a new list based on existing list. It maps a list into another list by applying a function to 991 | 992 | each of the elements of the existing list. List comprehensions creates lists without using 993 | map() , filter() or lambda form. 994 | 995 | 105. Explain how to copy an object in Python.? 996 | Ans: 997 | There are two ways in which objects can be copied in python. Shallow copy & 998 | Deep copy. Shallow copies duplicate as minute as possible whereas Deep copies 999 | duplicate everything. If a is object to be copied then … 1000 | copy.copy(a) returns a shallow copy of a. 1001 | copy.deepcopy(a) returns a deep copy of a. 1002 | 1003 | 106. Describe how to send mail from a Python script? 1004 | Ans: 1005 | The smtplib module defines an SMTP client session object that can be used to 1006 | send mail to any Internet machine. 1007 | A sample email is demonstrated below. 1008 | import smtplib 1009 | SERVER = smtplib.SMTP(‘smtp.server.domain’) 1010 | FROM = sender@mail.com 1011 | TO = [“user@mail.com”] # must be a list 1012 | SUBJECT = “Hello!” 1013 | TEXT = “This message was sent with Python’s smtplib.” 1014 | # Main message 1015 | message = “”” 1016 | From: Lincoln < sender@mail.com > 1017 | To: CarreerRide user@mail.com 1018 | Subject: SMTP email msg 1019 | This is a test email. Acknowledge the email by responding. 1020 | “”” % (FROM, “, “.join(TO), SUBJECT, TEXT) 1021 | server = smtplib.SMTP(SERVER) 1022 | server.sendmail(FROM, TO, message) 1023 | server.quit() 1024 | 1025 | 107. Which of the languages does Python resemble in its class syntax? 1026 | Ans: c++. 1027 | 1028 | 108. Python How to create a multidimensional list? 1029 | Ans: There are two ways in which Multidimensional list can be created: 1030 | By direct initializing the list as shown below to create myList below. 1031 | >>>myList=[[227,122,223],[222,321,192],[21,122,444]] 1032 | >>>printmyList[0] 1033 | >>>printmyList[1][2] 1034 | ____________________ 1035 | Output 1036 | [227, 122, 223] 1037 | 192 1038 | The second approach is to create a list of the desired length first and then fill in each 1039 | element with a newly created lists demonstrated below : 1040 | >>>list=[0]*3 1041 | >>>foriinrange(3): 1042 | >>>list[i]=[0]*2 1043 | >>>foriinrange(3): 1044 | >>>forjinrange(2): 1045 | >>>list[i][j]=i+j 1046 | >>>printlist 1047 | __________________________ 1048 | Output 1049 | [[0,1],[1,2],[2,3]] 1050 | 1051 | 109. Explain the disadvantages of python 1052 | Ans: Disadvantages of Python are: Python isn’t the best for memory intensive tasks. 1053 | Python is interpreted language & is slow compared to C/C++ or Java. 1054 | 1055 | 110. Explain how to make Forms in python. 1056 | Ans. As python is scripting language forms processing is done by Python. We need to 1057 | import cgi module to access form fields using FieldStorage class. 1058 | Every instance of class FieldStorage (for ‘form’) has the following attributes: 1059 | form.name: The name of the field, if specified. 1060 | 1061 | form.filename: If an FTP transaction, the clientside filename. 1062 | form.value: The value of the field as a string. 1063 | form.file: file object from which data can be read. 1064 | form.type: The content type, if applicable. 1065 | form.type_options: The options of the ‘contenttype’ line of the HTTP request, returned 1066 | as a dictionary. 1067 | form.disposition: The field ‘contentdisposition’; None if unspecified. 1068 | form.disposition_options: The options for ‘contentdisposition’. 1069 | form.headers: All of the HTTP headers returned as a dictionary. 1070 | A code snippet of form handling in python: 1071 | importcgi 1072 | form=cgi.FieldStorage() 1073 | ifnot(form.has_key(“name”)andform.has_key(“age”)): 1074 | print”
name:”,form[“name”].value 1078 | print”
Age:”,form[“age”].value
1079 |
1080 | 111. Explain how python is interpreted.
1081 | Ans: Python program runs directly from the source code. Each type Python programs
1082 | are executed code is required. Python converts source code written by the programmer
1083 | into intermediate language which is again translated it into the native language
1084 | machine language that is executed. So Python is an Interpreted language.
1085 |
1086 | 112. Explain how to overload constructors (or methods) in Python.?
1087 | Ans. _init__ () is a first
1088 |
1089 | 113.What is the difference between List & Tuple in Python.?
1090 | LIST vs TUPLES
1091 | LIST TUPLES
1092 | Lists are mutable i.e they can be edited. Tuples are immutable (tuples are lists which can’t be edited).
1093 | Lists are slower than tuples. Tuples are faster than list.
1094 | Syntax: list_1 = [10, ‘Chelsea’, 20] Syntax: tup_1 = (10, ‘Chelsea’ , 20)
1095 |
1096 |
1097 | 114.What are the key features of Python?
1098 | Ans:
1099 |
1100 | Python is an interpreted language. That means that, unlike languages like C and its variants, Python does not need to be compiled before it is run. Other interpreted languages include PHP and Ruby.
1101 | Python is dynamically typed, this means that you don’t need to state the types of variables when you declare them or anything like that. You can do things like x=111 and then x="I'm a string" without error
1102 | Python is well suited to object orientated programming in that it allows the definition of classes along with composition and inheritance. Python does not have access specifiers (like C++’s public, private).
1103 | In Python, functions are first-class objects. This means that they can be assigned to variables, returned from other functions and passed into functions. Classes are also first class objects
1104 | Writing Python code is quick but running it is often slower than compiled languages. Fortunately,Python allows the inclusion of C based extensions so bottlenecks can be optimized away and often are. The numpy package is a good example of this, it’s really quite quick because a lot of the number crunching it does isn’t actually done by Python
1105 | Python finds use in many spheres – web applications, automation, scientific modeling, big data applications and many more. It’s also often used as “glue” code to get other languages and components to play nice.
1106 |
1107 |
1108 | 115.How is Python an interpreted language?
1109 | Ans: An interpreted language is any programming language which is not in machine level code before runtime. Therefore, Python is an interpreted language.
1110 |
1111 | 116.How is memory managed in Python?
1112 | Ans:
1113 |
1114 | Memory management in python is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap. The python interpreter takes care of this instead.
1115 | The allocation of heap space for Python objects is done by Python’s memory manager. The core API gives access to some tools for the programmer to code.
1116 | Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it can be made available to the heap space.
1117 |
1118 |
1119 | 117.What is PYTHONPATH?
1120 | Ans:It is an environment variable which is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.
1121 |
1122 | 118. What are python modules? Name some commonly used built-in modules in Python?
1123 | Ans:Python modules are files containing Python code. This code can either be functions classes or variables. A Python module is a .py file containing executable code.
1124 |
1125 | Some of the commonly used built-in modules are:
1126 |
1127 | os
1128 | sys
1129 | math
1130 | random
1131 | data time
1132 | JSON
1133 | 119.What are local variables and global variables in Python?
1134 | Ans:
1135 |
1136 | Global Variables:
1137 |
1138 | Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program.
1139 |
1140 | Local Variables:
1141 |
1142 | Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.
1143 |
1144 | Example:
1145 |
1146 | 1
1147 | 2
1148 | 3
1149 | 4
1150 | 5
1151 | 6
1152 | a=2
1153 | def add():
1154 | b=3
1155 | c=a+b
1156 | print(c)
1157 | add()
1158 | Output: 5
1159 |
1160 | When you try to access the local variable outside the function add(), it will throw an error.
1161 |
1162 | 120. Is python case sensitive?
1163 | Ans:Yes. Python is a case sensitive language.
1164 |
1165 | 121.What is type conversion in Python?
1166 | Ans:Type conversion refers to the conversion of one data type iinto another.
1167 |
1168 | int() – converts any data type into integer type
1169 |
1170 | float() – converts any data type into float type
1171 |
1172 | ord() – converts characters into integer
1173 |
1174 | hex() – converts integers to hexadecimal
1175 |
1176 | oct() – converts integer to octal
1177 |
1178 | tuple() – This function is used to convert to a tuple.
1179 |
1180 | set() – This function returns the type after converting to set.
1181 |
1182 | list() – This function is used to convert any data type to a list type.
1183 |
1184 | dict() – This function is used to convert a tuple of order (key,value) into a dictionary.
1185 |
1186 | str() – Used to convert integer into a string.
1187 |
1188 | complex(real,imag) – This functionconverts real numbers to complex(real,imag) number.
1189 |
1190 |
1191 |
1192 | 122. How to install Python on Windows and set path variable?
1193 | Ans:To install Python on Windows, follow the below steps:
1194 |
1195 | Install python from this link: https://www.python.org/downloads/
1196 | After this, install it on your PC. Look for the location where PYTHON has been installed on your PC using the following command on your command prompt: cmd python.
1197 | Then go to advanced system settings and add a new variable and name it as PYTHON_NAME and paste the copied path.
1198 | Look for the path variable, select its value and select ‘edit’.
1199 | Add a semicolon towards the end of the value if it’s not present and then type %PYTHON_HOME%
1200 |
1201 |
1202 | 123. Is indentation required in python?
1203 | Ans:Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block. It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.
1204 |
1205 | 124. What is the difference between Python Arrays and lists?
1206 | Ans:Arrays and lists, in Python, have the same way of storing data. But, arrays can hold only a single data type elements whereas lists can hold any data type elements.
1207 |
1208 | Example:
1209 |
1210 | 1
1211 | 2
1212 | 3
1213 | 4
1214 | 5
1215 | import array as arr
1216 | My_Array=arr.array('i',[1,2,3,4])
1217 | My_list=[1,'abc',1.20]
1218 | print(My_Array)
1219 | print(My_list)
1220 | Output:
1221 |
1222 | array(‘i’, [1, 2, 3, 4]) [1, ‘abc’, 1.2]
1223 |
1224 | 125. What are functions in Python?
1225 | Ans:A function is a block of code which is executed only when it is called. To define a Python function, the def keyword is used.
1226 |
1227 | Example:
1228 |
1229 | 1
1230 | 2
1231 | 3
1232 | def Newfunc():
1233 | print("Hi, Welcome to Edureka")
1234 | Newfunc(); #calling the function
1235 | Output: Hi, Welcome to Edureka
1236 |
1237 | 126.What is __init__?
1238 | Ans:__init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method.
1239 |
1240 | Here is an example of how to use it.
1241 |
1242 | 1
1243 | 2
1244 | 3
1245 | 4
1246 | 5
1247 | 6
1248 | 7
1249 | 8
1250 | 9
1251 | 10
1252 | 11
1253 | class Employee:
1254 | def __init__(self, name, age,salary):
1255 | self.name = name
1256 | self.age = age
1257 | self.salary = 20000
1258 | E1 = Employee("XYZ", 23, 20000)
1259 | # E1 is the instance of class Employee.
1260 | #__init__ allocates memory for E1.
1261 | print(E1.name)
1262 | print(E1.age)
1263 | print(E1.salary)
1264 | Output:
1265 |
1266 |
1267 |
1268 | XYZ
1269 |
1270 | 23
1271 |
1272 | 20000
1273 |
1274 |
1275 |
1276 | 127.What is a lambda function?
1277 | Ans:An anonymous function is known as a lambda function. This function can have any number of parameters but, can have just one statement.
1278 |
1279 | Example:
1280 |
1281 | 1
1282 | 2
1283 | a = lambda x,y : x+y
1284 | print(a(5, 6))
1285 | Output: 11
1286 |
1287 | 128. What is self in Python?
1288 | Ans:Self is an instance or an object of a class. In Python, this is explicitly included as the first parameter. However, this is not the case in Java where it’s optional. It helps to differentiate between the methods and attributes of a class with local variables.
1289 |
1290 | The self variable in the init method refers to the newly created object while in other methods, it refers to the object whose method was called.
1291 |
1292 | 129. How does break, continue and pass work?
1293 | Break Allows loop termination when some condition is met and the control is transferred to the next statement.
1294 | Continue Allows skipping some part of a loop when some specific condition is met and the control is transferred to the beginning of the loop
1295 | Pass Used when you need some block of code syntactically, but you want to skip its execution. This is basically a null operation. Nothing happens when this is executed.
1296 | 130. What does [::-1} do?
1297 | Ans: [::-1] is used to reverse the order of an array or a sequence.
1298 | For example:
1299 | 1
1300 | 2
1301 | 3
1302 | import array as arr
1303 | My_Array=arr.array('i',[1,2,3,4,5])
1304 | My_Array[::-1]
1305 | Output: array(‘i’, [5, 4, 3, 2, 1])
1306 |
1307 | [::-1] reprints a reversed copy of ordered data structures such as an array or a list. the original array or list remains unchanged.
1308 |
1309 |
1310 | 131. How can you randomize the items of a list in place in Python?
1311 | Ans: Consider the example shown below:
1312 |
1313 | 1
1314 | 2
1315 | 3
1316 | 4
1317 | from random import shuffle
1318 | x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High']
1319 | shuffle(x)
1320 | print(x)
1321 | The output of the following code is as below.
1322 |
1323 | ['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag']
1324 | 132. What are python iterators?
1325 | Ans:Iterators are objects which can be traversed though or iterated upon.
1326 |
1327 | 133. How can you generate random numbers in Python?
1328 | Ans: Random module is the standard module that is used to generate a random number. The method is defined as:
1329 |
1330 | 1
1331 | 2
1332 | import random
1333 | random.random
1334 | The statement random.random() method return the floating point number that is in the range of [0, 1). The function generates random float numbers. The methods that are used with the random class are the bound methods of the hidden instances. The instances of the Random can be done to show the multi-threading programs that creates a different instance of individual threads. The other random generators that are used in this are:
1335 |
1336 | randrange(a, b): it chooses an integer and define the range in-between [a, b). It returns the elements by selecting it randomly from the range that is specified. It doesn’t build a range object.
1337 | uniform(a, b): it chooses a floating point number that is defined in the range of [a,b).Iyt returns the floating point number
1338 | normalvariate(mean, sdev): it is used for the normal distribution where the mu is a mean and the sdev is a sigma that is used for standard deviation.
1339 | The Random class that is used and instantiated creates an independent multiple random number generators.
1340 | 134. What is the difference between range & xrange?
1341 | Ans: 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. The only difference is that range returns a Python list object and x range returns an xrange object.
1342 |
1343 | 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.
1344 |
1345 | 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.
1346 |
1347 | 135. How do you write comments in python?
1348 | Ans:Comments in Python start with a # character. However, alternatively at times, commenting is done using docstrings(strings enclosed within triple quotes).
1349 |
1350 | Example:
1351 |
1352 | #Comments in Python start like this
1353 | print("Comments in Python start with a #")
1354 | Output: Comments in Python start with a #
1355 |
1356 | 136. What is pickling and unpickling?
1357 | Ans: 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.
1358 |
1359 | 137. What are the generators in python?
1360 | Ans: Functions that return an iterable set of items are called generators.
1361 |
1362 | 138. How will you capitalize the first letter of string?
1363 | Ans:In Python, the capitalize() method capitalizes the first letter of a string. If the string already consists of a capital letter at the beginning, then, it returns the original string.
1364 |
1365 | 139. How will you convert a string to all lowercase?
1366 | Ans:To convert a string to lowercase, lower() function can be used.
1367 |
1368 | Example:
1369 |
1370 | 1
1371 | 2
1372 | stg='ABCD'
1373 | print(stg.lower())
1374 | Output: abcd
1375 |
1376 | 140. How to comment multiple lines in python?
1377 | Ans: Multi-line comments appear in more than one line. All the lines to be commented are to be prefixed by a #. You can also a very good shortcut method to comment multiple lines. All you need to do is hold the ctrl key and left click in every place wherever you want to include a # character and type a # just once. This will comment all the lines where you introduced your cursor.
1378 |
1379 | 141.What are docstrings in Python?
1380 | Ans:Docstrings are not actually comments, but, they are documentation strings. These docstrings are within triple quotes. They are not assigned to any variable and therefore, at times, serve the purpose of comments as well.
1381 |
1382 | Example:
1383 |
1384 | 1
1385 | 2
1386 | 3
1387 | 4
1388 | 5
1389 | 6
1390 | 7
1391 | 8
1392 | """
1393 | Using docstring as a comment.
1394 | This code divides 2 numbers
1395 | """
1396 | x=8
1397 | y=4
1398 | z=x/y
1399 | print(z)
1400 | Output: 2.0
1401 |
1402 | 141. What is the purpose of is, not and in operators?
1403 | Ans:Operators are special functions. They take one or more values and produce a corresponding result.
1404 |
1405 | is: returns true when 2 operands are true (Example: “a” is ‘a’)
1406 |
1407 | not: returns the inverse of the boolean value
1408 |
1409 | in: checks if some element is present in some sequence
1410 |
1411 | 142. What is the usage of help() and dir() function in Python?
1412 | Ans: Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions.
1413 |
1414 | Help() function: The help() function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc.
1415 | Dir() function: The dir() function is used to display the defined symbols.
1416 | 143. Whenever Python exits, why isn’t all the memory de-allocated?
1417 | Ans:
1418 |
1419 | 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.
1420 | It is impossible to de-allocate those portions of memory that are reserved by the C library.
1421 | On exit, because of having its own efficient clean up mechanism, Python would try to de-allocate/destroy every other object.
1422 | 143. What is a dictionary in Python?
1423 | Ans: The built-in datatypes in Python is called dictionary. It defines one-to-one relationship between keys and values. Dictionaries contain pair of keys and their corresponding values. Dictionaries are indexed by keys.
1424 |
1425 | Let’s take an example:
1426 |
1427 | The following example contains some keys. Country, Capital & PM. Their corresponding values are India, Delhi and Modi respectively.
1428 |
1429 | 1
1430 | dict={'Country':'India','Capital':'Delhi','PM':'Modi'}
1431 | 1
1432 | print dict[Country]
1433 | India
1434 | 1
1435 | print dict[Capital]
1436 | Delhi
1437 | 1
1438 | print dict[PM]
1439 | Modi
1440 | 144. How can the ternary operators be used in python?
1441 | Ans: The Ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it.
1442 |
1443 | Syntax:
1444 |
1445 | The Ternary operator will be given as:
1446 | [on_true] if [expression] else [on_false]x, y = 25, 50big = x if x < y else y
1447 |
1448 | Example:
1449 |
1450 | The expression gets evaluated like if x
3815 | When webpack processes your application, it starts from a list of modules defined on the command line or in its config file. Starting from these entry points, webpack recursively builds a dependency graph that includes every module your application needs, then packages all of those modules into a small number of bundles – often, just one – to be loaded by the browser.
3816 |
3817 | The require('logo.png') source code never actually gets executed in the browser (nor in Node.js). Webpack builds a new Javascript file, replacing require() calls with valid Javascript code, such as URLs. The bundled file is what’s executed by Node or the browser.
3818 |
3819 |
3820 |
3821 |
3822 |
3823 | 325. What are metaclasses in Python?
3824 | Ans: A metaclass is the class of a class. A class defines how an instance of the class (i.e. an object) behaves while a metaclass defines how a class behaves. A class is an instance of a metaclass. You can call it a ‘class factory’.
3825 |
3826 |
3827 |
3828 |
3829 |
3830 |
3831 |
3832 | 326. How to make a chain of function decorators?
3833 | Ans: How can I make two decorators in Python that would do the following?
3834 |
3835 | @makebold
3836 | @makeitalic
3837 | def say():
3838 | return "Hello"
3839 | which should return:
3840 |
3841 | "Hello"
3842 | Answer:
3843 | Consider:
3844 |
3845 | from functools import wraps
3846 |
3847 | def makebold(fn):
3848 | @wraps(fn)
3849 | def wrapped(*args, **kwargs):
3850 | return "" + fn(*args, **kwargs) + ""
3851 | return wrapped
3852 |
3853 | def makeitalic(fn):
3854 | @wraps(fn)
3855 | def wrapped(*args, **kwargs):
3856 | return "" + fn(*args, **kwargs) + ""
3857 | return wrapped
3858 |
3859 | @makebold
3860 | @makeitalic
3861 | def hello():
3862 | return "hello world"
3863 |
3864 | @makebold
3865 | @makeitalic
3866 | def log(s):
3867 | return s
3868 |
3869 | print hello() # returns "hello world"
3870 | print hello.__name__ # with functools.wraps() this returns "hello"
3871 | print log('hello') # returns "hello"
3872 |
3873 |
3874 |
3875 |
3876 |
3877 |
3878 |
3879 | 327. What is the difference between @staticmethod and @classmethod?
3880 | Ans: A staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It’s definition is immutable via inheritance.
3881 |
3882 | class C:
3883 | @staticmethod
3884 | def f(arg1, arg2, ...): ...
3885 | A classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. Its definition follows Sub class, not Parent class, via inheritance.
3886 |
3887 | class C:
3888 | @classmethod
3889 | def f(cls, arg1, arg2, ...): ...
3890 | If your method accesses other variables/methods in your class then use @classmethod.
3891 |
3892 |
3893 |
3894 | 328. What’s the difference between a Python module and a Python package?
3895 | Ans: Any Python file is a module, its name being the file’s base name without the .py extension.
3896 |
3897 | import my_module
3898 | A package is a collection of Python modules: while a module is a single Python file, a package is a directory of Python modules containing an additional init.py file, to distinguish a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own init.py file.
3899 |
3900 | Packages are modules too. They are just packaged up differently; they are formed by the combination of a directory plus init.py file. They are modules that can contain other modules.
3901 |
3902 | from my_package.timing.danger.internets import function_of_love
3903 |
3904 |
3905 |
3906 |
3907 | 329. What is GIL?
3908 | Ans: Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your ‘threads’ can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread. This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core. All this GIL passing adds overhead to execution.
3909 |
3910 |
3911 |
3912 |
3913 |
3914 | 330. Is it a good idea to use multi-thread to speed your Python code?
3915 | Ans: Python doesn’t allow multi-threading in the truest sense of the word. It has a multi-threading package but if you want to multi-thread to speed your code up, then it’s usually not a good idea to use it.
3916 |
3917 | Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your ‘threads’ can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread. This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core. All this GIL passing adds overhead to execution.
3918 |
3919 |
3920 |
3921 |
3922 |
3923 | 331. How do I write a function with output parameters (call by reference)?
3924 | Ans: In Python arguments are passed by assignment. When you call a function with a parameter, a new reference is created that refers to the object passed in. This is separate from the reference that was used in the function call, so there’s no way to update that reference and make it refer to a new object.
3925 |
3926 | If you pass a mutable object into a method, the method gets a reference to that same object and you can mutate it to your heart’s delight, but if you rebind the reference in the method (like b = b + 1), the outer scope will know nothing about it, and after you’re done, the outer reference will still point at the original object.
3927 |
3928 | So to achieve the desired effect your best choice is to return a tuple containing the multiple results:
3929 |
3930 | def func2(a, b):
3931 | a = 'new-value' # a and b are local names
3932 | b = b + 1 # assigned to new objects
3933 | return a, b # return new values
3934 |
3935 | x, y = 'old-value', 99
3936 | x, y = func2(x, y)
3937 | print(x, y)
3938 |
3939 |
3940 |
3941 |
3942 |
3943 |
3944 | 332. Whenever you exit Python, is all memory de-allocated?
3945 | Ans: 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. Plus, it is impossible to de-allocate portions of memory reserved by the C library.
3946 |
3947 |
3948 |
3949 |
3950 |
3951 |
3952 |
3953 | 333. What is the purpose of the single underscore “_” variable in Python?
3954 | Ans: has 4 main conventional uses in Python:
3955 |
3956 | To hold the result of the last executed expression(/statement) in an interactive interpreter session. This precedent was set by the standard CPython interpreter, and other interpreters have followed suit
3957 | For translation lookup in i18n (see the gettext documentation for example), as in code like: raise forms.ValidationError(_("Please enter a correct username"))
3958 | As a general purpose “throwaway” variable name to indicate that part of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like: label, has_label, _ = text.partition(':').
3959 | As part of a function definition (using either def or lambda), where the signature is fixed (e.g. by a callback or parent class API), but this particular function implementation doesn’t need all of the parameters, as in code like: callback = lambda _: True
3960 |
3961 |
3962 |
3963 |
3964 |
3965 |
3966 | 334. How is set() implemented internally?
3967 | I’ve seen people say that set objects in python have O(1) membership-checking. How are they implemented internally to allow this? What sort of data structure does it use? What other implications does that implementation have?
3968 |
3969 | Ans:
3970 | Indeed, CPython’s sets are implemented as something like dictionaries with dummy values (the keys being the members of the set), with some optimization(s) that exploit this lack of values.
3971 |
3972 | So basically a set uses a hashtable as its underlying data structure. This explains the O(1) membership checking, since looking up an item in a hashtable is an O(1) operation, on average.
3973 |
3974 | Also, it worth to mention when people say sets have O(1) membership-checking, they are talking about the average case. In the worst case (when all hashed values collide) membership-checking is O(n).
3975 |
3976 |
3977 |
3978 |
3979 |
3980 |
3981 |
3982 |
3983 |
3984 | 335. What is MRO in Python? How does it work?
3985 | Ans: Method Resolution Order (MRO) it denotes the way a programming language resolves a method or attribute. Python supports classes inheriting from other classes. The class being inherited is called the Parent or Superclass, while the class that inherits is called the Child or Subclass.
3986 |
3987 | In Python,** method resolution order** defines the order in which the base classes are searched when executing a method. First, the method or attribute is searched within a class and then it follows the order we specified while inheriting. This order is also called Linearization of a class and set of rules are called MRO (Method Resolution Order). While inheriting from another class, the interpreter needs a way to resolve the methods that are being called via an instance. Thus we need the method resolution order.
3988 |
3989 | Python resolves method and attribute lookups using the C3 linearisation of the class and its parents. The C3 linearisation is neither depth-first nor breadth-first in complex multiple inheritance hierarchies.
3990 |
3991 |
3992 |
3993 |
3994 |
3995 |
3996 |
3997 | 336. What is the difference between old style and new style classes in Python?
3998 | Ans: Declaration-wise:
3999 |
4000 | New-style classes inherit from object, or from another new-style class.
4001 |
4002 | class NewStyleClass(object):
4003 | pass
4004 |
4005 | class AnotherNewStyleClass(NewStyleClass):
4006 | pass
4007 | Old-style classes don’t.
4008 |
4009 | class OldStyleClass():
4010 | pass
4011 | Python 3 Note:
4012 |
4013 | Python 3 doesn’t support old style classes, so either form noted above results in a new-style class.
4014 |
4015 | Also, MRO (Method Resolution Order) changed:
4016 |
4017 | Classic classes do a depth first search from left to right. Stop on first match. They do not have the mro attribute.
4018 | New-style classes MRO is more complicated to synthesize in a single English sentence. One of its properties is that a Base class is only searched for once all its Derived classes have been. They have the mro attribute which shows the search order.
4019 | Some other notes:
4020 |
4021 | New style class objects cannot be raised unless derived from Exception.
4022 | Old style classes are still marginally faster for attribute lookup.
4023 |
4024 |
4025 |
4026 |
4027 |
4028 |
4029 |
4030 |
4031 | 337. Why Python (CPython and others) uses the GIL?
4032 | Ans: In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple native threads from executing Python bytecodes at once. This lock is necessary mainly because CPython’s memory management is not thread-safe.
4033 |
4034 | Python has a GIL as opposed to fine-grained locking for several reasons:
4035 |
4036 | It is faster in the single-threaded case.
4037 | It is faster in the multi-threaded case for i/o bound programs.
4038 | It is faster in the multi-threaded case for cpu-bound programs that do their compute-intensive work in C libraries.
4039 | It makes C extensions easier to write: there will be no switch of Python threads except where you allow it to happen (i.e. between the Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros).
4040 | It makes wrapping C libraries easier. You don’t have to worry about thread-safety. If the library is not thread-safe, you simply keep the GIL locked while you call it
4041 |
4042 |
4043 |
4044 |
4045 |
4046 |
4047 | 338. How are arguments passed by value or by reference in python?
4048 | Ans:
4049 |
4050 | Pass by value: Copy of the actual object is passed. Changing the value of the copy of the object will not change the value of the original object.
4051 | Pass by reference: Reference to the actual object is passed. Changing the value of the new object will change the value of the original object.
4052 | In Python, arguments are passed by reference, i.e., reference to the actual object is passed.
4053 |
4054 | def appendNumber(arr):
4055 | arr.append(4)
4056 |
4057 | arr = [1, 2, 3]
4058 |
4059 | print(arr) #Output: => [1, 2, 3]
4060 | appendNumber(arr)
4061 | print(arr) #Output: => [1, 2, 3, 4]
4062 |
4063 |
4064 |
4065 |
4066 |
4067 |
4068 | 339. What is a boolean in Python?
4069 | Ans: Boolean is one of the built-in data types in Python, it mainly contains two values, and they are true and false.
4070 |
4071 | Python bool() is the method used to convert a value to a boolean value.
4072 |
4073 | 1
4074 | Syntax for bool() method: bool([a])
4075 |
4076 |
4077 |
4078 |
4079 |
4080 |
4081 | 340. What is Python String format and Python String replace?
4082 | Ans: Python String Format: The String format() method in Python is mainly used to format the given string into an accurate output or result.
4083 |
4084 | Syntax for String format() method:
4085 |
4086 | 1
4087 | template.format(p0, p1, ..., k0=v0, k1=v1, ...)
4088 | Python String Replace: This method is mainly used to return a copy of the string in which all the occurrence of the substring is replaced by another substring.
4089 |
4090 | Syntax for String replace() method:
4091 |
4092 | 1
4093 | str.replace(old, new [, count])
4094 |
4095 |
4096 |
4097 |
4098 |
4099 |
4100 |
4101 |
4102 |
4103 |
4104 | 341. Name some of the built-in modules in Python?
4105 | Ans: The built-in modules in Python are:
4106 |
4107 | sys module
4108 | OS module
4109 | random module
4110 | collection module
4111 | JSON
4112 | Math module
4113 |
4114 |
4115 |
4116 |
4117 |
4118 |
4119 |
4120 |
4121 | 342. How do we convert the string to lowercase?
4122 | Ans: lower() function is used to convert string to lowercase.
4123 |
4124 | Example:
4125 |
4126 | 1
4127 | 2
4128 | str = 'XYZ'
4129 | print(str.lower())
4130 | Output:
4131 | 1
4132 | xyz
4133 |
4134 |
4135 |
4136 |
4137 |
4138 |
4139 |
4140 |
4141 | 343. How to remove values from a Python array?
4142 | Ans: The elements can be removed from a Python array using remove() or pop() function. The difference between pop() and remove() will be explained in the below example.
4143 |
4144 | Example:
4145 |
4146 | 1
4147 | 2
4148 | 3
4149 | 4
4150 | 5
4151 | x = arr.array('d', [ 1.0, 2.2, 3.4, 4.8, 5.2, 6.6, 7.3])
4152 | print(x.pop())
4153 | print(x.pop(3))
4154 | x.remove(1.0)
4155 | print(a)
4156 | Output:
4157 |
4158 | 1
4159 | 2
4160 | 3
4161 | 7.3
4162 | 4.8
4163 | array(‘d’, [2.2, 3.4, 5.2, 6.6])
4164 |
4165 |
4166 |
4167 |
4168 |
4169 |
4170 | 344. What is Try Block?
4171 | A block which is preceded by the try keyword is known as a try block
4172 |
4173 | Syntax:
4174 |
4175 | 1
4176 | 2
4177 | 3
4178 | try{
4179 | //statements that may cause an exception
4180 | }
4181 |
4182 |
4183 |
4184 |
4185 |
4186 |
4187 |
4188 |
4189 | 345. How can we access a module written in Python from C?
4190 | Ans: We can access the module written in Python from C by using the following method.
4191 |
4192 | 1
4193 | Module == PyImport_ImportModule("