Movatterモバイル変換


[0]ホーム

URL:


Menu
×
Sign In
+1 Get Certified For Teachers Spaces Plus Get Certified For Teachers Spaces Plus
   ❮     
     ❯   

Python Tutorial

Python HOMEPython IntroPython Get StartedPython SyntaxPython CommentsPython VariablesPython Data TypesPython NumbersPython CastingPython StringsPython BooleansPython OperatorsPython ListsPython TuplesPython SetsPython DictionariesPython If...ElsePython MatchPython While LoopsPython For LoopsPython FunctionsPython LambdaPython ArraysPython OOPPython Classes/ObjectsPython InheritancePython IteratorsPython PolymorphismPython ScopePython ModulesPython DatesPython MathPython JSONPython RegExPython PIPPython Try...ExceptPython String FormattingPython User InputPython VirtualEnv

File Handling

Python File HandlingPython Read FilesPython Write/Create FilesPython Delete Files

Python Modules

NumPy TutorialPandas TutorialSciPy TutorialDjango Tutorial

Python Matplotlib

Matplotlib IntroMatplotlib Get StartedMatplotlib PyplotMatplotlib PlottingMatplotlib MarkersMatplotlib LineMatplotlib LabelsMatplotlib GridMatplotlib SubplotMatplotlib ScatterMatplotlib BarsMatplotlib HistogramsMatplotlib Pie Charts

Machine Learning

Getting StartedMean Median ModeStandard DeviationPercentileData DistributionNormal Data DistributionScatter PlotLinear RegressionPolynomial RegressionMultiple RegressionScaleTrain/TestDecision TreeConfusion MatrixHierarchical ClusteringLogistic RegressionGrid SearchCategorical DataK-meansBootstrap AggregationCross ValidationAUC - ROC CurveK-nearest neighbors

Python DSA

Python DSALists and ArraysStacksQueuesLinked ListsHash TablesTreesBinary TreesBinary Search TreesAVL TreesGraphsLinear SearchBinary SearchBubble SortSelection SortInsertion SortQuick SortCounting SortRadix SortMerge Sort

Python MySQL

MySQL Get StartedMySQL Create DatabaseMySQL Create TableMySQL InsertMySQL SelectMySQL WhereMySQL Order ByMySQL DeleteMySQL Drop TableMySQL UpdateMySQL LimitMySQL Join

Python MongoDB

MongoDB Get StartedMongoDB Create DBMongoDB CollectionMongoDB InsertMongoDB FindMongoDB QueryMongoDB SortMongoDB DeleteMongoDB Drop CollectionMongoDB UpdateMongoDB Limit

Python Reference

Python OverviewPython Built-in FunctionsPython String MethodsPython List MethodsPython Dictionary MethodsPython Tuple MethodsPython Set MethodsPython File MethodsPython KeywordsPython ExceptionsPython Glossary

Module Reference

Random ModuleRequests ModuleStatistics ModuleMath ModulecMath Module

Python How To

Remove List DuplicatesReverse a StringAdd Two Numbers

Python Examples

Python ExamplesPython CompilerPython ExercisesPython QuizPython ServerPython SyllabusPython Study PlanPython Interview Q&APython BootcampPython CertificatePython Training

PythonInterview Questions


This page contains a list of typical Python Interview Questions and Answers.


Python Interview Questions

These questions and answers cover some fundamental Python concepts that are often discussed in interviews.


1) What is the difference between global and local scope?

  • A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
  • A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local.

2) What is an iterator in Python?

  • An iterator is an object that contains a countable number of values.
  • An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
  • Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().

3) What is the __init__() function in Python?

  • All classes in Python have a function called __init__(), which is always executed when the class is being initiated.
  • We can use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created.

4) When should you use lambda functions in Python?

  • Use lambda functions when an anonymous function is required for a short period of time.

5) What is the difference between lists, tuples and sets?

Lists, tuples, and sets are all used to store multiple items in a single variable, but they have different properties:

  • A list is ordered and changeable. It allows duplicate values.
  • A tuple is ordered but unchangeable (immutable). It also allows duplicates.
  • A set is unordered, unindexed, and contains only unique items. It is changeable, but you cannot modify individual elements by index.

6) How can you check if all the characters in a string are alphanumeric?

  • You can use theisalnum() method, which returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).

7) How can you convert a string to an integer?

  • You can use theint() function, like this:
  • num = "5"
    convert = int(num)

8) What is indentation in Python, and why is it important?

  • Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important.
  • Python uses indentation to indicate a block of code.
  • Python will give you an error if you skip the indentation.

9) What is the correct syntax to output the type of a variable or object in Python?

    print(type(x))

10) Which collection does not allow duplicate members?

  • SET

11) What is Inheritance in Python?

  • Inheritance allows us to define a class that inherits all the methods and properties from another class.
  • Parent class is the class being inherited from, also called base class.
  • Child class is the class that inherits from another class, also called derived class.

12) What is the output of the following code?

x = 41if x > 10:  print("Above ten,")  if x > 20:    print("and also above 20!")  else:    print("but not above 20.")
  • Above ten,
    and also above 20!

13) Can you list Python's primary built-in data types, in categories?

  • Text Type:str
  • Numeric Types:int,float,complex
  • Sequence Types:list,tuple,range
  • Mapping Type:dict
  • Set Types:set,frozenset
  • Boolean Type:bool
  • Binary Types:bytes,bytearray,memoryview

14) What are Membership Operators?

  • Membership operators are used to test if a sequence is present in an object. Thein andnot in operators are examples of these:

  • x = ["apple", "banana"]
    print("banana" in x) # returns True

    x = ["apple", "banana"]
    print("pineapple" not in x) # returns True

15) Whichstatement can be used to avoid errors if anif statement has no content?

  • Thepass statement

16) What are Arbitrary Arguments?

  • Arbitrary Arguments are often shortened to*args in Python documentations.
  • If you do not know how many arguments that will be passed into your function, add a* before the parameter name in the function definition. This way the function will receive a tuple of arguments, and can access the items accordingly.

17) How can you create and use a Module in Python??

  • To create a module just save the code you want in a file with the file extension.py:

    def greeting(name):
      print("Hello, " + name)
  • Now we can use the module we just created, by using theimport statement:

    import mymodule

    mymodule.greeting("Jonathan")

18) Can you copy a List in Python by simply writing:list2 = list1?

  • No, because:list2 will only be areference tolist1, and changes made inlist1 will automatically also be made inlist2.
  • To make a copy of a list, you can usecopy() or thelist() method.

19) How can you return a range of characters of a string?

  • You can return a range of characters by using the "slice syntax".
  • Specify the start index and the end index, separated by a colon, to return a part of the string, for example:
  • Get the characters from position 2 to position 5 (not included):

    b = "Hello, World!"
    print(b[2:5])

20) What is a class in Python, and how do you use it?

  • A Class is like an object constructor, or a "blueprint" for creating objects.
  • You can create a class with the class keyword:
    class MyClass:
    x = 5

    Now we can use the class named MyClass to create objects:

    Create an object named p1, and print the value of x:

    p1 = MyClass()
    print(p1.x)

Kickstart your career

Get certified by completingthe course

Get certifiedw3schoolsCERTIFIED.2025

 
Track your progress - it's free!
 

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp