Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Interview Questions and Answers
Next article icon

Python Interview Questions and Answers

Last Updated : 10 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Python Interview Questions. We have prepared a list of the Top 50 Python Interview Questions along with their answers to ace interviews.

Python Interview Questions for Freshers

1. Is Python a compiled language or an interpreted language?

Please remember one thing, whether a language is compiled or interpreted or both is not defined in the language standard. In other words, it is not a properly of a programming language. Different Python distributions (or implementations) choose to do different things (compile or interpret or both). However the most common implementations like CPython do both compile and interpret, but in different stages of its execution process.

  • Compilation: When you write Python code and run it, the source code (.py files) is first compiled into an intermediate form called bytecode (.pyc files). This bytecode is a lower-level representation of your code, but it is still not directly machine code. It’s something that the Python Virtual Machine (PVM) can understand and execute.
  • Interpretation: After Python code is compiled into bytecode, it is executed by the Python Virtual Machine (PVM), which is an interpreter. The PVM reads the bytecode and executes it line-by-line at runtime, which is why Python is considered an interpreted language in practice.

Some implementations, like PyPy, use Just-In-Time (JIT) compilation, where Python code is compiled into machine code at runtime for faster execution, blurring the lines between interpretation and compilation.

2. How can you concatenate two lists in Python?

We can concatenate two lists in Python using the +operator or the extend() method.

1. Using the + operator:

This creates a new list by joining two lists together.

Python
a = [1, 2, 3] b = [4, 5, 6] res = a + b print(res)  

Output
[1, 2, 3, 4, 5, 6] 

2. Using the extend() method:

This adds all the elements of the second list to the first list in-place.

Python
a = [1, 2, 3] b = [4, 5, 6] a.extend(b) print(a)  

Output
[1, 2, 3, 4, 5, 6] 

3. Difference between for loop and while loop in Python

  • For loop: Used when we know how many times to repeat, often with lists, tuples, sets, or dictionaries.
  • While loop: Used when we only have an end condition and don’t know exactly how many times it will repeat.
Python
for i in range(5):     print(i)  c = 0 while c < 5:     print(c)     c += 1 

Output
0 1 2 3 4 0 1 2 3 4 

4. How do you floor a number in Python?

To floor a number in Python, you can use the math.floor() function, which returns the largest integer less than or equal to the given number.

  • floor()method in Python returns the floor of x i.e., the largest integer not greater than x. 
  • Also, The method ceil(x) in Pythonreturns a ceiling value of x i.e., the smallest integer greater than or equal to x.
Python
import math  n = 3.7 F_num = math.floor(n)  print(F_num)  

Output
3 

5. What is the difference between / and // in Python?

/ represents precise division (result is a floating point number) whereas // represents floor division (result is an integer). For Example:

