├── 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, object­oriented 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 language​is a programming language​for which most of its 367 | implementations execute instructions directly, without previously compiling a program 368 | into machine­language​instructions. 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 switch­case statements. You can use if­else 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/python​on 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 data­types/data­structures 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: Built­in 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 built­in 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 built­in 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 multi­core 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 multi­core 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 python­versions, 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 higher­order 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 de­allocated 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 de­allocation, 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 human­readable, 970 | while repr() generates representations which can be read by the interpreter. repr() 971 | returns a machine­readable 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 client­side 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 ‘content­type’ line of the HTTP request, returned 1066 | as a dictionary. 1067 | form.disposition: The field ‘content­disposition’; None if unspecified. 1068 | form.disposition_options: The options for ‘content­disposition’. 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&AgenotEntered

” 1075 | print”FilltheName&Ageaccurately.” 1076 | return 1077 | 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>> some_string = 'techbeamers' 1989 | >>> len(some_string) 1990 | 11 1991 | 211. What Does The Chr() Function Do In Python? 1992 | Ans: The chr() function got re-added in Python 3.2. In version 3.0, it got removed. 1993 | 1994 | It returns the string denoting a character whose Unicode code point is an integer. 1995 | 1996 | For example, the chr(122) returns the string ‘z’ whereas the chr(1212) returns the string ‘Ҽ’. 1997 | 1998 | 212. What Does The Ord() Function Do In Python? 1999 | Ans: The ord(char) in Python takes a string of size one and returns an integer denoting the Unicode code format of the character in case of a Unicode type object, or the value of the byte if the argument is of 8-bit string type. 2000 | 2001 | >>> ord("z") 2002 | 122 2003 | 213. What Is Rstrip() In Python? 2004 | Ans: Python provides the rstrip() method which duplicates the string but leaves out the whitespace characters from the end. 2005 | 2006 | The rstrip() escapes the characters from the right end based on the argument value, i.e., a string mentioning the group of characters to get excluded. 2007 | 2008 | The signature of the rstrip() is: 2009 | 2010 | str.rstrip([char sequence/pre> 2011 | #Example 2012 | test_str = 'Programming ' 2013 | # The trailing whitespaces are excluded 2014 | print(test_str.rstrip()) 2015 | 2016 | 2017 | 214.What Is Whitespace In Python? 2018 | Ans: Whitespace represents the characters that we use for spacing and separation. 2019 | 2020 | They possess an “empty” representation. In Python, it could be a tab or space. 2021 | 2022 | 215. What Is Isalpha() In Python? 2023 | Ans: Python provides this built-in isalpha() function for the string handling purpose. 2024 | 2025 | It returns True if all characters in the string are of alphabet type, else it returns False. 2026 | 2027 | 216. How Do You Use The Split() Function In Python? 2028 | Python’s split() function works on strings to cut a large piece into smaller chunks, or sub-strings. We can specify a separator to start splitting, or it uses the space as one by default. 2029 | 2030 | #Example 2031 | str = 'pdf csv json' 2032 | print(str.split(" ")) 2033 | print(str.split()) 2034 | The output: 2035 | 2036 | ['pdf', 'csv', 'json'] 2037 | ['pdf', 'csv', 'json'] 2038 | 217. What Does The Join Method Do In Python? 2039 | Ans: Python provides the join() method which works on strings, lists, and tuples. It combines them and returns a united value. 2040 | 2041 | 218. What Does The Title() Method Do In Python? 2042 | Ans: Python provides the title() method to convert the first letter in each word to capital format while the rest turns to Lowercase. 2043 | 2044 | #Example 2045 | str = 'lEaRn pYtHoN' 2046 | print(str.title()) 2047 | The output: 2048 | 2049 | Learn Python 2050 | Now, check out some general purpose Python interview questions. 2051 | 2052 | 219. What Makes The CPython Different From Python? 2053 | Ans: CPython has its core developed in C. The prefix ‘C’ represents this fact. It runs an interpreter loop used for translating the Python-ish code to C language. 2054 | 2055 | 220. Which Package Is The Fastest Form Of Python? 2056 | Ans: PyPy provides maximum compatibility while utilizing CPython implementation for improving its performance. 2057 | 2058 | The tests confirmed that PyPy is nearly five times faster than the CPython. It currently supports Python 2.7. 2059 | 2060 | 221. What Is GIL In Python Language? 2061 | Ans: Python supports GIL (the global interpreter lock) which is a mutex used to secure access to Python objects, synchronizing multiple threads from running the Python bytecodes at the same time. 2062 | 2063 | 222. How Is Python Thread Safe? 2064 | Ans: Python ensures safe access to threads. It uses the GIL mutex to set synchronization. If a thread loses the GIL lock at any time, then you have to make the code thread-safe. 2065 | 2066 | For example, many of the Python operations execute as atomic such as calling the sort() method on a list. 2067 | 2068 | 223. How Does Python Manage The Memory? 2069 | Ans: Python implements a heap manager internally which holds all of its objects and data structures. 2070 | 2071 | This heap manager does the allocation/de-allocation of heap space for objects. 2072 | 2073 | 2074 | 2075 | 224.What Is The Set Object In Python? 2076 | Ans: Sets are unordered collection objects in Python. They store unique and immutable objects. Python has its implementation derived from mathematics. 2077 | 2078 | 225. What Is The Use Of The Dictionary In Python? 2079 | Ans: A dictionary has a group of objects (the keys) map to another group of objects (the values). A Python dictionary represents a mapping of unique Keys to Values. 2080 | 2081 | They are mutable and hence will not change. The values associated with the keys can be of any Python types. 2082 | 2083 | 226. Is Python List A Linked List? 2084 | Ans: A Python list is a variable-length array which is different from C-style linked lists. 2085 | 2086 | Internally, it has a contiguous array for referencing to other objects and stores a pointer to the array variable and its length in the list head structure. 2087 | 2088 | Here are some Python interview questions on classes and objects 2089 | 2090 | 2091 | 2092 | 227.What Is Class In Python? 2093 | Ans: Python supports object-oriented programming and provides almost all OOP features to use in programs. 2094 | 2095 | A Python class is a blueprint for creating the objects. It defines member variables and gets their behavior associated with them. 2096 | 2097 | We can make it by using the keyword “class.” An object gets created from the constructor. This object represents the instance of the class. 2098 | 2099 | In Python, we generate classes and instances in the following way. 2100 | 2101 | >>>class Human: # Create the class 2102 | ... pass 2103 | >>>man = Human() # Create the instance 2104 | >>>print(man) 2105 | <__main__.Human object at 0x0000000003559E10> 2106 | 228. What Are Attributes And Methods In A Python Class? 2107 | Ans: A class is useless if it has not defined any functionality. We can do so by adding attributes. They work as containers for data and functions. We can add an attribute directly specifying inside the class body. 2108 | 2109 | >>> class Human: 2110 | ... profession = "programmer" # specify the attribute 'profession' of the class 2111 | >>> man = Human() 2112 | >>> print(man.profession) 2113 | programmer 2114 | After we added the attributes, we can go on to define the functions. Generally, we call them methods. In the method signature, we always have to provide the first argument with a self-keyword. 2115 | 2116 | >>> class Human: 2117 | profession = "programmer" 2118 | def set_profession(self, new_profession): 2119 | self.profession = new_profession 2120 | >>> man = Human() 2121 | >>> man.set_profession("Manager") 2122 | >>> print(man.profession) 2123 | Manager 2124 | 229. How To Assign Values For The Class Attributes At Runtime? 2125 | Ans: We can specify the values for the attributes at runtime. We need to add an init method and pass input to object constructor. See the following example demonstrating this. 2126 | 2127 | >>> class Human: 2128 | def __init__(self, profession): 2129 | self.profession = profession 2130 | def set_profession(self, new_profession): 2131 | self.profession = new_profession 2132 | 2133 | >>> man = Human("Manager") 2134 | >>> print(man.profession) 2135 | Manager 2136 | 230.What Is Inheritance In Python Programming? 2137 | Ans: Inheritance is an OOP mechanism which allows an object to access its parent class features. It carries forward the base class functionality to the child. 2138 | 2139 | Python Interview Questions - Inheritance 2140 | 2141 | We do it intentionally to abstract away the similar code in different classes. 2142 | 2143 | The common code rests with the base class, and the child class objects can access it via inheritance. Check out the below example. 2144 | 2145 | class PC: # Base class 2146 | processor = "Xeon" # Common attribute 2147 | def set_processor(self, new_processor): 2148 | processor = new_processor 2149 | 2150 | class Desktop(PC): # Derived class 2151 | os = "Mac OS High Sierra" # Personalized attribute 2152 | ram = "32 GB" 2153 | 2154 | class Laptop(PC): # Derived class 2155 | os = "Windows 10 Pro 64" # Personalized attribute 2156 | ram = "16 GB" 2157 | 2158 | desk = Desktop() 2159 | print(desk.processor, desk.os, desk.ram) 2160 | 2161 | lap = Laptop() 2162 | print(lap.processor, lap.os, lap.ram) 2163 | The output: 2164 | 2165 | Xeon Mac OS High Sierra 32 GB 2166 | Xeon Windows 10 Pro 64 16 GB 2167 | 2168 | 2169 | 231.What Is Composition In Python? 2170 | Ans: The composition is also a type of inheritance in Python. It intends to inherit from the base class but a little differently, i.e., by using an instance variable of the base class acting as a member of the derived class. 2171 | 2172 | See the below diagram. 2173 | 2174 | Python Interview Questions - Composition 2175 | 2176 | To demonstrate composition, we need to instantiate other objects in the class and then make use of those instances. 2177 | 2178 | class PC: # Base class 2179 | processor = "Xeon" # Common attribute 2180 | def __init__(self, processor, ram): 2181 | self.processor = processor 2182 | self.ram = ram 2183 | 2184 | def set_processor(self, new_processor): 2185 | processor = new_processor 2186 | 2187 | def get_PC(self): 2188 | return "%s cpu & %s ram" % (self.processor, self.ram) 2189 | 2190 | class Tablet(): 2191 | make = "Intel" 2192 | def __init__(self, processor, ram, make): 2193 | self.PC = PC(processor, ram) # Composition 2194 | self.make = make 2195 | 2196 | def get_Tablet(self): 2197 | return "Tablet with %s CPU & %s ram by %s" % (self.PC.processor, self.PC.ram, self.make) 2198 | 2199 | if __name__ == "__main__": 2200 | tab = Tablet("i7", "16 GB", "Intel") 2201 | print(tab.get_Tablet()) 2202 | The output is: 2203 | 2204 | Tablet with i7 CPU & 16 GB ram by Intel 2205 | 2206 | 2207 | 2208 | 232.What Are Errors And Exceptions In Python Programs? 2209 | Ans: Errors are coding issues in a program which may cause it to exit abnormally. 2210 | 2211 | On the contrary, exceptions happen due to the occurrence of an external event which interrupts the normal flow of the program. 2212 | 2213 | 233. How Do You Handle Exceptions With Try/Except/Finally In Python? 2214 | Ans: Python lay down Try, Except, Finally constructs to handle errors as well as Exceptions. We enclose the unsafe code indented under the try block. And we can keep our fall-back code inside the except block. Any instructions intended for execution last should come under the finally block. 2215 | 2216 | try: 2217 | print("Executing code in the try block") 2218 | print(exception) 2219 | except: 2220 | print("Entering in the except block") 2221 | finally: 2222 | print("Reached to the final block") 2223 | The output is: 2224 | 2225 | Executing code in the try block 2226 | Entering in the except block 2227 | Reached to the final block 2228 | 234. How Do You Raise Exceptions For A Predefined Condition In Python? 2229 | Ans: We can raise an exception based on some condition. 2230 | 2231 | For example, if we want the user to enter only odd numbers, else will raise an exception. 2232 | 2233 | # Example - Raise an exception 2234 | while True: 2235 | try: 2236 | value = int(input("Enter an odd number- ")) 2237 | if value%2 == 0: 2238 | raise ValueError("Exited due to invalid input!!!") 2239 | else: 2240 | print("Value entered is : %s" % value) 2241 | except ValueError as ex: 2242 | print(ex) 2243 | break 2244 | The output is: 2245 | 2246 | Enter an odd number- 2 2247 | Exited due to invalid input!!! 2248 | Enter an odd number- 1 2249 | Value entered is : 1 2250 | Enter an odd number- 2251 | 235. What Are Python Iterators? 2252 | Ans: Iterators in Python are array-like objects which allow moving on the next element. We use them in traversing a loop, for example, in a “for” loop. 2253 | 2254 | Python library has a no. of iterators. For example, a list is also an iterator and we can start a for loop over it. 2255 | 2256 | 236. What Is The Difference Between An Iterator And Iterable? 2257 | Ans: The collection type like a list, tuple, dictionary, and set are all iterable objects whereas they are also iterable containers which return an iterator while traversing. 2258 | 2259 | Here are some advanced-level Python interview questions. 2260 | 2261 | 237. What Are Python Generators? 2262 | Ans: A Generator is a kind of function which lets us specify a function that acts like an iterator and hence can get used in a “for” loop. 2263 | 2264 | In a generator function, the yield keyword substitutes the return statement. 2265 | 2266 | # Simple Python function 2267 | def fn(): 2268 | return "Simple Python function." 2269 | 2270 | # Python Generator function 2271 | def generate(): 2272 | yield "Python Generator function." 2273 | 2274 | print(next(generate())) 2275 | The output is: 2276 | 2277 | Python Generator function. 2278 | 2279 | 2280 | 238.What Are Closures In Python? 2281 | Ans: Python closures are function objects returned by another function. We use them to eliminate code redundancy. 2282 | 2283 | In the example below, we’ve written a simple closure for multiplying numbers. 2284 | 2285 | def multiply_number(num): 2286 | def product(number): 2287 | 'product() here is a closure' 2288 | return num * number 2289 | return product 2290 | 2291 | num_2 = multiply_number(2) 2292 | print(num_2(11)) 2293 | print(num_2(24)) 2294 | 2295 | num_6 = multiply_number(6) 2296 | print(num_6(1)) 2297 | The output is: 2298 | 2299 | 22 2300 | 48 2301 | 6 2302 | 239. What Are Decorators In Python? 2303 | Ans: Python decorator gives us the ability to add new behavior to the given objects dynamically. In the example below, we’ve written a simple example to display a message pre and post the execution of a function. 2304 | 2305 | def decorator_sample(func): 2306 | def decorator_hook(*args, **kwargs): 2307 | print("Before the function call") 2308 | result = func(*args, **kwargs) 2309 | print("After the function call") 2310 | return result 2311 | return decorator_hook 2312 | 2313 | @decorator_sample 2314 | def product(x, y): 2315 | "Function to multiply two numbers." 2316 | return x * y 2317 | 2318 | print(product(3, 3)) 2319 | The output is: 2320 | 2321 | Before the function call 2322 | After the function call 2323 | 9 2324 | 240. How Do You Create A Dictionary In Python? 2325 | Ans: Let’s take the example of building site statistics. For this, we first need to break up the key-value pairs using a colon(“:”). The keys should be of an immutable type, i.e., so we’ll use the data-types which don’t allow changes at runtime. We’ll choose from an int, string, or tuple. 2326 | 2327 | However, we can take values of any kind. For distinguishing the data pairs, we can use a comma(“,”) and keep the whole stuff inside curly braces({…}). 2328 | 2329 | >>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"} 2330 | >>> type(site_stats) 2331 | 2332 | >>> print(site_stats) 2333 | {'type': 'organic', 'site': 'tecbeamers.com', 'traffic': 10000} 2334 | 241. How Do You Read From A Dictionary In Python? 2335 | Ans:To fetch data from a dictionary, we can directly access using the keys. We can enclose a “key” using brackets […] after mentioning the variable name corresponding to the dictionary. 2336 | 2337 | >>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"} 2338 | >>> print(site_stats["traffic"]) 2339 | We can even call the get method to fetch the values from a dict. It also let us set a default value. If the key is missing, then the KeyError would occur. 2340 | 2341 | >>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"} 2342 | >>> print(site_stats.get('site')) 2343 | tecbeamers.com 2344 | 242. How Do You Traverse Through A Dictionary Object In Python? 2345 | Ans: We can use the “for” and “in” loop for traversing the dictionary object. 2346 | 2347 | >>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"} 2348 | >>> for k, v in site_stats.items(): 2349 | print("The key is: %s" % k) 2350 | print("The value is: %s" % v) 2351 | print("++++++++++++++++++++++++") 2352 | The output is: 2353 | 2354 | The key is: type 2355 | The value is: organic 2356 | ++++++++++++++++++++++++ 2357 | The key is: site 2358 | The value is: tecbeamers.com 2359 | ++++++++++++++++++++++++ 2360 | The key is: traffic 2361 | The value is: 10000 2362 | ++++++++++++++++++++++++ 2363 | 243. How Do You Add Elements To A Dictionary In Python? 2364 | Ans: We can add elements by modifying the dictionary with a fresh key and then set the value to it. 2365 | 2366 | >>> # Setup a blank dictionary 2367 | >>> site_stats = {} 2368 | >>> site_stats['site'] = 'google.com' 2369 | >>> site_stats['traffic'] = 10000000000 2370 | >>> site_stats['type'] = 'Referral' 2371 | >>> print(site_stats) 2372 | {'type': 'Referral', 'site': 'google.com', 'traffic': 10000000000} 2373 | We can even join two dictionaries to get a bigger dictionary with the help of the update() method. 2374 | 2375 | >>> site_stats['site'] = 'google.co.in' 2376 | >>> print(site_stats) 2377 | {'site': 'google.co.in'} 2378 | >>> site_stats_new = {'traffic': 1000000, "type": "social media"} 2379 | >>> site_stats.update(site_stats_new) 2380 | >>> print(site_stats) 2381 | {'type': 'social media', 'site': 'google.co.in', 'traffic': 1000000} 2382 | 244. How Do You Delete Elements Of A Dictionary In Python? 2383 | Ans: We can delete a key in a dictionary by using the del() method. 2384 | 2385 | >>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"} 2386 | >>> del site_stats["type"] 2387 | >>> print(site_stats) 2388 | {'site': 'google.co.in', 'traffic': 1000000} 2389 | Another method, we can use is the pop() function. It accepts the key as the parameter. Also, a second parameter, we can pass a default value if the key doesn’t exist. 2390 | 2391 | >>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"} 2392 | >>> print(site_stats.pop("type", None)) 2393 | organic 2394 | >>> print(site_stats) 2395 | {'site': 'tecbeamers.com', 'traffic': 10000} 2396 | 245. How Do You Check The Presence Of A Key In A Dictionary? 2397 | Ans: We can use Python’s “in” operator to test the presence of a key inside a dict object. 2398 | 2399 | >>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"} 2400 | >>> 'site' in site_stats 2401 | True 2402 | >>> 'traffic' in site_stats 2403 | True 2404 | >>> "type" in site_stats 2405 | True 2406 | Earlier, Python also provided the has_key() method which got deprecated. 2407 | 2408 | 246. What Is The Syntax For List Comprehension In Python? 2409 | Ans: The signature for the list comprehension is as follows: 2410 | 2411 | [ expression(var) for var in iterable ] 2412 | For example, the below code will return all the numbers from 10 to 20 and store them in a list. 2413 | 2414 | >>> alist = [var for var in range(10, 20)] 2415 | >>> print(alist) 2416 | 247. What Is The Syntax For Dictionary Comprehension In Python? 2417 | A dictionary has the same syntax as was for the list comprehension but the difference is that it uses curly braces: 2418 | 2419 | { aKey, itsValue for aKey in iterable } 2420 | For example, the below code will return all the numbers 10 to 20 as the keys and will store the respective squares of those numbers as the values. 2421 | 2422 | >>> adict = {var:var**2 for var in range(10, 20)} 2423 | >>> print(adict) 2424 | 248. What Is The Syntax For Generator Expression In Python? 2425 | Ans: The syntax for generator expression matches with the list comprehension, but the difference is that it uses parenthesis: 2426 | 2427 | ( expression(var) for var in iterable ) 2428 | For example, the below code will create a generator object that generates the values from 10 to 20 upon using it. 2429 | 2430 | >>> (var for var in range(10, 20)) 2431 | at 0x0000000003668728> 2432 | >>> list((var for var in range(10, 20))) 2433 | Now, see more Python interview questions for practice. 2434 | 2435 | 249. How Do You Write A Conditional Expression In Python? 2436 | Ans: We can utilize the following single statement as a conditional expression. default_statment if Condition else another_statement 2437 | 2438 | >>> no_of_days = 366 2439 | >>> is_leap_year = "Yes" if no_of_days == 366 else "No" 2440 | >>> print(is_leap_year) 2441 | Yes 2442 | 250. What Do You Know About The Python Enumerate? 2443 | Ans: While using the iterators, sometimes we might have a use case to store the count of iterations. Python gets this task quite easy for us by giving a built-in method known as the enumerate(). 2444 | 2445 | The enumerate() function attaches a counter variable to an iterable and returns it as the “enumerated” object. 2446 | 2447 | We can use this object directly in the “for” loops or transform it into a list of tuples by calling the list() method. It has the following signature: 2448 | 2449 | enumerate(iterable, to_begin=0) 2450 | Arguments: 2451 | iterable: array type object which enables iteration 2452 | to_begin: the base index for the counter is to get started, its default value is 0 2453 | # Example - enumerate function 2454 | alist = ["apple","mango", "orange"] 2455 | astr = "banana" 2456 | 2457 | # Let's set the enumerate objects 2458 | list_obj = enumerate(alist) 2459 | str_obj = enumerate(astr) 2460 | 2461 | print("list_obj type:", type(list_obj)) 2462 | print("str_obj type:", type(str_obj)) 2463 | 2464 | print(list(enumerate(alist)) ) 2465 | # Move the starting index to two from zero 2466 | print(list(enumerate(astr, 2))) 2467 | The output is: 2468 | 2469 | list_obj type: 2470 | str_obj type: 2471 | [(0, 'apple'), (1, 'mango'), (2, 'orange')] 2472 | [(2, 'b'), (3, 'a'), (4, 'n'), (5, 'a'), (6, 'n'), (7, 'a')] 2473 | 251. What Is The Use Of Globals() Function In Python? 2474 | Ans: The globals() function in Python returns the current global symbol table as a dictionary object. 2475 | 2476 | Python maintains a symbol table to keep all necessary information about a program. This info includes the names of variables, methods, and classes used by the program. 2477 | 2478 | All the information in this table remains in the global scope of the program and Python allows us to retrieve it using the globals() method. 2479 | 2480 | Signature: globals() 2481 | 2482 | Arguments: None 2483 | # Example: globals() function 2484 | x = 9 2485 | def fn(): 2486 | y = 3 2487 | z = y + x 2488 | # Calling the globals() method 2489 | z = globals()['x'] = z 2490 | return z 2491 | 2492 | # Test Code 2493 | ret = fn() 2494 | print(ret) 2495 | The output is: 2496 | 2497 | 12 2498 | 252. Why Do You Use The Zip() Method In Python? 2499 | Ans: The zip method lets us map the corresponding index of multiple containers so that we can use them using as a single unit. 2500 | 2501 | Signature: 2502 | zip(*iterators) 2503 | Arguments: 2504 | Python iterables or collections (e.g., list, string, etc.) 2505 | Returns: 2506 | A single iterator object with combined mapped values 2507 | # Example: zip() function 2508 | 2509 | emp = [ "tom", "john", "jerry", "jake" ] 2510 | age = [ 32, 28, 33, 44 ] 2511 | dept = [ 'HR', 'Accounts', 'R&D', 'IT' ] 2512 | 2513 | # call zip() to map values 2514 | out = zip(emp, age, dept) 2515 | 2516 | # convert all values for printing them as set 2517 | out = set(out) 2518 | 2519 | # Displaying the final values 2520 | print ("The output of zip() is : ",end="") 2521 | print (out) 2522 | The output is: 2523 | 2524 | The output of zip() is : {('jerry', 33, 'R&D'), ('jake', 44, 'IT'), ('john', 28, 'Accounts'), ('tom', 32, 'HR')} 2525 | 253. What Are Class Or Static Variables In Python Programming? 2526 | Ans: In Python, all the objects share common class or static variables. 2527 | 2528 | But the instance or non-static variables are altogether different for different objects. 2529 | 2530 | The programming languages like C++ and Java need to use the static keyword to make a variable as the class variable. However, Python has a unique way to declare a static variable. 2531 | 2532 | All names initialized with a value in the class declaration becomes the class variables. And those which get assigned values in the class methods becomes the instance variables. 2533 | 2534 | # Example 2535 | class Test: 2536 | aclass = 'programming' # A class variable 2537 | def __init__(self, ainst): 2538 | self.ainst = ainst # An instance variable 2539 | 2540 | # Objects of CSStudent class 2541 | test1 = Test(1) 2542 | test2 = Test(2) 2543 | 2544 | print(test1.aclass) 2545 | print(test2.aclass) 2546 | print(test1.ainst) 2547 | print(test2.ainst) 2548 | 2549 | # A class variable is also accessible using the class name 2550 | print(Test.aclass) 2551 | The output is: 2552 | 2553 | programming 2554 | programming 2555 | 1 2556 | 2 2557 | programming 2558 | Let’s now answer some advanced-level Python interview questions. 2559 | 2560 | 254. How Does The Ternary Operator Work In Python? 2561 | Ans: The ternary operator is an alternative for the conditional statements. It combines true or false values with a statement that you need to test. 2562 | 2563 | The syntax would look like the one given below. 2564 | 2565 | [onTrue] if [Condition] else [onFalse] 2566 | 2567 | x, y = 35, 75 2568 | smaller = x if x < y else y 2569 | print(smaller) 2570 | 255. What Does The “Self” Keyword Do? 2571 | Ans: The self is a Python keyword which represents a variable that holds the instance of an object. 2572 | 2573 | In almost, all the object-oriented languages, it is passed to the methods as a hidden parameter. 2574 | 2575 | 256. What Are The Different Methods To Copy An Object In Python? 2576 | Ans: There are two ways to copy objects in Python. 2577 | 2578 | copy.copy() function 2579 | It makes a copy of the file from source to destination. 2580 | It’ll return a shallow copy of the parameter. 2581 | copy.deepcopy() function 2582 | It also produces the copy of an object from the source to destination. 2583 | It’ll return a deep copy of the parameter that you can pass to the function. 2584 | 257: What Is The Purpose Of Docstrings In Python? 2585 | Ans: In Python, the docstring is what we call as the docstrings. It sets a process of recording Python functions, modules, and classes. 2586 | 2587 | 258. Which Python Function Will You Use To Convert A Number To A String? 2588 | Ans: For converting a number into a string, you can use the built-in function str(). If you want an octal or hexadecimal representation, use the inbuilt function oct() or hex(). 2589 | 2590 | 2591 | 2592 | 259. How Do You Debug A Program In Python? Is It Possible To Step Through The Python Code? 2593 | Ans: Yes, we can use the Python debugger (pdb) to debug any Python program. And if we start a program using pdb, then it let us even step through the code. 2594 | 2595 | 260. List Down Some Of The PDB Commands For Debugging Python Programs? 2596 | Ans: Here are a few PDB commands to start debugging Python code. 2597 | 2598 | Add breakpoint (b) 2599 | Resume execution (c) 2600 | Step by step debugging (s) 2601 | Move to the next line (n) 2602 | List source code (l) 2603 | Print an expression (p) 2604 | 261. What Is The Command To Debug A Python Program? 2605 | Ans: The following command helps run a Python program in debug mode. 2606 | 2607 | $ python -m pdb python-script.py 2608 | 262. How Do You Monitor The Code Flow Of A Program In Python? 2609 | Ans: In Python, we can use the sys module’s settrace() method to setup trace hooks and monitor the functions inside a program. 2610 | 2611 | You need to define a trace callback method and pass it to the settrace() function. The callback should specify three arguments as shown below. 2612 | 2613 | import sys 2614 | 2615 | def trace_calls(frame, event, arg): 2616 | # The 'call' event occurs before a function gets executed. 2617 | if event != 'call': 2618 | return 2619 | # Next, inspect the frame data and print information. 2620 | print 'Function name=%s, line num=%s' % (frame.f_code.co_name, frame.f_lineno) 2621 | return 2622 | 2623 | def demo2(): 2624 | print 'in demo2()' 2625 | 2626 | def demo1(): 2627 | print 'in demo1()' 2628 | demo2() 2629 | 2630 | sys.settrace(trace_calls) 2631 | demo1() 2632 | 2633 | 2634 | 2635 | 2636 | 263. How long can an identifier be in Python? 2637 | Ans: According to the official Python documentation, an identifier can be of any length. However, PEP 8 suggests that you should limit all lines to a maximum of 79 characters. Also, PEP 20 says ‘readability counts’. So, a very long identifier will violate PEP-8 and PEP-20. 2638 | 2639 | Apart from that, there are certain rules we must follow to name one: 2640 | 2641 | According to the official Python documentation, an identifier can be of any length. However, PEP 8 suggests that you should limit all lines to a maximum of 79 characters. Also, PEP 20 says ‘readability counts’. So, a very long identifier will violate PEP-8 and PEP-20. 2642 | 2643 | Apart from that, there are certain rules we must follow to name one: 2644 | 2645 | It can only begin with an underscore or a character from A-Z or a-z. 2646 | The rest of it can contain anything from the following: A-Z/a-z/_/0-9. 2647 | Python is case-sensitive, as we discussed in the previous question. 2648 | Keywords cannot be used as identifiers. Python has the following keywords: 2649 | 2650 | 2651 | and def False import not True 2652 | as del finally in or try 2653 | assert elif for is pass while 2654 | break else from lambda print with 2655 | class except global None raise yield 2656 | continue exec if nonlocal return 2657 | 264. How would you convert a string into lowercase? 2658 | Ans: We use the lower() method for this. 2659 | 2660 | >>> ‘AyuShi’.lower() 2661 | ‘ayushi’ 2662 | 2663 | To convert it into uppercase, then, we use upper(). 2664 | 2665 | >>> ‘AyuShi’.upper() 2666 | ‘AYUSHI’ 2667 | 2668 | Also, to check if a string is in all uppercase or all lowercase, we use the methods isupper() and islower(). 2669 | 2670 | >>> ‘AyuShi’.isupper() 2671 | False 2672 | 2673 | >>> ‘AYUSHI’.isupper() 2674 | True 2675 | 2676 | >>> ‘ayushi’.islower() 2677 | True 2678 | 2679 | >>> ‘@yu$hi’.islower() 2680 | True 2681 | 2682 | >>> ‘@YU$HI’.isupper() 2683 | True 2684 | 2685 | So, characters like @ and $ will suffice for both cases 2686 | 2687 | Also, istitle() will tell us if a string is in title case. 2688 | 2689 | >>> ‘The Corpse Bride’.istitle() 2690 | True 2691 | 2692 | 2693 | 2694 | 265. What is the pass statement in Python? 2695 | 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. 2696 | 2697 | >>> def func(*args): 2698 | pass 2699 | >>> 2700 | Similarly, the break statement breaks out of a loop. 2701 | 2702 | >>> for i in range(7): 2703 | if i==3: break 2704 | print(i) 2705 | 1 2706 | 2707 | 2 2708 | 2709 | Finally, the continue statement skips to the next iteration. 2710 | 2711 | >>> for i in range(7): 2712 | if i==3: continue 2713 | print(i) 2714 | 1 2715 | 2716 | 2 2717 | 2718 | 4 2719 | 2720 | 5 2721 | 2722 | 6 2723 | 2724 | 2725 | 2726 | 266. Explain help() and dir() functions in Python? 2727 | Ans: 2728 | 2729 | The help() function displays the documentation string and help for its argument. 2730 | 2731 | >>> import copy 2732 | >>> help(copy.copy) 2733 | Help on function copy in module copy: 2734 | 2735 | copy(x) 2736 | 2737 | Shallow copy operation on arbitrary Python objects. 2738 | 2739 | See the module’s __doc__ string for more info. 2740 | 2741 | The dir() function displays all the members of an object(any kind). 2742 | 2743 | >>> dir(copy.copy) 2744 | [‘__annotations__’, ‘__call__’, ‘__class__’, ‘__closure__’, ‘__code__’, ‘__defaults__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__get__’, ‘__getattribute__’, ‘__globals__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__kwdefaults__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__name__’, ‘__ne__’, ‘__new__’, ‘__qualname__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’] 2745 | 2746 | 2747 | 2748 | 267. How do you get a list of all the keys in a dictionary? 2749 | Ans:For this, we use the function keys(). 2750 | 2751 | >>> mydict={‘a’:1,‘b’:2,‘c’:3,‘e’:5} 2752 | >>> mydict.keys() 2753 | dict_keys([‘a’, ‘b’, ‘c’, ‘e’]) 2754 | 2755 | 268. How will you check if all characters in a string are alphanumeric? 2756 | Ans: For this, we use the method isalnum(). 2757 | 2758 | 2759 | 2760 | 269. With Python, how do you find out which directory you are currently in? 2761 | Ans: To find this, we use the function/method getcwd(). We import it from the module os. 2762 | 2763 | >>> import os 2764 | >>> os.getcwd() 2765 | ‘C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32’ 2766 | 2767 | >>> type(os.getcwd) 2768 | 2769 | 2770 | We can also change the current working directory with chdir(). 2771 | 2772 | >>> os.chdir(‘C:\\Users\\lifei\\Desktop’) 2773 | >>> os.getcwd() 2774 | ‘C:\\Users\\lifei\\Desktop’ 2775 | 2776 | 2777 | 2778 | 270. How do you insert an object at a given index in Python? 2779 | Ans: Let’s build a list first. 2780 | 2781 | >>> a=[1,2,4] 2782 | Now, we use the method insert. The first argument is the index at which to insert, the second is the value to insert. 2783 | 2784 | >>> a.insert(2,3) 2785 | >>> a 2786 | [1, 2, 3, 4] 2787 | 2788 | 2789 | 2790 | 271. how do you reverse a list? 2791 | Ans: Using the reverse() method. 2792 | 2793 | >>> a.reverse() 2794 | >>> a 2795 | [4, 3, 2, 1] 2796 | 2797 | You can also do it via slicing from right to left: 2798 | 2799 | >>> a[::-1] 2800 | >>> a 2801 | [1, 2, 3, 4] 2802 | 2803 | This gives us the original list because we already reversed it once. However, this does not modify the original list to reverse it. 2804 | 2805 | 2806 | 2807 | 272. How does a function return values? 2808 | Ans: A function uses the ‘return’ keyword to return a value. Take a look: 2809 | 2810 | >>> def add(a,b): 2811 | return a+b 2812 | 2813 | 2814 | 273. How would you define a block in Python? 2815 | Ans: For any kind of statements, we possibly need to define a block of code under them. However, Python does not support curly braces. This means we must end such statements with colons and then indent the blocks under those with the same amount. 2816 | 2817 | >>> if 3>1: 2818 | print(“Hello”) 2819 | print(“Goodbye”) 2820 | Hello 2821 | 2822 | Goodbye 2823 | 2824 | 2825 | 2826 | 2827 | 2828 | 274. Will the do-while loop work if you don’t end it with a semicolon? 2829 | Ans: Trick question! Python does not support an intrinsic do-while loop. Secondly, to terminate do-while loops is a necessity for languages like C++. 2830 | 2831 | 2832 | 2833 | 275. In one line, show us how you’ll get the max alphabetical character from a string.? 2834 | Ans: For this, we’ll simply use the max function. 2835 | 2836 | >>> max(‘flyiNg’) 2837 | ‘y’ 2838 | 2839 | The following are the ASCII values for all the letters of this string- 2840 | 2841 | f- 102 2842 | 2843 | l- 108 2844 | 2845 | y- 121 2846 | 2847 | i- 105 2848 | 2849 | N- 78 2850 | 2851 | g- 103 2852 | 2853 | By this logic, try to explain the following line of code- 2854 | 2855 | >>> max(‘fly{}iNg’) 2856 | ‘}’ 2857 | 2858 | (Bonus: } – 125) 2859 | 2860 | 2861 | 2862 | 276. What is Python good for? 2863 | Ans: Python is a jack of many trades, check out Applications of Python to find out more. 2864 | 2865 | Meanwhile, we’ll say we can use it for: 2866 | 2867 | Web and Internet Development 2868 | Desktop GUI 2869 | Scientific and Numeric Applications 2870 | Software Development Applications 2871 | Applications in Education 2872 | Applications in Business 2873 | Database Access 2874 | Network Programming 2875 | Games, 3D Graphics 2876 | Other Python Applications 2877 | 2878 | 2879 | 277. Can you name ten built-in functions in Python and explain each in brief? 2880 | Ans: Ten Built-in Functions, you say? Okay, here you go. 2881 | 2882 | complex()- Creates a complex number. 2883 | 2884 | >>> complex(3.5,4) 2885 | (3.5+4j) 2886 | 2887 | eval()- Parses a string as an expression. 2888 | 2889 | >>> eval(‘print(max(22,22.0)-min(2,3))’) 2890 | 20 2891 | 2892 | filter()- Filters in items for which the condition is true. 2893 | 2894 | >>> list(filter(lambda x:x%2==0,[1,2,0,False])) 2895 | [2, 0, False] 2896 | 2897 | format()- Lets us format a string. 2898 | 2899 | >>> print(“a={0} but b={1}”.format(a,b)) 2900 | a=2 but b=3 2901 | 2902 | hash()- Returns the hash value of an object. 2903 | 2904 | >>> hash(3.7) 2905 | 644245917 2906 | 2907 | hex()- Converts an integer to a hexadecimal. 2908 | 2909 | >>> hex(14) 2910 | ‘0xe’ 2911 | 2912 | input()- Reads and returns a line of string. 2913 | 2914 | >>> input(‘Enter a number’) 2915 | Enter a number7 2916 | 2917 | ‘7’ 2918 | len()- Returns the length of an object. 2919 | 2920 | >>> len(‘Ayushi’) 2921 | 6 2922 | 2923 | locals()- Returns a dictionary of the current local symbol table. 2924 | 2925 | >>> locals() 2926 | {‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: , ‘__spec__’: None, ‘__annotations__’: {}, ‘__builtins__’: , ‘a’: 2, ‘b’: 3} 2927 | 2928 | open()- Opens a file. 2929 | 2930 | >>> file=open(‘tabs.txt’) 2931 | 2932 | 2933 | 278. How will you convert a list into a string? 2934 | Ans: We will use the join() method for this. 2935 | 2936 | >>> nums=[‘one’,‘two’,‘three’,‘four’,‘five’,‘six’,‘seven’] 2937 | >>> s=‘ ‘.join(nums) 2938 | >>> s 2939 | o/p= ‘one two three four five six seven’ 2940 | 2941 | 2942 | 2943 | 279. How will you remove a duplicate element from a list? 2944 | Ans: We can turn it into a set to do that. 2945 | 2946 | >>> list=[1,2,1,3,4,2] 2947 | >>> set(list) 2948 | {1, 2, 3, 4} 2949 | 2950 | 2951 | 2952 | 280. Can you explain the life cycle of a thread? 2953 | Ans: 2954 | 2955 | python scripting interview questions 2956 | 2957 | To create a thread, we create a class that we make override the run method of the thread class. Then, we instantiate it. 2958 | A thread that we just created is in the new state. When we make a call to start() on it, it forwards the threads for scheduling. These are in the ready state. 2959 | When execution begins, the thread is in the running state. 2960 | Calls to methods like sleep() and join() make a thread wait. Such a thread is in the waiting/blocked state. 2961 | When a thread is done waiting or executing, other waiting threads are sent for scheduling. 2962 | A running thread that is done executing terminates and is in the dead state. 2963 | 2964 | 2965 | 281. Explain the //, %, and ** operators in Python? 2966 | Ans: The // operator performs floor division. It will return the integer part of the result on division. 2967 | 2968 | >>> 7//2 2969 | 3 2970 | 2971 | Normal division would return 3.5 here. 2972 | 2973 | Similarly, ** performs exponentiation. a**b returns the value of a raised to the power b. 2974 | 2975 | >>> 2**10 2976 | 1024 2977 | 2978 | Finally, % is for modulus. This gives us the value left after the highest achievable division. 2979 | 2980 | >>> 13%7 2981 | 6 2982 | 2983 | >>> 3.5%1.5 2984 | 0.5 2985 | 2986 | 2987 | 2988 | 282. What are membership operators? 2989 | Ans: With the operators ‘in’ and ‘not in’, we can confirm if a value is a member in another. 2990 | 2991 | >>> ‘me’ in ‘disappointment’ 2992 | True 2993 | 2994 | >>> ‘us’ not in ‘disappointment’ 2995 | True 2996 | 2997 | 2998 | 2999 | 283. Explain identity operators in Python? 3000 | Ans: The operators ‘is’ and ‘is not’ tell us if two values have the same identity. 3001 | 3002 | >>> 10 is ’10’ 3003 | False 3004 | 3005 | >>> True is not False 3006 | True 3007 | 3008 | 3009 | 3010 | 284. Finally, tell us about bitwise operators in Python? 3011 | 3012 | Ans: 3013 | 3014 | python interview questions for freshers 3015 | 3016 | These operate on values bit by bit. 3017 | 3018 | AND (&) This performs & on each bit pair. 3019 | 3020 | >>> 0b110 & 0b010 3021 | 2 3022 | 3023 | OR (|) This performs | on each bit pair. 3024 | 3025 | >>> 3|2 3026 | 3 3027 | 3028 | XOR (^) This performs an exclusive-OR operation on each bit pair. 3029 | 3030 | >>> 3^2 3031 | 1 3032 | 3033 | Binary One’s Complement (~) This returns the one’s complement of a value. 3034 | 3035 | >>> ~2 3036 | -3 3037 | 3038 | Binary Left-Shift (<<) This shifts the bits to the left by the specified amount. 3039 | 3040 | >>> 1<<2 3041 | 4 3042 | 3043 | Here, 001 was shifted to the left by two places to get 100, which is binary for 4. 3044 | 3045 | Binary Right-Shift (>>) 3046 | 3047 | >>> 4>>2 3048 | 1 3049 | 3050 | 3051 | 3052 | 285. What data types does Python support? 3053 | Ans: Python provides us with five kinds of data types: 3054 | 3055 | Numbers – Numbers use to hold numerical values. 3056 | 3057 | >>> a=7.0 3058 | >>> 3059 | Strings – A string is a sequence of characters. We declare it using single or double quotes. 3060 | 3061 | >>> title=“Ayushi’s Book” 3062 | Lists – A list is an ordered collection of values, and we declare it using square brackets. 3063 | 3064 | >>> colors=[‘red’,‘green’,‘blue’] 3065 | >>> type(colors) 3066 | 3067 | 3068 | 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. 3069 | 3070 | >>> name=(‘Ayushi’,‘Sharma’) 3071 | >>> name[0]=‘Avery’ 3072 | Traceback (most recent call last): 3073 | 3074 | File “”, line 1, in 3075 | 3076 | name[0]=’Avery’ 3077 | 3078 | TypeError: ‘tuple’ object does not support item assignment 3079 | 3080 | Dictionary – A dictionary is a data structure that holds key-value pairs. We declare it using curly braces. 3081 | 3082 | >>> squares={1:1,2:4,3:9,4:16,5:25} 3083 | >>> type(squares) 3084 | 3085 | 3086 | >>> type({}) 3087 | 3088 | 3089 | We can also use a dictionary comprehension: 3090 | 3091 | >>> squares={x:x**2 for x in range(1,6)} 3092 | >>> squares 3093 | {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} 3094 | 3095 | 3096 | 3097 | 286. How would you convert a string into an int in Python? 3098 | Ans: If a string contains only numerical characters, you can convert it into an integer using the int() function. 3099 | 3100 | >>> int(‘227’) 3101 | 227 3102 | 3103 | Let’s check the types: 3104 | 3105 | >>> type(‘227’) 3106 | 3107 | 3108 | >>> type(int(‘227’)) 3109 | 3110 | 3111 | 3112 | 3113 | 287. How do you take input in Python? 3114 | Ans: For taking input from the user, we have the function input(). In Python 2, we had another function raw_input(). 3115 | 3116 | The input() function takes, as an argument, the text to be displayed for the task: 3117 | 3118 | >>> a=input(‘Enter a number’) 3119 | Enter a number7 3120 | 3121 | But if you have paid attention, you know that it takes input in the form of a string. 3122 | 3123 | >>> type(a) 3124 | 3125 | 3126 | Multiplying this by 2 gives us this: 3127 | 3128 | >>> a*=2 3129 | >>> a 3130 | ’77’ 3131 | 3132 | So, what if we need to work on an integer instead? 3133 | 3134 | We use the int() function for this. 3135 | 3136 | >>> a=int(input(‘Enter a number’)) 3137 | Enter a number7 3138 | 3139 | Now when we multiply it by 2, we get this: 3140 | 3141 | >>> a*=2 3142 | >>> a 3143 | 14 3144 | 3145 | 3146 | 3147 | 288. What is a function? 3148 | Ans: 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. 3149 | 3150 | >>> def greater(a,b): 3151 | return a is a>b else b 3152 | >>> greater(3,3.5) 3153 | 3.5 3154 | 3155 | 3156 | 3157 | 3158 | 3159 | 289. What is recursion? 3160 | Ans: 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. 3161 | 3162 | Let’s take an example. 3163 | 3164 | >>> def facto(n): 3165 | if n==1: return 1 3166 | return n*facto(n-1) 3167 | >>> facto(4) 3168 | 24 3169 | 3170 | 3171 | 3172 | 3173 | 3174 | 290. What do you know about relational operators in Python? 3175 | Ans: 3176 | 3177 | Top python interview questions with answers 3178 | 3179 | 3180 | 3181 | Relational operators compare values. 3182 | 3183 | Less than (<) If the value on the left is lesser, it returns True. 3184 | 3185 | >>> ‘hi’<‘Hi’ 3186 | False 3187 | Greater than (>) If the value on the left is greater, it returns True. 3188 | 3189 | >>> 1.1+2.2>3.3 3190 | True 3191 | 3192 | This is because of the flawed floating-point arithmetic in Python, due to hardware dependencies. 3193 | 3194 | Less than or equal to (<=) If the value on the left is lesser than or equal to, it returns True. 3195 | 3196 | >>> 3.0<=3 3197 | True 3198 | 3199 | Greater than or equal to (>=) If the value on the left is greater than or equal to, it returns True. 3200 | 3201 | >>> True>=False 3202 | True 3203 | 3204 | Equal to (==) If the two values are equal, it returns True. 3205 | 3206 | >>> {1,3,2,2}=={1,2,3} 3207 | True 3208 | 3209 | Not equal to (!=) If the two values are unequal, it returns True. 3210 | 3211 | >>> True!=0.1 3212 | True 3213 | 3214 | >>> False!=0.1 3215 | True 3216 | 3217 | 3218 | 3219 | 291. What are assignment operators in Python? 3220 | Ans: 3221 | 3222 | 3223 | 3224 | python coding interview questions 3225 | 3226 | We can combine all arithmetic operators with the assignment symbol. 3227 | 3228 | >>> a=7 3229 | >>> a+=1 3230 | >>> a 3231 | 8 3232 | 3233 | >>> a-=1 3234 | >>> a 3235 | 7 3236 | 3237 | >>> a*=2 3238 | >>> a 3239 | 14 3240 | 3241 | >>> a/=2 3242 | >>> a 3243 | 7.0 3244 | 3245 | >>> a**=2 3246 | >>> a 3247 | 49.0 3248 | 3249 | >>> a//=3 3250 | >>> a 3251 | 16.0 3252 | 3253 | >>> a%=4 3254 | >>> a 3255 | 0.0 3256 | 3257 | 3258 | 3259 | 3260 | 3261 | 292. Explain logical operators in Python.? 3262 | Ans: We have three logical operators- and, or, not. 3263 | 3264 | >>> False and True 3265 | False 3266 | 3267 | >>> 7<7 or True 3268 | True 3269 | 3270 | >>> not 2==2 3271 | False 3272 | 3273 | 3274 | 3275 | 3276 | 3277 | 293. What does the function zip() do? 3278 | Ans: One of the less common functions with beginners, zip() returns an iterator of tuples. 3279 | 3280 | >>> list(zip([‘a’,‘b’,‘c’],[1,2,3])) 3281 | [(‘a’, 1), (‘b’, 2), (‘c’, 3)] 3282 | 3283 | Here, it pairs items from the two lists and creates tuples with those. But it doesn’t have to be lists. 3284 | 3285 | >>> list(zip((‘a’,‘b’,‘c’),(1,2,3))) 3286 | [(‘a’, 1), (‘b’, 2), (‘c’, 3)] 3287 | 3288 | 3289 | 3290 | 294. How can you declare multiple assignments in one statement? 3291 | Ans: There are two ways to do this: 3292 | 3293 | First – 3294 | 3295 | >>> a,b,c=3,4,5 #This assigns 3, 4, and 5 to a, b, and c respectively 3296 | Second – 3297 | 3298 | >>> a=b=c=3 #This assigns 3 to a, b, and c 3299 | 3300 | 3301 | 3302 | 3303 | 295. If you are ever stuck in an infinite loop, how will you break out of it? 3304 | Ans: For this, we press Ctrl+C. This interrupts the execution. Let’s create an infinite loop to demonstrate this. 3305 | 3306 | >>> def counterfunc(n): 3307 | while(n==7):print(n) 3308 | >>> counterfunc(7) 3309 | 7 3310 | 3311 | 7 3312 | 3313 | 7 3314 | 3315 | 7 3316 | 3317 | 7 3318 | 3319 | 7 3320 | 3321 | 7 3322 | 3323 | 7 3324 | 3325 | 7 3326 | 3327 | 7 3328 | 3329 | 7 3330 | 3331 | 7 3332 | 3333 | 7 3334 | 3335 | 7 3336 | 3337 | 7 3338 | 3339 | 7 3340 | 3341 | 7 3342 | 3343 | Traceback (most recent call last): 3344 | 3345 | File “”, line 1, in 3346 | 3347 | counterfunc(7) 3348 | 3349 | File “”, line 2, in counterfunc 3350 | 3351 | while(n==7):print(n) 3352 | 3353 | KeyboardInterrupt 3354 | 3355 | 3356 | 3357 | 3358 | 3359 | 296. How is a .pyc file different from a .py file? 3360 | Ans: 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). 3361 | 3362 | 3363 | 3364 | 297. How many types of objects does Python support? 3365 | Ans: Immutable objects- Those which do not let us modify their contents. Examples of these will be tuples, booleans, strings, integers, floats, and complexes. Iterations on such objects are faster. 3366 | 3367 | >>> tuple=(1,2,4) 3368 | >>> tuple 3369 | (1, 2, 4) 3370 | 3371 | >>> 2+4j 3372 | (2+4j) 3373 | 3374 | Mutable objects – Those that let you modify their contents. Examples of these are lists, sets, and dicts. Iterations on such objects are slower. 3375 | 3376 | >>> [2,4,9] 3377 | [2, 4, 9] 3378 | 3379 | >>> dict1={1:1,2:2} 3380 | >>> dict1 3381 | {1: 1, 2: 2} 3382 | 3383 | While two equal immutable objects’ reference variables share the same address, it is possible to create two mutable objects with the same content. 3384 | 3385 | 3386 | 3387 | 298. When is the else part of a try-except block executed? 3388 | Ans: In an if-else block, the else part is executed when the condition in the if-statement is False. But with a try-except block, the else part executes only if no exception is raised in the try part. 3389 | 3390 | 3391 | 3392 | 3393 | 3394 | 299. Explain join() and split() in Python? 3395 | Ans: 3396 | 3397 | 1)join() lets us join characters from a string together by a character we specify. 3398 | 3399 | >>> ‘,’.join(‘12345’) 3400 | ‘1,2,3,4,5’ 3401 | 3402 | 2) split() lets us split a string around the character we specify. 3403 | 3404 | >>> ‘1,2,3,4,5’.split(‘,’) 3405 | [‘1’, ‘2’, ‘3’, ‘4’, ‘5’] 3406 | 3407 | 3408 | 3409 | 300. Explain a few methods to implement Functionally Oriented Programming in Python? 3410 | Ans: 3411 | 3412 | Sometimes, when we want to iterate over a list, a few methods come in handy. 3413 | 3414 | a. filter() 3415 | 3416 | Filter lets us filter in some values based on conditional logic. 3417 | 3418 | >>> list(filter(lambda x:x>5,range(8))) 3419 | [6, 7] 3420 | 3421 | b. map() 3422 | 3423 | Map applies a function to every element in an iterable. 3424 | 3425 | >>> list(map(lambda x:x**2,range(8))) 3426 | [0, 1, 4, 9, 16, 25, 36, 49] 3427 | c. reduce() 3428 | 3429 | Reduce repeatedly reduces a sequence pair-wise until we reach a single value. 3430 | 3431 | >>> from functools import reduce 3432 | >>> reduce(lambda x,y:x-y,[1,2,3,4,5]) 3433 | -13 3434 | 3435 | 300. Explain a few methods to implement Functionally Oriented Programming in Python? 3436 | Ans: 3437 | 3438 | Sometimes, when we want to iterate over a list, a few methods come in handy. 3439 | 3440 | a. filter() 3441 | 3442 | Filter lets us filter in some values based on conditional logic. 3443 | 3444 | >>> list(filter(lambda x:x>5,range(8))) 3445 | [6, 7] 3446 | 3447 | b. map() 3448 | 3449 | Map applies a function to every element in an iterable. 3450 | 3451 | >>> list(map(lambda x:x**2,range(8))) 3452 | [0, 1, 4, 9, 16, 25, 36, 49] 3453 | c. reduce() 3454 | 3455 | Reduce repeatedly reduces a sequence pair-wise until we reach a single value. 3456 | 3457 | >>> from functools import reduce 3458 | >>> reduce(lambda x,y:x-y,[1,2,3,4,5]) 3459 | -13 3460 | 3461 | 3462 | 3463 | 301. Is del the same as remove()? What are they? 3464 | Ans: 3465 | 3466 | del and remove() are methods on lists/ ways to eliminate elements. 3467 | 3468 | >>> list=[3,4,5,6,7] 3469 | >>> del list[3] 3470 | >>> list 3471 | [3, 4, 5, 7] 3472 | 3473 | >>> list.remove(5) 3474 | >>> list 3475 | [3, 4, 7] 3476 | 3477 | While del lets us delete an element at a certain index, remove() lets us remove an element by its value. 3478 | 3479 | 3480 | 3481 | 302. Explain a few methods to implement Functionally Oriented Programming in Python? 3482 | Ans: Sometimes, when we want to iterate over a list, a few methods come in handy. 3483 | 3484 | a. filter() 3485 | 3486 | Filter lets us filter in some values based on conditional logic. 3487 | 3488 | >>> list(filter(lambda x:x>5,range(8))) 3489 | [6, 7] 3490 | 3491 | b. map() 3492 | 3493 | Map applies a function to every element in an iterable. 3494 | 3495 | >>> list(map(lambda x:x**2,range(8))) 3496 | [0, 1, 4, 9, 16, 25, 36, 49] 3497 | c. reduce() 3498 | 3499 | Reduce repeatedly reduces a sequence pair-wise until we reach a single value. 3500 | 3501 | >>> from functools import reduce 3502 | >>> reduce(lambda x,y:x-y,[1,2,3,4,5]) 3503 | -13 3504 | 3505 | 3506 | 3507 | 304. How do you open a file for writing? 3508 | Ans: Let’s create a text file on our Desktop and call it tabs.txt. To open it to be able to write to it, use the following line of code- 3509 | 3510 | >>> file=open(‘tabs.txt’,‘w’) 3511 | This opens the file in writing mode. You should close it once you’re done. 3512 | 3513 | >>> file.close() 3514 | 3515 | 3516 | 3517 | 3518 | 305. Difference between the append() and extend() methods of a list. 3519 | 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. 3520 | 3521 | Let’s take two lists. 3522 | 3523 | >>> list1,list2=[1,2,3],[5,6,7,8] 3524 | This is how append() works: 3525 | 3526 | >>> list1.append(4) 3527 | >>> list1 3528 | [1, 2, 3, 4] 3529 | 3530 | And this is how extend() works: 3531 | 3532 | >>> list1.extend(list2) 3533 | >>> list1 3534 | [1, 2, 3, 4, 5, 6, 7, 8] 3535 | 3536 | 3537 | 3538 | 306. What are the different file-processing modes with Python? 3539 | We have the following modes- 3540 | 3541 | read-only – ‘r’ 3542 | write-only – ‘w’ 3543 | read-write – ‘rw’ 3544 | append – ‘a’ 3545 | We can open a text file with the option ‘t’. So to open a text file to read it, we can use the mode ‘rt’. Similarly, for binary files, we use ‘b’. 3546 | 3547 | 3548 | 3549 | 3550 | 3551 | 307. What does the map() function do? 3552 | Ans: map() executes the function we pass to it as the first argument; it does so on all elements of the iterable in the second argument. Let’s take an example, shall we? 3553 | 3554 | >>> for i in map(lambda i:i**3, (2,3,7)): 3555 | print(i) 3556 | 8 3557 | 27 3558 | 343 3559 | 3560 | This gives us the cubes of the values 2, 3, and 7. 3561 | 3562 | 3563 | 3564 | 3565 | 3566 | 308. Is there a way to remove the last object from a list? 3567 | Yes, there is. Try running the following piece of code- 3568 | 3569 | >>> list=[1,2,3,4,5 3570 | >>> list.pop(–1) 3571 | 5 3572 | 3573 | >>> list 3574 | [1, 2, 3, 4] 3575 | 3576 | 3577 | 3578 | 3579 | 3580 | 3581 | 3582 | 309. How will you convert an integer to a Unicode character? 3583 | Ans: This is simple. All we need is the chr(x) built-in function. See how. 3584 | 3585 | >>> chr(52) 3586 | ‘4’ 3587 | 3588 | >>> chr(49) 3589 | ‘1’ 3590 | 3591 | >>> chr(67) 3592 | ‘C’ 3593 | 3594 | 3595 | 3596 | 3597 | 3598 | 310. So does recursion cause any trouble? 3599 | Ans: Sure does: 3600 | 3601 | Needs more function calls. 3602 | Each function call stores a state variable to the program stack- consumes memory, can cause memory overflow. 3603 | Calling a function consumes time. 3604 | 3605 | 3606 | 3607 | 3608 | 3609 | 3610 | 311. What good is recursion? 3611 | Ans: With recursion, we observe the following: 3612 | 3613 | Need to put in less efforts. 3614 | Smaller code than that by loops. 3615 | Easier-to-understand code. 3616 | 3617 | 3618 | 3619 | 3620 | 3621 | 3622 | 3623 | 3624 | 3625 | 3626 | 312. Can you remove the whitespaces from the string “aaa bbb ccc ddd eee”? 3627 | Ans: I can think of three ways to do this. 3628 | 3629 | Using join- 3630 | 3631 | >>> s=‘aaa bbb ccc ddd eee’ 3632 | >>> s1=”.join(s.split()) 3633 | >>> s1 3634 | ‘aaabbbcccdddeee’ 3635 | 3636 | Using a list comprehension– 3637 | 3638 | >>> s=‘aaa bbb ccc ddd eee’ 3639 | >>> s1=str(”.join(([i for i in s if i!=‘ ‘]))) 3640 | >>> s1 3641 | ‘aaabbbcccdddeee’ 3642 | 3643 | Using replace()- 3644 | 3645 | >>> s=‘aaa bbb ccc ddd eee’ 3646 | >>> s1 = s.replace(‘ ‘,”) 3647 | >>> s1 3648 | ‘aaabbbcccdddeee’ 3649 | 3650 | 3651 | 3652 | 3653 | 3654 | 3655 | 3656 | 313. How do you get the current working directory using Python? 3657 | Ans: Working on software with Python, you may need to read and write files from various directories. To find out which directory we’re presently working under, we can borrow the getcwd() method from the os module. 3658 | 3659 | >>> import os 3660 | >>> os.getcwd() 3661 | ‘C:\\Users\\Raj\\AppData\\Local\\Programs\\Python\\Python37-32’ 3662 | 3663 | 3664 | 3665 | 314. What are the file-related modules we have in Python? 3666 | Ans: We have the following libraries and modules that let us manipulate text and binary files on our file systems- 3667 | 3668 | os 3669 | os.path 3670 | shutil 3671 | 3672 | 3673 | 3674 | 3675 | 3676 | 3677 | 3678 | 315. Explain the uses of the modules sqlite3, ctypes, pickle, traceback, and itertools. 3679 | sqlite3- Helps with handling databases of type SQLite 3680 | ctypes- Lets create and manipulate C data types in Python 3681 | pickle- Lets put any data structure to external files 3682 | traceback- Allows extraction, formatting, and printing of stack traces 3683 | itertools– Supports working with permutations, combinations, and other useful iterables. 3684 | 3685 | 3686 | 3687 | 3688 | 3689 | 3690 | 316. How will you print the contents of a file? 3691 | >>> try: 3692 | with open(‘tabs.txt’,‘r’) as f: 3693 | print(f.read()) 3694 | except IOError: 3695 | print(“File not found”) 3696 | 3697 | 3698 | 3699 | 3700 | 3701 | 3702 | 317. What is Virtualenv in Python? 3703 | Ans: virtualenv is a tool to create isolated Python environments. virtualenv creates a folder which contains all the necessary executables to use the packages that a Python project would need. It can be used standalone, in place of Pipenv. 3704 | 3705 | Install virtualenv via pip: $ pip install virtualenv. 3706 | 3707 | 3708 | 3709 | 3710 | 3711 | 318. What is the function of “self”? 3712 | Ans: Self is a variable that represents the instance of the object to itself. In most of the object oriented programming language, this is passed to the methods as a hidden parameters that is defined by an object. But, in python, it is declared and passed explicitly. It is the first argument that gets created in the instance of the class A and the parameters to the methods are passed automatically. It refers to separate instance of the variable for individual objects. 3713 | 3714 | Let’s say you have a class ClassA which contains a method methodA defined as: 3715 | 3716 | def methodA(self, arg1, arg2): #do something 3717 | and ObjectA is an instance of this class. 3718 | 3719 | Now when ObjectA.methodA(arg1, arg2) is called, python internally converts it for you as: 3720 | 3721 | ClassA.methodA(ObjectA, arg1, arg2) 3722 | The self variable refers to the object itself. 3723 | 3724 | 3725 | 3726 | 3727 | 3728 | 319. What does the Python nonlocal statement do (in Python 3.0 and later)? 3729 | Ans: In short, it lets you assign values to a variable in an outer (but non-global) scope. 3730 | 3731 | The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. 3732 | 3733 | For example the counter generator can be rewritten to use this so that it looks more like the idioms of languages with closures. 3734 | 3735 | def make_counter(): 3736 | count = 0 3737 | def counter(): 3738 | nonlocal count 3739 | count += 1 3740 | return count 3741 | return counter 3742 | 3743 | 3744 | 3745 | 3746 | 3747 | 3748 | 320. What are the wheels and eggs? What is the difference? 3749 | Ans: 3750 | 3751 | Wheel and Egg are both packaging formats that aim to support the use case of needing an install artifact that doesn’t require building or compilation, which can be costly in testing and production workflows. 3752 | 3753 | The Egg format was introduced by setuptools in 2004, whereas the Wheel format was introduced by PEP 427 in 2012. 3754 | 3755 | Wheel is currently considered the standard for built and binary packaging for Python. 3756 | 3757 | Here’s a breakdown of the important differences between Wheel and Egg. 3758 | 3759 | Wheel has an official PEP. Egg did not. 3760 | Wheel is a distribution format, i.e a packaging format. 1 Egg was both a distribution format and a runtime installation format (if left zipped), and was designed to be importable. 3761 | Wheel archives do not include .pyc files. Therefore, when the distribution only contains Python files (i.e. no compiled extensions), and is compatible with Python 2 and 3, it’s possible for a wheel to be “universal”, similar to an sdist. 3762 | Wheel uses PEP376-compliant .dist-info directories. Egg used .egg-info. 3763 | Wheel has a richer file naming convention. A single wheel archive can indicate its compatibility with a number of Python language versions and implementations, ABIs, and system architectures. 3764 | Wheel is versioned. Every wheel file contains the version of the wheel specification and the implementation that packaged it. 3765 | Wheel is internally organized by sysconfig path type, therefore making it easier to convert to other formats. 3766 | 3767 | 3768 | 3769 | 3770 | 3771 | 3772 | 321. What is webpack? 3773 | Ans: Webpack is a build tool that puts all of your assets, including Javascript, images, fonts, and CSS, in a dependency graph. Webpack lets you use require() in your source code to point to local files, like images, and decide how they’re processed in your final Javascript bundle, like replacing the path with a URL pointing to a CDN. 3774 | 3775 | 3776 | 3777 | 3778 | 3779 | 322. Name some benefits of using webpack 3780 | Ans: Webpack and static assets in a dependency graph offers many benefits. Here’s a few: 3781 | 3782 | Dead asset elimination. This is killer, especially for CSS rules. You only build the images and CSS into your dist/ folder that your application actually needs. 3783 | Easier code splitting. For example, because you know that your file Homepage.js only requires specific CSS files, Webpack could easily build a homepage.css file to greatly reduce initial file size. 3784 | You control how assets are processed. If an image is below a certain size, you could base64 encode it directly into your Javascript for fewer HTTP requests. If a JSON file is too big, you can load it from a URL. You can require('./style.less') and it’s automaticaly parsed by Less into vanilla CSS. 3785 | Stable production deploys. You can’t accidentally deploy code with images missing, or outdated styles. 3786 | Webpack will slow you down at the start, but give you great speed benefits when used correctly. You get hot page reloading. True CSS management. CDN cache busting because Webpack automatically changes file names to hashes of the file contents, etc. 3787 | Webpack is the main build tool adopted by the React community. 3788 | 3789 | 3790 | 3791 | 3792 | 3793 | 3794 | 3795 | 323. Name some plugins you think are very important and helpful? 3796 | Ans: 3797 | 3798 | CommonsChunkPlugin – creates a separate file (known as a chunk), consisting of common modules shared between multiple entry points. 3799 | DefinePlugin – allows you to create global constants which can be configured at compile time. 3800 | HtmlWebpackPlugin – simplifies creation of HTML files to serve your webpack bundles. 3801 | ExtractTextWebpackPlugin – Extract text from a bundle, or bundles, into a separate file. 3802 | CompressionWebpackPlugin – Prepare compressed versions of assets to serve them with Content-Encoding. 3803 | 3804 | 3805 | 3806 | 3807 | 3808 | 3809 | 324. Webpack gives us a dependency graph. What does that mean? 3810 | Ans: Any time one file depends on another, webpack treats this as a dependency. This allows webpack to take non-code assets, such as images or web fonts, and also provide them as dependencies for your application. 3811 | 3812 | Webpack lets you use require() on local “static assets”: 3813 | 3814 | 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(""); 4194 | 4195 | 4196 | 4197 | 4198 | 4199 | 4200 | 346. Write a program to count the number of capital letters in a file? 4201 | Ans: 4202 | 1 4203 | 2 4204 | 3 4205 | 4 4206 | 5 4207 | 6 4208 | with open(SOME_LARGE_FILE) as countletter: 4209 | count = 0 4210 | text = countletter.read() 4211 | for character in text: 4212 | if character.isupper(): 4213 | count += 1 4214 | 4215 | 4216 | 4217 | 4218 | 4219 | 4220 | 4221 | 4222 | 347. Write a program to display the Fibonacci sequence in Python? 4223 | Ans: 4224 | 1 4225 | 2 4226 | 3 4227 | 4 4228 | 5 4229 | 6 4230 | 7 4231 | 8 4232 | 9 4233 | 10 4234 | 11 4235 | 12 4236 | 13 4237 | 14 4238 | 15 4239 | 16 4240 | 17 4241 | 18 4242 | 19 4243 | 20 4244 | 21 4245 | # Displaying Fibonacci sequence 4246 | n = 10 4247 | # first two terms 4248 | n0 = 0 4249 | n1 = 1 4250 | #Count 4251 | x = 0 4252 | # check if the number of terms is valid 4253 | if n <= 0: 4254 | print("Enter positive integer") 4255 | elif n == 1: 4256 | print("Numbers in Fibonacci sequence upto",n,":") 4257 | print(n0) 4258 | else: 4259 | print("Numbers in Fibonacci sequence upto",n,":") 4260 | while x < n: 4261 | print(n0,end=', ') 4262 | nth = n0 + n1 4263 | n0 = n1 4264 | n1 = nth 4265 | x += 1 4266 | Output: 4267 | 4268 | 1 4269 | 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 4270 | 4271 | 4272 | 4273 | 4274 | 4275 | 4276 | 348. Write a program in Python to produce Star triangle? 4277 | Ans: The code to produce star triangle is as follows: 4278 | 4279 | 1 4280 | 2 4281 | 3 4282 | 4 4283 | def pyfun(r): 4284 | for a in range(r): 4285 | print(' '*(r-x-1)+'*'*(2*x+1)) 4286 | pyfun(9) 4287 | Output: 4288 | 4289 | 1 4290 | 2 4291 | 3 4292 | 4 4293 | 5 4294 | 6 4295 | 7 4296 | 8 4297 | 9 4298 | * 4299 | *** 4300 | ***** 4301 | ******* 4302 | ********* 4303 | *********** 4304 | ************* 4305 | *************** 4306 | ***************** 4307 | 4308 | 4309 | 4310 | 4311 | 349. Write a program to check whether the given number is prime or not? 4312 | Ans: The code to check prime number is as follows: 4313 | 4314 | 1 4315 | 2 4316 | 3 4317 | 4 4318 | 5 4319 | 6 4320 | 7 4321 | 8 4322 | 9 4323 | 10 4324 | 11 4325 | 12 4326 | 13 4327 | 14 4328 | 15 4329 | 16 4330 | 17 4331 | # program to check the number is prime or not 4332 | n1 = 409 4333 | # num1 = int(input("Enter any one number: ")) 4334 | # prime number is greater than 1 4335 | if n1 > 1: 4336 | # check the following factors 4337 | for x is in range of(2,num1): 4338 | if (n1 % x) == 0: 4339 | print(n1,"is not a prime number") 4340 | print(x,"times",n1//x,"is",num) 4341 | break 4342 | else: 4343 | print(n1,"is a prime number") 4344 | # if input number is smaller than 4345 | # or equal to the value 1, then it is not prime number 4346 | else: 4347 | print(n1,"is not a prime number") 4348 | Output: 4349 | 4350 | 1 4351 | 409 is a prime number 4352 | 4353 | 4354 | 4355 | 4356 | 4357 | 4358 | 4359 | 4360 | 350. Write Python code to check the given sequence is a palindrome or not? 4361 | Ans: 4362 | 4363 | 1 4364 | 2 4365 | 3 4366 | 4 4367 | 5 4368 | 6 4369 | 7 4370 | 8 4371 | 9 4372 | 10 4373 | 11 4374 | # Python code to check a given sequence 4375 | # is palindrome or not 4376 | my_string1 = 'MOM' 4377 | My_string1 = my_string1.casefold() 4378 | # reverse the given string 4379 | rev_string1 = reversed(my_string1) 4380 | # check whether the string is equal to the reverse of it or not 4381 | if list(my_string1) == list(rev_string1): 4382 | print("It is a palindrome") 4383 | else: 4384 | print("It is not a palindrome") 4385 | Output: 4386 | 4387 | 1 4388 | it is a palindrome 4389 | 4390 | 4391 | 4392 | 4393 | 4394 | 4395 | 4396 | 4397 | 351. Write Python code to sort a numerical dataset? 4398 | Ans: The code to sort a numerical dataset is as follows: 4399 | 4400 | 1 4401 | 2 4402 | 3 4403 | 4 4404 | list = [ "13", "16", "1", "5" , "8"] 4405 | list = [int(x) for x in the list] 4406 | list.sort() 4407 | print(list) 4408 | Output: 4409 | 4410 | 1 4411 | 1, 5, 8, 13, 16 4412 | 4413 | 4414 | 4415 | 4416 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 300-python-Interview-questions-and-solutions --------------------------------------------------------------------------------