Python Interview Questions: Complete Guide for Success

May 22, 2026
75 min read

AI Insights

Powered by GPT-4o-mini

Verified Context: python-interview-questions-complete-guide-for-success
Quick Answer

A complete original Python interview guide covering basics, data structures, functions, recursion, OOP, files, exceptions, iterators, generators, decorators, modules, output tracing, and coding practice.

Quick Summary

Prepare for your Python interview with our complete guide covering key concepts, practice problems, and expert tips for success.

Complete Python Interview Questions and Practice Problems

This guide is a complete interview revision file for the Python Foundations series.

It covers the ideas from the earlier lessons:

  • Python basics, variables, input, output, and type conversion
  • operators, control flow, loops, and pattern thinking
  • strings, lists, tuples, sets, and dictionaries
  • functions, recursion, time complexity, and memory behavior
  • OOP, encapsulation, inheritance, polymorphism, and abstraction
  • file handling, JSON, pickle, exceptions, iterators, generators, namespaces, closures, decorators, modules, imports, and packages

All questions, explanations, examples, and practice problems here are written freshly. Use this as a learning and interview-preparation guide, not as a memorization sheet.

How to Use This Interview Guide

Use three passes:

  1. Read the question and answer it out loud before looking.
  2. Compare your answer with the explanation.
  3. Run or mentally trace the code where shown.

In interviews, the best answers are usually:

  • clear
  • short at first
  • backed by one example
  • honest about edge cases
  • connected to practical use

Interview Answer Formula

For theory questions, use this structure:

  1. Define the concept.
  2. Mention why it matters.
  3. Give a small example.
  4. Mention one common mistake or edge case.

Example:

text
A list is an ordered, mutable collection in Python.
It is useful when we need to store items and update them later.
For example, scores = [10, 20, 30].
A common mistake is copying a nested list with copy(), because nested objects are still shared.

Part 1: Core Python Interview Questions

1. What is Python?

Python is a high-level, general-purpose programming language known for readable syntax and a large standard library.

It is used for web development, automation, data analysis, machine learning, scripting, testing, backend services, and many other tasks.

2. Why is Python called high-level?

Python hides many low-level details such as manual memory management and direct CPU instructions.

You write code closer to human-readable logic:

python
name = "Asha"
print(f"Welcome, {name}")

Explanation

  • The variable name is assigned the string value "Asha".
  • The print function outputs a formatted string that includes the value of name.
  • The f-string syntax (prefixing the string with f) allows for easy insertion of variable values directly within the string.
  • The output of this code will be: "Welcome, Asha".

3. Is Python interpreted or compiled?

Python is commonly called interpreted because users usually run source code directly.

In CPython, Python source code is first compiled internally into bytecode, and then that bytecode is executed by the Python virtual machine.

4. What is CPython?

CPython is the reference implementation of Python, written mainly in C.

When most people say "Python", they usually mean CPython unless they mention another implementation such as PyPy or Jython.

5. What is dynamic typing?

Dynamic typing means variable names do not have fixed declared types.

python
value = 10
value = "ten"

print(value)

Explanation

  • The variable value is initially assigned an integer of 10.
  • The variable value is then reassigned to the string "ten", overriding the previous integer value.
  • The print function outputs the current value of the variable, which will display "ten".
  • This snippet illustrates how Python allows dynamic typing, enabling variables to change types during execution.

The name value first points to an integer object and later points to a string object.

6. What is strong typing?

Strong typing means Python does not silently mix incompatible types in unsafe ways.

python
age = 25

print("Age: " + str(age))

Explanation

  • The variable age is assigned the integer value of 25.
  • The print function is used to output a string that includes the age.
  • The integer age is converted to a string using str(age) to ensure proper concatenation.
  • The final output will display "Age: 25" in the console.

Without str(age), string concatenation with an integer would fail.

7. What is PEP 8?

PEP 8 is Python's style guide.

It gives naming, formatting, indentation, spacing, and readability conventions. It is not the language grammar, but it helps teams write consistent code.

8. Why is indentation important in Python?

Indentation defines code blocks in Python.

python
score = 85

if score >= 50:
    print("pass")
else:
    print("try again")

Explanation

  • The variable score is initialized with a value of 85.
  • An if statement checks if the score is greater than or equal to 50.
  • If the condition is true, it prints "pass"; otherwise, it prints "try again".
  • This code effectively categorizes the score into a pass/fail outcome based on a threshold.