Python
print(5//2) print(5/2) 

Output
2 2.5 

6. Is Indentation Required in Python?

Yes, indentation is required in Python. A Python interpreter can be informed that a group of statements belongs to a specific block of code by using Python indentation. Indentations make the code easy to read for developers in all programming languages but in Python, it is very important to indent the code in a specific order.

Indentation-in-python
Python Indentation

7. Can we Pass a function as an argument in Python?

Yes, Several arguments can be passed to a function, including objects, variables (of the same or distinct data types) and functions. Functions can be passed as parameters to other functions because they are objects. Higher-order functions are functions that can take other functions as arguments.

Python
def add(x, y):     return x + y  def apply_func(func, a, b):     return func(a, b)  print(apply_func(add, 3, 5)) 

Output
8 

The add function is passed as an argument to apply_func, which applies it to 3 and 5.

8. What is a dynamically typed language?

  • In a dynamically typed language, the data type of a variable is determined at runtime, not at compile time.
  • No need to declare data types manually; Python automatically detects it based on the assigned value.
  • Examples of dynamically typed languages: Python, JavaScript.
  • Examples of statically typed languages: C, C++, Java.
  • Dynamically typed languages are easier and faster to code.
  • Statically typed languages are usually faster to execute due to type checking at compile time.

Example:

Python
x = 10       # x is an integer x = "Hello"  # Now x is a string 

Here, the type of x changes at runtime based on the assigned value hence it shows dynamic nature of Python.

9. What is pass in Python?

  • The pass statement is a placeholder that does nothing.
  • It is used when a statement is syntactically required but no code needs to run.
  • Commonly used when defining empty functions, classes or loops during development.
Python
def fun():     pass  # Placeholder, no functionality yet  # Call the function fun() 

Output

Here, fun() does nothing, but the code stays syntactically correct.

10. How are arguments passed by value or by reference in Python?

  • Python’s argument-passing model is neither “Pass by Value” nor “Pass by Reference” but it is “Pass by Object Reference”. 
  • Depending on the type of object you pass in the function, the function behaves differently. Immutable objects show “pass by value” whereas mutable objects show “pass by reference”.

You can check the difference between pass-by-value and pass-by-reference in the example below:

Python
def call_by_val(x):     x = x * 2     return x   def call_by_ref(b):     b.append("D")     return b   a = ["E"] num = 6  # Call functions updated_num = call_by_val(num) updated_list = call_by_ref(a)  # Print after function calls print("Updated value after call_by_val:", updated_num) print("Updated list after call_by_ref:", updated_list) 

Output
Updated value after call_by_val: 12 Updated list after call_by_ref: ['E', 'D'] 

11. What is a lambda function?

A lambda function is an anonymous function. This function can have any number of parameters but, can have just one statement.

In the example, we defined a lambda function(upper) to convert a string to its upper case using upper().

Python
s1 = 'GeeksforGeeks'  s2 = lambda func: func.upper() print(s2(s1)) 

Output
GEEKSFORGEEKS 

12. What is List Comprehension? Give an Example.

List comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques.

For example, if we have a list of integers and want to create a new list containing the square of each element, we can easily achieve this using list comprehension.

Python
a = [2,3,4,5] res = [val ** 2 for val in a] print(res) 

Output
[4, 9, 16, 25] 

13. What are *args and **kwargs?

  • *args: The special syntax *args in function definitions is used to pass a variable number of arguments to a function. Python program to illustrate *args for a variable number of arguments:
Python
def fun(*argv):     for arg in argv:         print(arg)  fun('Hello', 'Welcome', 'to', 'GeeksforGeeks') 

Output
Hello Welcome to GeeksforGeeks 
  • **kwargs: The special syntax **kwargs in function definitions is used to pass a variable length argument list. We use the name kwargs with the double star **.
Python
def fun(**kwargs):     for k, val in kwargs.items():         print("%s == %s" % (k, val))   # Driver code fun(s1='Geeks', s2='for', s3='Geeks') 

Output
s1 == Geeks s2 == for s3 == Geeks 

14. What is a break, continue and pass in Python? 

  • Break statementis used to terminate the loop or statement in which it is present. After that, the control will pass to the statements that are present after the break statement, if available.
  • Continue is also a loop control statement just like the break statement. continue statement is opposite to that of the break statement, instead of terminating the loop, it forces to execute the next iteration of the loop.
  • Passmeans performing no operation or in other words, it is a placeholder in the compound statement, where there should be a blank left and nothing has to be written there.

15. What is the difference between a Set and Dictionary?

  • A Python Set is an unordered collection data type that is iterable, mutable and has no duplicate elements. Python’s set class represents the mathematical notion of a set.
  • Syntax: Defined using curly braces {} or the set() function.

my_set = {1, 2, 3}

  • Dictionary in Python is an ordered (since Py 3.7) [unordered (Py 3.6 & prior)] collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized.
  • Syntax: Defined using curly braces {} with key-value pairs.

my_dict = {"a": 1, "b": 2, "c": 3}

16. What are Built-in data types in Python?

The following are the standard or built-in data types in Python:

  • Numeric: The numeric data type in Python represents the data that has a numeric value. A numeric value can be an integer, a floating number, a Boolean, or even a complex number.
  • Sequence Type: The sequence Data Type in Python is the ordered collection of similar or different data types. There are several sequence types in Python:
    • Python String
    • Python List
    • Python Tuple
    • Python range
  • Mapping Types: In Python, hashable data can be mapped to random objects using a mapping object. There is currently only one common mapping type, the dictionary and mapping objects are mutable.
    • Python Dictionary
  • Set Types: In Python, a Set is an unordered collection of data types that is iterable, mutable and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements.

17. What is the difference between a Mutable datatype and an Immutable data type?

  • Mutable data types can be edited i.e., they can change at runtime. Eg – List, Dictionary, etc.
  • Immutable data types can not be edited i.e., they can not change at runtime. Eg – String, Tuple, etc.

18. What is a Variable Scope in Python?

The location where we can find a variable and also access it if required is called the scope of a variable.

  • Python Local variable: Local variables are those that are initialized within a function and are unique to that function. A local variable cannot be accessed outside of the function.
  • Python Global variables: Global variables are the ones that are defined and declared outside any function and are not specified to any function.
  • Module-level scope: It refers to the global objects of the current module accessible in the program.
  • Outermost scope: It refers to any built-in names that the program can call. The name referenced is located last among the objects in this scope.

19. How is a dictionary different from a list?

A list is an ordered collection of items accessed by their index, while a dictionary is an unordered collection of key-value pairs accessed using unique keys. Lists are ideal for sequential data, whereas dictionaries are better for associative data. For example, a list can store [10, 20, 30], whereas a dictionary can store {"a": 10, "b": 20, "c": 30}.

20. What is docstring in Python?

Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes and methods.

  • Declaring Docstrings: The docstrings are declared using ”’triple single quotes”’ or “””triple double quotes””” just below the class, method, or function declaration. All functions should have a docstring.
  • Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or using the help function.

21. How is Exceptional handling done in Python?

There are 3 main keywords i.e. try, except and finally which are used to catch exceptions:

  • try: A block of code that is monitored for errors.
  • except: Executes when an error occurs in the try block.
  • finally: Executes after the try and except blocks, regardless of whether an error occurred. It’s used for cleanup tasks.

Example: Trying to divide a number by zero will cause an exception.

Python
n = 10 try:     res = n / 0  # This will raise a ZeroDivisionError      except ZeroDivisionError:     print("Can't be divided by zero!") 

Output
Can't be divided by zero! 

Explanation: In this example, dividing number by 0 raises a ZeroDivisionError. The try block contains the code that might cause an exception and the except block handles the exception, printing an error message instead of stopping the program.

22. What is the difference between Python Arrays and Lists?

  • Arrays (when talking about the array module in Python) are specifically used to store a collection of numeric elements that are all of the same type. This makes them more efficient for storing large amounts of data and performing numerical computations where the type consistency is maintained.
  • Syntax: Need to import the array module to use arrays.

Example:

Python
from array import array arr = array('i', [1, 2, 3, 4])  # Array of integers 

Output
  • Lists are more flexible than arrays in that they can hold elements of different types (integers, strings, objects, etc.). They come built-in with Python and do not require importing any additional modules.
  • Lists support a variety of operations that can modify the list.

Example:

Python
a = [1, 'hello', 3.14, [1, 2, 3]] 

Output

read more about Difference between List and Array in Python

23. What are Modules and Packages in Python?

A module is a single file that contains Python code (functions, variables, classes) which can be reused in other programs. You can think of it as a code library. For example: math is a built-in module that provides math functions like sqrt(), pi, etc.

Python
import math print(math.sqrt(16))   

Output
4.0 

package is a collection of related modules stored in a directory. It helps in organizing and grouping modules together for easier management. For example: The numpy package contains multiple modules for numerical operations.

To create a package, the directory must contain a special file named __init__.py.

Intermediate Python Interview Questions

24. What is the difference between xrange and range functions?

range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. 

  • In Python 3, there is no xrange, but the range function behaves like xrange.
  • In Python 2
    • range() – This returns a range object, which is an immutable sequence type that generates the numbers on demand. 
    • xrange() – This function returns the generator object that can be used to display numbers only by looping. The only particular range is displayed on demand and hence called lazy evaluation.

25. What is Dictionary Comprehension? Give an Example

Dictionary Comprehension is a syntax construction to ease the creation of a dictionary based on the existing iterable.

Python
keys = ['a','b','c','d','e'] values = [1,2,3,4,5]    # this line shows dict comprehension here   d = { k:v for (k,v) in zip(keys, values)}    # We can use below too # d = dict(zip(keys, values))    print (d) 

Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} 

