Python Keywords
Python Keywords Interview with follow-up questions
1. Can you explain what are keywords in Python and why they are important?
Keywords are reserved words with fixed meaning in Python's grammar — they form the language's syntax, so you can't use them as variable, function, or class names. They're case-sensitive (True, not true), and you can list them at runtime with import keyword; keyword.kwlist.
They fall into rough groups:
- Control flow:
if,elif,else,for,while,break,continue,pass,match/case(soft keywords, 3.10). - Functions/classes:
def,return,lambda,class,yield. - Logic/identity:
and,or,not,in,is. - Exceptions:
try,except,finally,raise,assert. - Scope/imports:
import,from,as,global,nonlocal. - Async:
async,await. Values:True,False,None.
if x > 0 and x is not None:
for item in items:
...
Follow-ups to expect:
- Soft keywords (
match,case,type,_) are contextual — they're only keywords in their specific syntax, so they can still be used as identifiers elsewhere (though it's discouraged). isvs==:is(identity) compares object identity;==compares value — a classic source of bugs, useisonly forNone/singletons.- A trailing-underscore name (
class_,type_) is the PEP 8 way to work around a keyword clash.
Follow-up 1
Can you name a few Python keywords?
Sure! Here are some of the most commonly used Python keywords:
- 'and'
- 'as'
- 'assert'
- 'break'
- 'class'
- 'continue'
- 'def'
- 'del'
- 'elif'
- 'else'
- 'except'
- 'finally'
- 'for'
- 'from'
- 'global'
- 'if'
- 'import'
- 'in'
- 'is'
- 'lambda'
- 'not'
- 'or'
- 'pass'
- 'raise'
- 'return'
- 'try'
- 'while'
- 'with'
- 'yield'
These keywords have specific meanings in Python and cannot be used as variable names or any other identifiers.
Follow-up 2
What is the role of the 'def' keyword?
The 'def' keyword in Python is used to define a function. It is followed by the function name and a set of parentheses, which may contain parameters. The function definition is then followed by a colon and an indented block of code that makes up the function body.
Here's an example:
# Function definition
def greet(name):
print('Hello, ' + name + '!')
# Function call
greet('Alice')
In this example, the 'def' keyword is used to define a function called 'greet' that takes a parameter 'name'. The function body prints a greeting message using the provided name. The function can be called later using the function name and passing an argument.
Follow-up 3
What does the 'pass' keyword do in Python?
The 'pass' keyword in Python is used as a placeholder when a statement is required syntactically but no action is needed. It is often used as a placeholder for code that will be implemented later.
Here's an example:
if x < 0:
pass # TODO: Implement error handling
else:
print('Positive number')
In this example, the 'pass' keyword is used as a placeholder in the 'if' statement. It indicates that no action is needed for the negative case, but the code will be implemented later. Without the 'pass' keyword, the code would result in a syntax error.
2. What is the purpose of the 'return' keyword in Python?
return exits a function immediately and hands a value back to the caller. Execution of the function stops at that point — any code after it doesn't run — and the returned value becomes the result of the call.
def divide(a: float, b: float) -> float | None:
if b == 0:
return None # early exit
return a / b # normal result
Follow-ups interviewers like:
- No
return, or a barereturnreturnsNoneimplicitly — sox = mylist.sort()givesNone, a classic bug since in-place methods returnNone. - Returning multiple values actually returns one tuple, unpacked at the call site:
return x, ythena, b = f(). returnvsyield:returnends the call;yieldsuspends it and makes the function a generator that resumes later.returnvsprint:printonly shows text;returngives a value the program can use. Beginners often confuse the two.returnintry/finally: afinallyblock still runs after thereturnis evaluated, and areturninfinallywill override the one intry— a known gotcha.
Follow-up 1
What happens if a function doesn't have a return statement?
If a function doesn't have a return statement, it will still execute the code inside the function but it will not return any value. In this case, the function will implicitly return 'None', which is a special value in Python that represents the absence of a value. It is important to note that 'None' is not the same as '0' or an empty string, it is a unique object in Python.
Follow-up 2
Can a function return multiple values in Python?
Yes, a function can return multiple values in Python. This can be achieved by returning a tuple, which is an ordered collection of elements. The values to be returned can be enclosed in parentheses and separated by commas. For example:
def get_name_and_age():
name = 'John'
age = 25
return name, age
name, age = get_name_and_age()
print(name) # Output: John
print(age) # Output: 25
3. How does the 'if' keyword work in Python?
if runs a block only when a condition is truthy, optionally with elif for further tests and else for the fallback. The colon opens the block and the body is indented:
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
Follow-ups interviewers probe:
- Truthiness: the condition need not be a real
bool. Empty containers ([],{},""),0, andNoneare falsy; non-empty/non-zero values are truthy. Soif items:is the idiomatic "is this list non-empty?" — prefer it overif len(items) > 0:. isvs==in conditions: useif x is None:, notif x == None:.- Conditional (ternary) expression:
grade = "A" if score >= 90 else "B"for a one-line value choice. - The walrus operator lets you test and capture in one go:
if (n := len(data)) > 10:. - For many discrete cases against one value,
match/case(3.10) can be cleaner than a longelifchain — thoughif/elifremains the default for boolean conditions. - There's no
switchstatement;matchis the structural-pattern equivalent.
Follow-up 1
Can you provide an example of an 'if' statement?
Certainly! Here's an example of an 'if' statement in Python:
x = 10
if x > 5:
print('x is greater than 5')
Follow-up 2
How can 'elif' and 'else' keywords be used with 'if'?
The 'elif' keyword is used to specify an additional condition to be checked if the previous 'if' or 'elif' condition(s) are false. It allows you to chain multiple conditions together. The 'else' keyword is used to specify a block of code to be executed if none of the previous conditions are true. Here's an example that demonstrates the usage of 'elif' and 'else' with 'if':
x = 10
if x > 5:
print('x is greater than 5')
elif x < 5:
print('x is less than 5')
else:
print('x is equal to 5')
4. What is the use of the 'for' keyword in Python?
for iterates over the items of any iterable — list, tuple, string, dict, set, range, generator, file — running the body once per item. Python's for is a "for-each" loop, not a C-style counter loop:
for item in [10, 20, 30]:
print(item)
Follow-ups interviewers expect:
range()for counts:for i in range(5):when you actually need indices;rangeis a lazy sequence, not a list.enumeratewhen you need index and value:for i, x in enumerate(items):— cleaner thanrange(len(items)).zipto iterate two sequences in parallel:for name, age in zip(names, ages):.- Iterating a dict yields its keys by default; use
.items()for key/value pairs,.values()for values. for/else: theelseblock runs only if the loop finished without hittingbreak— useful for search loops, and a frequent gotcha.- Don't mutate a list while iterating it (e.g. removing items) — iterate over a copy or build a new list/comprehension instead.
- Under the hood,
forcallsiter()thennext()untilStopIteration— the iterator protocol.
Follow-up 1
Can you provide an example of a 'for' loop?
Sure! Here's an example of a 'for' loop that iterates over a list of numbers and prints each number:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
Output:
1
2
3
4
5
Follow-up 2
How does the 'break' keyword work in a 'for' loop?
The 'break' keyword is used to exit a 'for' loop prematurely. When the 'break' keyword is encountered inside a 'for' loop, the loop is immediately terminated and the program execution continues with the next statement after the loop. This can be useful when you want to stop the loop execution based on a certain condition.
5. Can you explain the 'try' and 'except' keywords in Python?
try/except is Python's exception-handling construct: code that might fail goes in the try block; if an exception is raised, control jumps to a matching except block instead of crashing. The full form adds else and finally:
try:
value = int(user_input)
except ValueError as err:
print(f"not a number: {err}")
else:
print("parsed", value) # runs only if no exception
finally:
print("always runs") # cleanup, runs no matter what
Follow-ups interviewers expect:
- Catch specific exceptions, not a bare
except:— a bare clause also swallowsKeyboardInterrupt/SystemExitand hides bugs. Catch the narrowest type, orexcept Exceptionat most. - Multiple types:
except (ValueError, TypeError) as err:; multipleexceptblocks are tried top to bottom, so order specific before general. elsevs putting code intry:elseruns only when no exception fired and keeps the "risky" lines minimal.finallyalways runs (even onreturnor re-raise) — for cleanup; though a context manager (with) is usually cleaner for resources like files.- Re-raising and chaining: bare
raisere-throws;raise NewError(...) from errpreserves the cause. - Exception groups and
except*(3.11) handle several errors at once, common with async code. - Don't use exceptions for ordinary control flow — "EAFP" is fine, but catching everything to ignore it is a smell.
Follow-up 1
How does exception handling work in Python?
In Python, when an exception occurs within a 'try' block, the code execution is immediately transferred to the 'except' block. The 'except' block catches the exception and executes the code within it. If there is no matching 'except' block for the raised exception, the program terminates and displays an error message.
Follow-up 2
Can you provide an example of using 'try' and 'except' in Python?
Certainly! Here's an example:
try:
x = 10 / 0
except ZeroDivisionError:
print('Error: Division by zero')
Live mock interview
Mock interview: Python Keywords
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.