Wrong indentation can change meaning or raise an error.

9. What are keywords?

Keywords are reserved words with special meaning.

Examples include if, else, for, while, def, class, try, except, return, yield, import, global, and nonlocal.

10. What are identifiers?

Identifiers are names created by programmers for variables, functions, classes, modules, and other objects.

Good identifiers are descriptive:

python
completed_lessons = 12

Explanation

  • The variable completed_lessons is assigned the integer value of 12.
  • This could represent the total number of lessons a user has finished in an educational application.
  • The variable can be used later in the code for calculations, condition checks, or displaying progress.
  • It serves as a simple way to store and manipulate user progress data.

11. What does print() do?

print() writes text representation of objects to standard output.

python
print("Python", "Interview", sep=" - ", end="!\n")

Explanation

  • The print function is used to display text output to the console.
  • The sep parameter specifies the string inserted between multiple arguments, here it is set to " - ".
  • The end parameter defines what is printed at the end of the output; in this case, it adds an exclamation mark followed by a newline.
  • The output of this code will be: Python - Interview!

Output:

text
Python - Interview!

12. What does input() return?

input() always returns a string.

python
raw_age = input("Age: ")
age = int(raw_age)

Explanation

  • The input() function prompts the user to enter their age as a string.
  • The entered value is stored in the variable raw_age.
  • The int() function converts the string value of raw_age into an integer and assigns it to the variable age.
  • This conversion allows for numerical operations to be performed on the age value later in the program.

Convert it when you need a number.

13. What is type conversion?

Type conversion changes a value from one type to another.

python
price = "199"
quantity = 3

print(int(price) * quantity)

Explanation

  • The variable price is initialized as a string containing the value "199".
  • The variable quantity is set to an integer value of 3.
  • The int(price) function converts the string price to an integer for mathematical operations.
  • The print function outputs the result of multiplying the integer value of price by quantity, which is 597.

14. What is implicit type conversion?

Implicit conversion happens when Python safely converts one type during an expression.

python
result = 10 + 2.5

print(result)

Explanation

  • The variable result is assigned the sum of an integer (10) and a float (2.5).
  • Python automatically handles the addition of different numeric types, resulting in a float.
  • The print function outputs the value of result to the console, which will be 12.5.
  • This snippet illustrates how Python can perform arithmetic operations seamlessly.

Output:

text
12.5

15. What is explicit type conversion?

Explicit conversion is done manually with functions such as int(), float(), str(), list(), tuple(), set(), and dict().

16. What does a Python variable store?

A Python variable stores a reference to an object, not the object directly.

python
first = [1, 2]
second = first

second.append(3)

print(first)

Explanation

  • The variable first is initialized as a list containing two integers: 1 and 2.
  • The variable second is assigned to reference the same list object as first, not a copy.
  • When 3 is appended to second, it modifies the original list that both first and second reference.
  • The print(first) statement outputs the modified list, which now includes the appended value, resulting in [1, 2, 3].
  • This demonstrates how mutable objects like lists in Python can be affected by changes through multiple references.

Output:

text
[1, 2, 3]

Both names point to the same list.

17. What is object identity?

Object identity is the unique identity of an object during its lifetime.

Use id() to inspect it:

python
items = ["python"]

print(id(items))

Explanation

  • The code initializes a list named items containing a single string element "python".
  • The id() function is called with items as an argument, which returns the unique memory address of the list object.
  • The print() function outputs this memory address to the console, allowing you to see where the list is stored in memory.
  • This can be useful for understanding object identity and memory management in Python.

18. What is the difference between == and is?

== compares values.

is compares object identity.

python
a = [1, 2]
b = [1, 2]
c = a

print(a == b)
print(a is b)
print(a is c)

Explanation

  • The code initializes two lists, a and b, with identical contents, and assigns c to reference the same list as a.
  • The expression a == b checks for value equality, returning True since both lists contain the same elements.
  • The expression a is b checks for identity, returning False because a and b are two distinct objects in memory.
  • The expression a is c checks for identity, returning True since c references the same object as a.

Output:

text
True
False
True

19. What are mutable objects?

Mutable objects can be changed after creation.

Examples include lists, dictionaries, and sets.

20. What are immutable objects?

Immutable objects cannot be changed after creation.

Examples include integers, floats, strings, tuples, booleans, and frozensets.

21. Why are strings immutable?