26. Is Tuple Comprehension possible in Python? If yes, how and if not why?

Tuple comprehensions are not directly supported, Python's existing features like generator expressions and the tuple() function provide flexible alternatives for creating tuples from iterable data.

(i for i in (1, 2, 3))

Tuple comprehension is not possible in Python because it will end up in a generator, not a tuple comprehension.

27. Differentiate between List and Tuple?

Let’s analyze the differences between List and Tuple:

List

  • Lists are Mutable datatype.
  • Lists consume more memory
  • The list is better for performing operations, such as insertion and deletion.
  • The implication of iterations is Time-consuming

Tuple

  • Tuples are Immutable datatype.
  • Tuple consumes less memory as compared to the list
  • A Tuple data type is appropriate for accessing the elements
  • The implication of iterations is comparatively Faster

28. What is the difference between a shallow copy and a deep copy?

Below is the tabular Difference between the Shallow Copy and Deep Copy:

Shallow CopyDeep Copy
Shallow Copy stores the references of objects to the original memory address.   Deep copy stores copies of the object’s value.
Shallow Copy reflects changes made to the new/copied object in the original object.Deep copy doesn’t reflect changes made to the new/copied object in the original object.
Shallow Copy stores the copy of the original object and points the references to the objects.Deep copy stores the copy of the original object and recursively copies the objects as well.
A shallow copy is faster.Deep copy is comparatively slower.

29. Which sorting technique is used by sort() and sorted() functions of python?

Python uses the Tim Sort algorithm for sorting. It’s a stable sorting whose worst case is O(N log N). It’s a hybrid sorting algorithm, derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data.

30. What are Decorators?

Decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality.

Decorators are often used in scenarios such as logging, authentication and memorization, allowing us to add additional functionality to existing functions or methods in a clean, reusable way.

31. How do you debug a Python program?

1. Using pdb (Python Debugger):

pdb is a built-in module that allows you to set breakpoints and step through the code line by line. You can start the debugger by adding import pdb; pdb.set_trace() in your code where you want to begin debugging.

Python
import pdb x = 5 pdb.set_trace()  # Debugger starts here print(x) 

Output

> /home/repl/02c07243-5df9-4fb0-a2cd-54fe6d597c80/main.py(4)<module>()
-> print(x)
(Pdb)

2. Using logging Module:

For more advanced debugging, the logging module provides a flexible way to log messages with different severity levels (INFO, DEBUG, WARNING, ERROR, CRITICAL).

Python
import logging logging.basicConfig(level=logging.DEBUG) logging.debug("This is a debug message") 

Output

DEBUG:root:This is a debug message

32. What are Iterators in Python?

In Python, iterators are used to iterate a group of elements, containers like a list. Iterators are collections of items and they can be a list, tuples, or a dictionary. Python iterator implements __itr__ and the next() method to iterate the stored elements. We generally use loops to iterate over the collections (list, tuple) in Python.

33. What are Generators in Python?

In Python, the generator is a way that specifies how to implement iterators. It is a normal function except that it yields expression in the function. It does not implement __itr__ and __next__ method and reduces other overheads as well.

If a function contains at least a yield statement, it becomes a generator. The yield keyword pauses the current execution by saving its states and then resumes from the same when required.

34. Does Python supports multiple Inheritance?

When a class is derived from more than one base class it is called multiple Inheritance. The derived class inherits all the features of the base case.

multipleinh
Multiple Inheritance

Python does support multiple inheritances, unlike Java.

35. What is Polymorphism in Python?

Polymorphism means the ability to take multiple forms. Polymorphism allows different classes to be treated as if they are instances of the same class through a common interface. This means that a method in a parent class can be overridden by a method with the same name in a child class, but the child class can provide its own specific implementation. This allows the same method to operate differently depending on the object that invokes it. Polymorphism is about overriding, not overloading; it enables methods to operate on objects of different classes, which can have their own attributes and methods, providing flexibility and reusability in the code.

36. Define encapsulation in Python?

Encapsulation is the process of hiding the internal state of an object and requiring all interactions to be performed through an object’s methods. This approach:

  • Provides better control over data.
  • Prevents accidental modification of data.
  • Promotes modular programming.