When you "modify" a string, Python creates a new string.

python
title = "python"
updated = title.upper()

print(title)
print(updated)

Explanation

  • The variable title is initialized with the string "python".
  • The upper() method is called on title, converting it to uppercase and storing the result in the variable updated.
  • The original string title is printed, displaying "python".
  • The uppercase version stored in updated is printed, displaying "PYTHON".

Output:

text
python
PYTHON

22. What is truthy and falsy?

Python treats some values as false in conditions.

Falsy examples:

  • False
  • None
  • 0
  • 0.0
  • ""
  • []
  • {}
  • set()

Non-empty containers and non-zero numbers are usually truthy.

23. What is None?

None represents absence of a value.

It is not the same as 0, False, or an empty string.

python
result = None

if result is None:
    print("No result yet")

Explanation

  • Initializes a variable result with a value of None.
  • Uses an if statement to check if result is still None.
  • If the condition is true, it prints "No result yet" to the console.
  • This code can be useful for debugging or handling cases where a result is expected but not yet available.

24. What is the difference between type() and isinstance()?

type() gives the exact class of an object.

isinstance() checks whether an object belongs to a class or subclass.

python
print(type(True))
print(isinstance(True, int))

Explanation

  • The print(type(True)) statement outputs the type of the Boolean value True, which is <class 'bool'>.
  • The print(isinstance(True, int)) statement checks if True is an instance of the int class, returning True since in Python, True is treated as 1.
  • This code demonstrates the dual nature of Boolean values in Python, where they are subclasses of integers.
  • It highlights how Boolean values can be used interchangeably with integers in certain contexts, such as arithmetic operations.

Output:

text
<class 'bool'>
True

25. What is floor division?

Floor division uses // and returns the floor of the division result.