Python achieves encapsulation through public, protected and private attributes.

Encapsulation-in-Python
Encapsulation in Python

37. How do you do data abstraction in Python?

Data Abstraction is providing only the required details and hides the implementation from the world. The focus is on exposing only the essential features and hiding the complex implementation behind an interface. It can be achieved in Python by using interfaces and abstract classes.

38. How is memory management done in Python?

Python uses its private heap space to manage the memory. Basically, all the objects and data structures are stored in the private heap space. Even the programmer can not access this private space as the interpreter takes care of this space. Python also has an inbuilt garbage collector, which recycles all the unused memory and frees the memory and makes it available to the heap space.

39. How to delete a file using Python?

We can delete a file using Python by following approaches:

  1. Python Delete File using os. remove
  2. Delete file in Python using the send2trash module
  3. Python Delete File using os.rmdir

40. What is slicing in Python?

Python Slicing is a string operation for extracting a part of the string, or some part of a list. With this operator, one can specify where to start the slicing, where to end and specify the step. List slicing returns a new list from the existing list.

Syntax:

substring = s[start : end : step]

41. What is a namespace in Python?

A namespace in Python refers to a container where names (variables, functions, objects) are mapped to objects. In simple terms, a namespace is a space where names are defined and stored and it helps avoid naming conflicts by ensuring that names are unique within a given scope.

types_namespace-1
Types of namespaces

Types of Namespaces:

  1. Built-in Namespace: Contains all the built-in functions and exceptions, like print(), int(), etc. These are available in every Python program.
  2. Global Namespace: Contains names from all the objects, functions and variables in the program at the top level.
  3. Local Namespace: Refers to names inside a function or method. Each function call creates a new local namespace.
Python-Interview-Questions
Python Interview

Advanced Python Interview Questions & Answers 

42. What is PIP?

PIP is an acronym for Python Installer Package which provides a seamless interface to install various Python modules. It is a command-line tool that can search for packages over the internet and install them without any user interaction.

43. What is a zip function?

Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, converts it into an iterator and aggregates the elements based on iterables passed. It returns an iterator of tuples.

Syntax:
zip(*iterables) 

44. What are Pickling and Unpickling?

  • Pickling: The pickle module converts any Python object into a byte stream (not a string representation). This byte stream can then be stored in a file, sent over a network, or saved for later use. The function used for pickling is pickle.dump().
  • Unpickling: The process of retrieving the original Python object from the byte stream (saved during pickling) is called unpickling. The function used for unpickling is pickle.load().

45. What is the difference between @classmethod, @staticmethod and instance methods in Python?

1. Instance Method operates on an instance of the class and has access to instance attributes and takes self as the first parameter. Example:

def method(self):

2. Class Method directly operates on the class itself and not on instance, it takes cls as the first parameter and defined with @classmethod.

Example: @classmethod def method(cls):

3. Static Method does not operate on an instance or the class and takes no self or cls as an argument and is defined with @staticmethod.

Example: @staticmethod def method(): align it and dont bolod anything and not bullet points

46. What is __init__() in Python and how does self play a role in it?

  • __init__() is Python's equivalent of constructors in OOP, called automatically when a new object is created. It initializes the object's attributes with values but doesn’t handle memory allocation.
  • Memory allocation is handled by the __new__() method, which is called before __init__().
  • The self parameter in __init__() refers to the instance of the class, allowing access to its attributes and methods.
  • self must be the first parameter in all instance methods, including __init__()
Python
class MyClass:     def __init__(self, value):         self.value = value  # Initialize object attribute      def display(self):         print(f"Value: {self.value}")  obj = MyClass(10) obj.display()  

Output
Value: 10 

47. Write a code to display the current time?

Python
import time  currenttime= time.localtime(time.time()) print ("Current time is", currenttime) 

Output
Current time is time.struct_time(tm_year=2025, tm_mon=6, tm_mday=10, tm_hour=11, tm_min=56, tm_sec=57, tm_wday=1, tm_yday=161, tm_isdst=0) 

48. What are Access Specifiers in Python?

Python uses the ‘_’ symbol to determine the access control for a specific data member or a member function of a class. A Class in Python has three types of Python access modifiers:

  • Public Access Modifier: The members of a class that are declared public are easily accessible from any part of the program. All data members and member functions of a class are public by default. 
  • Protected Access Modifier: The members of a class that are declared protected are only accessible to a class derived from it. All data members of a class are declared protected by adding a single underscore '_' symbol before the data members of that class. 
  • Private Access Modifier: The members of a class that are declared private are accessible within the class only, the private access modifier is the most secure access modifier. Data members of a class are declared private by adding a double underscore ‘__’ symbol before the data member of that class. 

49. What are unit tests in Python?

Unit Testing is the first level of software testing where the smallest testable parts of the software are tested. This is used to validate that each unit of the software performs as designed. The unit test framework is Python’s xUnit style framework. The White Box Testing method is used for Unit testing.

50. Python Global Interpreter Lock (GIL)?

Python Global Interpreter Lock (GIL) is a type of process lock that is used by Python whenever it deals with processes. Generally, Python only uses only one thread to execute the set of written statements. The performance of the single-threaded process and the multi-threaded process will be the same in Python and this is because of GIL in Python. We can not achieve multithreading in Python because we have a global interpreter lock that restricts the threads and works as a single thread.

51. What are Function Annotations in Python?

  • Function Annotation is a feature that allows you to add metadata to function parameters and return values. This way you can specify the input type of the function parameters and the return type of the value the function returns.
  • Function annotations are arbitrary Python expressions that are associated with various parts of functions. These expressions are evaluated at compile time and have no life in Python’s runtime environment. Python does not attach any meaning to these annotations. They take life when interpreted by third-party libraries, for example, mypy.

52. What are Exception Groups in Python?

The latest feature of Python 3.11, Exception Groups. The ExceptionGroup can be handled using a new except* syntax. The * symbol indicates that multiple exceptions can be handled by each except* clause.

ExceptionGroup is a collection/group of different kinds of Exception. Without creating Multiple Exceptions we can group together different Exceptions which we can later fetch one by one whenever necessary, the order in which the Exceptions are stored in the Exception Group doesn’t matter while calling them.

try:
raise ExceptionGroup('Example ExceptionGroup', (
TypeError('Example TypeError'),
ValueError('Example ValueError'),
KeyError('Example KeyError'),
AttributeError('Example AttributeError')
))
except* TypeError:
...
except* ValueError as e:
...
except* (KeyError, AttributeError) as e:
...

53. What is Python Switch Statement?

From version 3.10 upward, Python has implemented a switch case feature called “structural pattern matching”. You can implement this feature with the match and case keywords. Note that the underscore symbol is what you use to define a default case for the switch statement in Python.

Note: Before Python 3.10 Python doesn't support match Statements.

Python
match term:    case pattern-1:    action-1    case pattern-2:    action-2    case pattern-3:    action-3    case _:    action-default 

54. What is Walrus Operator?

  • Walrus Operator allows you to assign a value to a variable within an expression. This can be useful when you need to use a value multiple times in a loop, but don't want to repeat the calculation.
  • Walrus Operator is represented by the `:=` syntax and can be used in a variety of contexts including while loops and if statements.

Note: Python versions before 3.8 doesn't support Walrus Operator.

Python
numbers = [1, 2, 3, 4, 5]  while (n := len(numbers)) > 0:     print(numbers.pop()) 

Output
5 4 3 2 1 

Next Article
Python Interview Questions and Answers

K

kartik
Improve
Article Tags :
  • Python
  • interview-preparation
  • Interview-Questions
Practice Tags :
  • python