python
print(7 // 2)
print(-7 // 2)

Explanation

  • The // operator performs floor division, which returns the largest integer less than or equal to the division result.
  • The first line print(7 // 2) calculates the floor division of 7 by 2, resulting in 3.
  • The second line print(-7 // 2) calculates the floor division of -7 by 2, resulting in -4, demonstrating how floor division rounds down towards negative infinity.
  • This behavior is important for understanding how Python handles division with negative numbers compared to other programming languages.

Output:

text
3
-4

26. What is the modulo operator?

% returns the remainder after division.

python
print(17 % 5)

Explanation

  • The print function outputs the result of the expression inside it to the console.
  • The expression 17 % 5 uses the modulus operator %, which returns the remainder of the division of 17 by 5.
  • In this case, 17 divided by 5 equals 3 with a remainder of 2, so the output will be 2.
  • This operation is useful for determining if a number is even or odd, or for cyclic calculations.

Output:

text
2

27. What is operator precedence?

Operator precedence decides which part of an expression is evaluated first.

python
print(2 + 3 * 4)
print((2 + 3) * 4)

Explanation

  • The first print statement calculates 2 + 3 * 4, where multiplication has higher precedence than addition, resulting in 2 + 12, which equals 14.
  • The second print statement calculates (2 + 3) * 4, where the parentheses force the addition to be performed first, resulting in 5 * 4, which equals 20.
  • This snippet demonstrates how operator precedence and parentheses can affect the outcome of arithmetic operations in Python.
  • It highlights the importance of understanding the order of operations to avoid unexpected results in calculations.

Output:

text
14
20

28. What is short-circuit evaluation?

Python may stop evaluating a logical expression once the result is already known.

python
name = ""

if name and name[0] == "A":
    print("Starts with A")
else:
    print("No usable name")

Explanation

  • Initializes an empty string variable name.
  • Uses a conditional statement to check if name is non-empty and if its first character is 'A'.
  • If both conditions are true, it prints "Starts with A".
  • If either condition is false, it prints "No usable name".

Because name is empty, name[0] is not evaluated.

29. What is a conditional expression?

It is Python's compact if-else expression.

python
score = 72
status = "pass" if score >= 50 else "fail"

print(status)

Explanation

  • A variable score is initialized with a value of 72.
  • A conditional expression assigns "pass" to the variable status if score is 50 or higher; otherwise, it assigns "fail".
  • The print function outputs the value of status, which will be "pass" in this case.

30. What is the difference between for and while loops?

Use for when you are iterating over a known iterable.

Use while when the loop depends on a condition that may change.

31. What are break, continue, and pass?

break exits the loop.

continue skips to the next iteration.

pass does nothing and is used as a placeholder.

32. What does range() produce?

range() produces an immutable sequence-like object that generates numbers lazily.

python
for number in range(2, 7, 2):
    print(number)

Explanation

  • The range(2, 7, 2) function generates a sequence of numbers starting from 2 up to, but not including, 7, with a step of 2.
  • The loop iterates through the generated numbers, which are 2, 4, and 6.
  • The print(number) statement outputs each number in the sequence to the console.
  • This code effectively showcases how to work with ranges and control the increment in a loop.

Output:

text
2
4
6

33. What is loop else?

A loop else block runs when the loop finishes normally, without break.

python
target = 7
numbers = [2, 4, 6]

for number in numbers:
    if number == target:
        print("found")
        break
else:
    print("not found")

Explanation

  • The variable target is set to 7, which is the number the code will search for in the list numbers.
  • The list numbers contains three integers: 2, 4, and 6.
  • A for loop iterates through each number in the numbers list.
  • If a number matches the target, it prints "found" and exits the loop using break.
  • If the loop completes without finding the target, the else block executes, printing "not found".

34. What are membership operators?

in and not in test membership.

python
tags = ["python", "oop", "files"]

print("oop" in tags)

Explanation

  • A list named tags is created containing three string elements: "python", "oop", and "files".
  • The print function is used to output the result of the expression "oop" in tags.
  • The expression evaluates to True if "oop" is found in the tags list, and False otherwise.
  • This demonstrates the use of the in keyword for membership testing in Python lists.

35. What are bitwise operators?

Bitwise operators work on integer bits.

Common examples are &, |, ^, ~, <<, and >>.

They are useful in flags, masks, permissions, and low-level tasks.

36. How does string indexing work?

Strings are indexed from 0.

Negative indexes count from the end.

python
word = "python"

print(word[0])
print(word[-1])

Explanation

  • The variable word is assigned the string value "python".
  • print(word[0]) outputs the first character of the string, which is 'p'.
  • print(word[-1]) outputs the last character of the string, which is 'n'.
  • This code demonstrates how to use positive and negative indexing to access string elements.

Output:

text
p
n

37. How does slicing work?

Slicing uses start:stop:step.

python
word = "interview"

print(word[0:5])
print(word[::-1])

Explanation

  • The variable word is initialized with the string "interview".
  • The first print statement outputs the first five characters of the string, resulting in "inter".
  • The second print statement uses slicing with a step of -1 to reverse the string, producing "weivretni".

Output:

text
inter
weivretni

38. Why should you prefer join() for combining many strings?

Repeated string concatenation can create many intermediate strings.

join() is clearer and usually more efficient for many pieces.

python
parts = ["python", "is", "clear"]

sentence = " ".join(parts)
print(sentence)

Explanation

  • A list named parts is created containing three string elements: "python", "is", and "clear".
  • The join() method is used on a space character to concatenate the elements of the list into a single string, with spaces in between.
  • The resulting string is stored in the variable sentence.
  • Finally, the print() function outputs the concatenated sentence to the console.

39. What is the difference between find() and index() on strings?

find() returns -1 if the substring is missing.

index() raises ValueError if the substring is missing.

40. What do split() and strip() do?

strip() removes surrounding whitespace or selected characters.

split() breaks a string into a list.

python
line = "  python,oop,files  "

print(line.strip().split(","))

Explanation

  • The line variable contains a string with leading and trailing spaces and comma-separated values.
  • The strip() method removes any whitespace from the beginning and end of the string.
  • The split(",") method then divides the cleaned string into a list using the comma as a delimiter.
  • The final output is a list of strings: ['python', 'oop', 'files'], with no extra spaces.

41. What is a list?

A list is an ordered, mutable collection.

python
scores = [90, 75, 88]
scores.append(92)

print(scores)

Explanation

  • A list named scores is initialized with three integer values representing scores.
  • The append method is used to add a new score, 92, to the end of the scores list.
  • The print function outputs the updated list, which now contains four scores: [90, 75, 88, 92].

42. What is the difference between append() and extend()?

append() adds one object as a single item.

extend() adds each item from an iterable.

python
items = [1, 2]
items.append([3, 4])
print(items)

items = [1, 2]
items.extend([3, 4])
print(items)

Explanation

  • The append method adds its argument as a single element to the end of the list, resulting in a nested list when a list is appended.
  • In the first case, items.append([3, 4]) results in items being [1, 2, [3, 4]].
  • The extend method, on the other hand, iterates over its argument and adds each element to the list, effectively flattening the input.
  • In the second case, items.extend([3, 4]) results in items being [1, 2, 3, 4].
  • This distinction is crucial when manipulating lists in Python, as it affects the structure of the resulting list.

43. What is list aliasing?

Aliasing happens when two names refer to the same list.

python
primary = ["draft"]
alias = primary

alias.append("review")

print(primary)

Explanation

  • The variable primary is initialized as a list containing a single string element "draft".
  • The variable alias is assigned to reference the same list object as primary, meaning both variables point to the same memory location.
  • When "review" is appended to alias, it modifies the list that both primary and alias reference.
  • The print(primary) statement outputs the modified list, which now contains both "draft" and "review".

44. How do you copy a list?

For a shallow copy, use copy(), slicing, or list().

python
original = ["a", "b"]
clone = original.copy()

Explanation

  • The variable original is initialized as a list containing two string elements: "a" and "b".
  • The copy() method is called on the original list to create a new list, clone, which contains the same elements.
  • The clone list is a shallow copy, meaning changes to clone will not affect original, and vice versa.
  • This method is useful for preserving the original list while allowing modifications to the copy.

For nested mutable objects, use copy.deepcopy() when you need independent nested data.

45. What is a tuple?

A tuple is an ordered, immutable collection.

It is useful for fixed records, multiple return values, and dictionary keys when all items are hashable.

46. Why does a one-item tuple need a comma?

The comma creates the tuple, not the parentheses.

python
not_tuple = (10)
one_item_tuple = (10,)

print(type(not_tuple))
print(type(one_item_tuple))

Explanation

  • The variable not_tuple is assigned a single integer value, which does not create a tuple.
  • The variable one_item_tuple is correctly defined as a tuple containing one item by including a trailing comma.
  • The type() function is used to check the data types of both variables.
  • The output will show that not_tuple is of type int, while one_item_tuple is of type tuple.
  • This snippet highlights the importance of the comma in tuple creation when defining single-item tuples in Python.

47. What is tuple unpacking?

Tuple unpacking assigns values from a tuple-like iterable to names.

python
name, score = ("Neha", 91)

print(name)
print(score)

Explanation

  • A tuple containing a name and a score is created and assigned to the variables name and score simultaneously.
  • The first element of the tuple, "Neha", is assigned to the variable name.
  • The second element, 91, is assigned to the variable score.
  • The print statements output the values of name and score to the console.

48. What is a set?

A set is an unordered collection of unique hashable items.

python
topics = {"python", "oop", "python"}

print(topics)

Explanation

  • A set named topics is initialized with three elements: "python", "oop", and "python".
  • Sets in Python automatically eliminate duplicate entries, so "python" appears only once in the final set.
  • The print function outputs the contents of the topics set to the console.
  • The order of elements in a set is not guaranteed, as sets are unordered collections.

49. Why are lists not allowed inside sets?

Set elements must be hashable.

Lists are mutable and unhashable, so they cannot be set elements.

50. What is a dictionary?

A dictionary maps keys to values.

Keys must be hashable. Values can be almost any object.

python
profile = {"name": "Ira", "score": 88}

print(profile["name"])

Explanation

  • A dictionary named profile is created with two key-value pairs: "name" and "score".
  • The value associated with the key "name" is accessed using profile["name"].
  • The print function outputs the value of "name", which is "Ira", to the console.

51. Why does dictionary membership check keys?

in checks dictionary keys because keys are the lookup mechanism.

python
profile = {"name": "Ira", "score": 88}

print("name" in profile)
print("Ira" in profile)

Explanation

  • A dictionary named profile is created with two key-value pairs: "name" and "score".
  • The first print statement checks if the key "name" exists in the profile dictionary, returning True.
  • The second print statement checks if the value "Ira" exists in the profile dictionary, returning False since it is not a key.

52. What are dictionary views?

keys(), values(), and items() return dynamic view objects.

They reflect dictionary changes.

53. When should you use a list, tuple, set, or dictionary?

Use a list for ordered mutable sequences.

Use a tuple for fixed records.

Use a set for uniqueness and membership tests.

Use a dictionary for key-value lookup.

54. What is a function?

A function is a reusable block of code that can receive inputs and return output.

python
def add_bonus(score, bonus):
    return score + bonus

Explanation

  • The function add_bonus takes two parameters: score and bonus.
  • It returns the sum of score and bonus, effectively increasing the score by the specified bonus amount.
  • This function can be used in scoring systems where additional points are awarded, such as in games or assessments.
  • It is a simple and reusable function that promotes code clarity and modularity.

55. What is the difference between parameter and argument?

A parameter is the name in the function definition.

An argument is the value passed during the function call.

56. What is the difference between print and return?

print displays a value.

return sends a value back to the caller.

python
def double(number):
    return number * 2

result = double(5)
print(result)

Explanation

  • The double function takes a single parameter, number.
  • It returns the value of number multiplied by 2.
  • The function is called with the argument 5, and the result is stored in the variable result.
  • Finally, the value of result is printed, which outputs 10.

57. What does a function return if there is no return statement?

It returns None.

python
def greet():
    print("hello")

value = greet()
print(value)

Explanation

  • The greet function is defined to print the string "hello" when called.
  • The function is invoked with value = greet(), which executes the print statement inside the function.
  • The return value of the greet function is None since it does not explicitly return anything, which is stored in the variable value.
  • The final print statement outputs the value of value, which will be None.

58. What are default arguments?

Default arguments are used when the caller does not provide a value.

python
def create_title(text, prefix="Lesson"):
    return f"{prefix}: {text}"

Explanation

  • The function create_title takes two parameters: text (the main title) and prefix (defaulting to "Lesson").
  • It uses an f-string to concatenate the prefix and the text, ensuring a consistent format.
  • The return value is a string that combines the prefix and the text, separated by a colon.
  • This function can be useful for creating standardized titles in educational or instructional content.

59. Why are mutable default arguments risky?

The default object is created once when the function is defined, not each time it is called.

Safer version:

python
def add_tag(tag, tags=None):
    if tags is None:
        tags = []

    tags.append(tag)
    return tags

Explanation

  • The function add_tag takes two parameters: tag (the tag to be added) and tags (an optional list of existing tags).
  • If tags is not provided (i.e., it is None), a new empty list is created to hold the tags.
  • The specified tag is appended to the tags list.
  • The updated list of tags is returned, allowing for easy accumulation of tags over multiple function calls.
  • This approach ensures that each call to add_tag can either modify an existing list or create a new one if none is provided.

60. What are *args and **kwargs?

*args collects extra positional arguments.

**kwargs collects extra keyword arguments.

python
def describe_event(*labels, **details):
    return labels, details

print(describe_event("python", "live", speaker="Maya"))

Explanation

  • The function describe_event accepts a variable number of positional arguments (*labels) and keyword arguments (**details).
  • Positional arguments are collected into a tuple named labels, while keyword arguments are stored in a dictionary named details.
  • The function returns both labels and details, allowing for flexible input regarding event characteristics.
  • In the provided print statement, the function is called with two positional arguments ("python", "live") and one keyword argument (speaker="Maya").

61. What is a lambda function?

A lambda is a small anonymous function expression.

python
scores = [3, 10, 2]
print(sorted(scores, key=lambda value: value % 3))

Explanation

  • The list scores contains three integer values: 3, 10, and 2.
  • The sorted() function is used to sort the list, with a custom sorting key defined by a lambda function.
  • The lambda function calculates the remainder of each score when divided by 3 (value % 3).
  • The sorting will arrange the scores in ascending order based on these remainders.
  • The output will be a new list of scores sorted according to their remainders: [3, 10, 2] becomes [3, 2, 10].

Use normal def when logic needs a name, documentation, or multiple statements.

62. What are first-class functions?

Functions are first-class objects in Python.

You can assign them to variables, pass them as arguments, return them from functions, and store them in containers.

63. What is scope?

Scope decides where a name can be accessed.

Python follows LEGB lookup:

  • Local
  • Enclosing
  • Global
  • Built-in

64. What is the global keyword?

global tells Python that assignment should target a module-level name.

Use it carefully because it can make code harder to reason about.

65. What is the nonlocal keyword?

nonlocal lets a nested function assign to a name from an enclosing function scope.

python
def make_counter():
    count = 0

    def next_count():
        nonlocal count
        count += 1
        return count

    return next_count

Explanation

Unlock the Full Article

You're reading a free 30% preview. The rest of this article is available to premium members.

Browse Free Posts

Already a premium member? Sign in here