Similar Reads

    Python Tutorial | Learn Python Programming Language
    Python Tutorial – Python is one of the most popular programming languages. It’s simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
    10 min read

    Python Fundamentals

    Python Introduction
    Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPython’s simple and readable syntax makes it beginner-frien
    3 min read
    Input and Output in Python
    Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
    8 min read
    Python Variables
    In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
    6 min read
    Python Operators
    In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /,
    6 min read
    Python Keywords
    Keywords in Python are reserved words that have special meanings and serve specific purposes in the language syntax. Python keywords cannot be used as the names of variables, functions, and classes or any other identifier. Getting List of all Python keywordsWe can also get all the keyword names usin
    2 min read
    Python Data Types
    Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
    9 min read
    Conditional Statements in Python
    Conditional statements in Python are used to execute certain blocks of code based on specific conditions. These statements help control the flow of a program, making it behave differently in different situations.If Conditional Statement in PythonIf statement is the simplest form of a conditional sta
    6 min read
    Loops in Python - For, While and Nested Loops
    Loops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions). In this article, we will look at Python loops and understand their working with the help of examples. While Loop in PythonIn Python, a while loop is us
    9 min read
    Python Functions
    Python Functions is a block of statements that does a specific task. The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over an
    9 min read
    Recursion in Python
    Recursion involves a function calling itself directly or indirectly to solve a problem by breaking it down into simpler and more manageable parts. In Python, recursion is widely used for tasks that can be divided into identical subtasks.In Python, a recursive function is defined like any other funct
    6 min read
    Python Lambda Functions
    Python Lambda Functions are anonymous functions means that the function is without a name. As we already know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python. In the example, we defined a lambda function(u
    6 min read

    Python Data Structures

    Python String
    A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.Pythons = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # update print(s1) # printOut
    6 min read
    Python Lists
    In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
    6 min read
    Python Tuples
    A tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogene
    6 min read
    Dictionaries in Python
    Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier to
    5 min read
    Python Sets
    Python set is an unordered collection of multiple items having different datatypes. In Python, sets are mutable, unindexed and do not contain duplicates. The order of elements in a set is not preserved and can change.Creating a Set in PythonIn Python, the most basic and efficient method for creating
    10 min read
    Python Arrays
    Lists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences:Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
    9 min read
    List Comprehension in Python
    List comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques.For example,
    4 min read

    Advanced Python

    Python OOPs Concepts
    Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
    11 min read
    Python Exception Handling
    Python Exception Handling handles errors that occur during the execution of a program. Exception handling allows to respond to the error, instead of crashing the running program. It enables you to catch and manage errors, making your code more robust and user-friendly. Let's look at an example:Handl
    7 min read
    File Handling in Python
    File handling refers to the process of performing operations on a file such as creating, opening, reading, writing and closing it, through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely a
    7 min read
    Python Database Tutorial
    Python being a high-level language provides support for various databases. We can connect and run queries for a particular database using Python and without writing raw queries in the terminal or shell of that particular database, we just need to have that database installed in our system. In this t
    4 min read
    Python MongoDB Tutorial
    MongoDB is a popular NoSQL database designed to store and manage data flexibly and at scale. Unlike traditional relational databases that use tables and rows, MongoDB stores data as JSON-like documents using a format called BSON (Binary JSON). This document-oriented model makes it easy to handle com
    2 min read
    Python MySQL
    Python MySQL Connector is a Python driver that helps to integrate Python and MySQL. This Python MySQL library allows the conversion between Python and MySQL data types. MySQL Connector API is implemented using pure Python and does not require any third-party library.  This Python MySQL tutorial will
    9 min read
    Python Packages
    Python packages are a way to organize and structure code by grouping related modules into directories. A package is essentially a folder that contains an __init__.py file and one or more Python files (modules). This organization helps manage and reuse code effectively, especially in larger projects.
    12 min read
    Python Modules
    Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work.In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we c
    7 min read
    Python DSA Libraries
    Data Structures and Algorithms (DSA) serve as the backbone for efficient problem-solving and software development. Python, known for its simplicity and versatility, offers a plethora of libraries and packages that facilitate the implementation of various DSA concepts. In this article, we'll delve in
    15 min read
    List of Python GUI Library and Packages
    Graphical User Interfaces (GUIs) play a pivotal role in enhancing user interaction and experience. Python, known for its simplicity and versatility, has evolved into a prominent choice for building GUI applications. With the advent of Python 3, developers have been equipped with lots of tools and li
    11 min read

    Data Science with Python

    NumPy Tutorial - Python Library
    NumPy (short for Numerical Python ) is one of the most fundamental libraries in Python for scientific computing. It provides support for large, multi-dimensional arrays and matrices along with a collection of mathematical functions to operate on arrays.At its core it introduces the ndarray (n-dimens
    3 min read
    Pandas Tutorial
    Pandas is an open-source software library designed for data manipulation and analysis. It provides data structures like series and DataFrames to easily clean, transform and analyze large datasets and integrates with other Python libraries, such as NumPy and Matplotlib. It offers functions for data t
    6 min read
    Matplotlib Tutorial
    Matplotlib is an open-source visualization library for the Python programming language, widely used for creating static, animated and interactive plots. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, Qt, GTK and wxPython. It
    5 min read
    Python Seaborn Tutorial
    Seaborn is a library mostly used for statistical plotting in Python. It is built on top of Matplotlib and provides beautiful default styles and color palettes to make statistical plots more attractive.In this tutorial, we will learn about Python Seaborn from basics to advance using a huge dataset of
    15+ min read
    StatsModel Library- Tutorial
    Statsmodels is a useful Python library for doing statistics and hypothesis testing. It provides tools for fitting various statistical models, performing tests and analyzing data. It is especially used for tasks in data science ,economics and other fields where understanding data is important. It is
    4 min read
    Learning Model Building in Scikit-learn
    Building machine learning models from scratch can be complex and time-consuming. Scikit-learn which is an open-source Python library which helps in making machine learning more accessible. It provides a straightforward, consistent interface for a variety of tasks like classification, regression, clu
    8 min read
    TensorFlow Tutorial
    TensorFlow is an open-source machine-learning framework developed by Google. It is written in Python, making it accessible and easy to understand. It is designed to build and train machine learning (ML) and deep learning models. It is highly scalable for both research and production.It supports CPUs
    2 min read
    PyTorch Tutorial
    PyTorch is an open-source deep learning framework designed to simplify the process of building neural networks and machine learning models. With its dynamic computation graph, PyTorch allows developers to modify the network’s behavior in real-time, making it an excellent choice for both beginners an
    7 min read

    Web Development with Python

    Flask Tutorial
    Flask is a lightweight and powerful web framework for Python. It’s often called a "micro-framework" because it provides the essentials for web development without unnecessary complexity. Unlike Django, which comes with built-in features like authentication and an admin panel, Flask keeps things mini
    8 min read
    Django Tutorial | Learn Django Framework
    Django is a Python framework that simplifies web development by handling complex tasks for you. It follows the "Don't Repeat Yourself" (DRY) principle, promoting reusable components and making development faster. With built-in features like user authentication, database connections, and CRUD operati
    10 min read
    Django ORM - Inserting, Updating & Deleting Data
    Django's Object-Relational Mapping (ORM) is one of the key features that simplifies interaction with the database. It allows developers to define their database schema in Python classes and manage data without writing raw SQL queries. The Django ORM bridges the gap between Python objects and databas
    4 min read
    Templating With Jinja2 in Flask
    Flask is a lightweight WSGI framework that is built on Python programming. WSGI simply means Web Server Gateway Interface. Flask is widely used as a backend to develop a fully-fledged Website. And to make a sure website, templating is very important. Flask is supported by inbuilt template support na
    6 min read
    Django Templates
    Templates are the third and most important part of Django's MVT Structure. A Django template is basically an HTML file that can also include CSS and JavaScript. The Django framework uses these templates to dynamically generate web pages that users interact with. Since Django primarily handles the ba
    7 min read
    Python | Build a REST API using Flask
    Prerequisite: Introduction to Rest API REST stands for REpresentational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. In this article, we will build a REST API in Python using the Fla
    3 min read
    How to Create a basic API using Django Rest Framework ?
    Django REST Framework (DRF) is a powerful extension of Django that helps you build APIs quickly and easily. It simplifies exposing your Django models as RESTfulAPIs, which can be consumed by frontend apps, mobile clients or other services.Before creating an API, there are three main steps to underst
    4 min read

    Python Practice

    Python Quiz
    These Python quiz questions are designed to help you become more familiar with Python and test your knowledge across various topics. From Python basics to advanced concepts, these topic-specific quizzes offer a comprehensive way to practice and assess your understanding of Python concepts. These Pyt
    3 min read
    Python Coding Practice Problems
    This collection of Python coding practice problems is designed to help you improve your overall programming skills in Python.The links below lead to different topic pages, each containing coding problems, and this page also includes links to quizzes. You need to log in first to write your code. Your
    1 min read
    Python Interview Questions and Answers
    Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences