Comment trouver un mot clé dans une phrase ?

Unlocking Python's Core: Understanding Keywords

04/06/2025

Rating: 4.3 (12388 votes)

Python, renowned for its readability and simplicity, owes much of its elegance to a well-defined set of fundamental building blocks: its keywords. These aren't just ordinary words; they are the special vocabulary of the Python language, each carrying a unique, predefined meaning that guides the interpreter in understanding and executing your code. For anyone delving into Python programming, a solid grasp of these keywords is not merely beneficial—it's absolutely essential.

Quels mots-clés ne sont pas autorisés dans un identificateur Python ?
Les mots-clés ne sont pas autorisés à être les noms des identificateurs. Les symboles spéciaux tels que $, !, @, #, %, etc. ne sont pas autorisés dans un identificateur. L’identificateur Python n’a pas de limitation de longueur. Les espaces vides ne sont pas autorisés.

This comprehensive guide aims to demystify Python's keywords. We'll explore what they are, how they differ from the broader concept of "reserved words," and, crucially, how you can programmatically discover and verify them within your Python environment. We'll also provide a detailed overview of each keyword, discuss best practices for using them, and address common questions to ensure you have a robust understanding of these core components of the Python language.

Table

Understanding Python Keywords: The Language's Vocabulary

In the realm of programming, a keyword is a word that is reserved by a program because it has a special meaning. Keywords are integral to the syntax of the language, dictating how statements are constructed and how operations are performed. They define the structure and behaviour of your programs, allowing you to control flow, define functions, handle errors, and much more.

Où trouver les mots-clés en Python ?
En Python, au moins depuis Python 3.7, tous les mots-clés sont des mots réservés. Vous pouvez interroger une liste de mots-clés Python avec le module de mots-clés dans la bibliothèque standard.

For instance, when you see if in Python code, you immediately know it's initiating a conditional statement. The word def signals the definition of a function, and for indicates a loop. These words are not arbitrary choices; they are the fixed, unchangeable commands that Python understands inherently. Because of their special roles, keywords cannot be used for any other purpose, such as naming variables, functions, or classes. Attempting to do so will result in a SyntaxError, as the Python interpreter would become confused about your intention.

Keywords vs. Reserved Words: A Subtle but Important Distinction

While often used interchangeably, "keywords" and "reserved words" have distinct technical definitions, though in Python, particularly from version 3.7 onwards, this distinction largely collapses. Strictly speaking, keywords are words that have a special meaning and are part of the language's syntax, like if, while, or def.

On the other hand, reserved words are simply words that cannot be used as identifiers (names for variables, functions, classes, etc.) because they are "reserved" by the language for future or existing use. A language might have reserved words that are not currently keywords but are set aside to prevent conflicts with future language features. However, Python simplifies this concept significantly:

  • In Python, at least since version 3.7, all keywords are also reserved words. This means any word that has a special syntactic meaning cannot be used as an identifier.
  • Conversely, there are no reserved words in Python that are not also keywords. This simplifies the rule: if it's a keyword, you can't use it as an identifier, and that's the only category of reserved words you need to worry about.

This clear-cut policy ensures that the language remains consistent and predictable, preventing naming conflicts that could lead to difficult-to-debug errors. When you're writing Python code, the practical takeaway is simple: avoid using any word from the keyword list as your own identifier.

Quel est le but de l'exercice de Python ?
J'ai quand même l'impression que le but de l'exercice est de faire utiliser boucles et tests à l'étudiant afin de résoudre un petit problème très courant. Ce n'est qu'après qu'il découvrira que python dispose de méthodes toutes faites. Cela étant, je préfère aussi la boucle for au while dans ce cas-ci.

Discovering Python's Keyword List: keyword.kwlist

Python thoughtfully provides a built-in module, aptly named keyword, that allows you to programmatically access its list of keywords. This is incredibly useful for introspection, especially when dealing with different Python versions or when building tools that might need to identify valid identifiers.

The most straightforward way to retrieve all current Python keywords is by accessing keyword.kwlist. This is a list object containing string representations of every keyword. Here's how you can use it:

import keyword import pprint # Check the type of keyword.kwlist print(type(keyword.kwlist)) # Output: <class 'list'> # Check the number of keywords (can vary by Python version) print(len(keyword.kwlist)) # Output (e.g., for Python 3.7.3): 35 # Pretty-print the list for better readability pprint.pprint(keyword.kwlist, compact=True) # Output: # ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', # 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', # 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', # 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] 

As you can see, keyword.kwlist is indeed a Python list, and each element within it is a standard string (str). This means you can iterate over it, check for specific keywords, or even count them, providing a dynamic way to understand the language's current vocabulary.

print(keyword.kwlist[0]) # Output: False print(type(keyword.kwlist[0])) # Output: <class 'str'> 

Attempting to use any of these words as an identifier will result in a SyntaxError. For example:

# This will cause an error! # True = 100 # SyntaxError: can't assign to keyword 

This strict enforcement is a core design principle of Python, ensuring that the interpreter always knows whether a given word is a command or a user-defined name.

Comment savoir si un mot-clé est actif en Python ?
Renvoie vrai si s est un mot-clé de Python. Séquence contenant tous les mots-clés définis par l'interpréteur. Si certains mots-clés sont définis pour être actifs seulement si des instructions __future__ particulières sont effectives, ils seront tout de même inclus. Return True if s is a Python soft keyword. Added in version 3.9.

A Note on Soft Keywords (keyword.softkwlist)

For Python versions 3.9 and later, you might also encounter keyword.softkwlist. These are identifiers that can act as keywords only in specific contexts, often related to new language features introduced through __future__ statements (like the match and case keywords for structural pattern matching). While they are not part of the main keyword.kwlist that represents universally reserved keywords, they are important to be aware of in modern Python development, as they also cannot be freely used as identifiers in those specific contexts.

Verifying Keywords: keyword.iskeyword()

Beyond listing all keywords, the keyword module also offers a convenient function to check if a specific string is a Python keyword: keyword.iskeyword(). This function takes a string as an argument and returns True if the string is a keyword, and False otherwise.

This is particularly useful if you're dynamically generating names or validating user input to ensure it doesn't clash with Python's reserved vocabulary. Here are some examples:

import keyword print(keyword.iskeyword('if')) # Output: True print(keyword.iskeyword('while')) # Output: True print(keyword.iskeyword('my_variable')) # Output: False print(keyword.iskeyword('Class')) # Case-sensitive! # Output: False (because 'class' is lowercase) print(keyword.iskeyword('TRUE')) # Case-sensitive! # Output: False (because 'True' is title-case) 

Remember that Python keywords are case-sensitive. While True, False, and None begin with an uppercase letter, all other keywords are entirely lowercase. keyword.iskeyword() respects this case sensitivity, making it a precise tool for keyword verification.

Où trouver les mots-clés en Python ?
En Python, au moins depuis Python 3.7, tous les mots-clés sont des mots réservés. Vous pouvez interroger une liste de mots-clés Python avec le module de mots-clés dans la bibliothèque standard.

The Complete List: A Comprehensive Overview of Python Keywords

To provide a clearer picture of the language's foundational vocabulary, here's a detailed table of Python's keywords, along with a brief description of their purpose and a typical use case. This list is based on Python 3.7+, which includes async and await.

KeywordDescriptionExample Use Case
FalseA boolean value representing logical falsehood.if not condition: # condition is False
NoneRepresents the absence of a value or a null value. It's often used to signify that a variable has no value.my_variable = None
TrueA boolean value representing logical truth.while True: # Infinite loop until break
andA logical operator that returns True if both operands are True.if x > 0 and y < 10:
asUsed to create an alias for an imported module or in a with statement for context managers.import math as m
with open('file.txt') as f:
assertUsed for debugging; checks if a condition is True. If False, it raises an AssertionError.assert age >= 18, "Must be an adult"
asyncIntroduced in Python 3.5, used to define an asynchronous function (coroutine).async def fetch_data():
awaitIntroduced in Python 3.5, used to pause the execution of an async function until a coroutine completes.data = await fetch_data()
breakTerminates the current loop (for or while) and transfers control to the statement immediately following the loop.for i in range(10): if i == 5: break
classUsed to define a new class, which is a blueprint for creating objects in object-oriented programming.class Car:
continueSkips the rest of the current iteration of a loop and moves to the next iteration.for i in range(10): if i % 2 == 0: continue # Skip even numbers
defUsed to define a function or method.def calculate_area(length, width):
delUsed to delete objects, elements from lists, or items from dictionaries.del my_list[0]
del my_variable
elifShorthand for "else if," used in conditional statements to check multiple conditions sequentially.if cond1: ... elif cond2: ...
elseExecutes a block of code if the preceding if or elif conditions are False.if cond: ... else: ...
exceptUsed with try to catch and handle specific exceptions (runtime errors).try: ... except ValueError: ...
finallyA clause in a try-except block that is always executed, regardless of whether an exception occurred.try: ... finally: # Cleanup code
forUsed to iterate over a sequence (like a list, tuple, string, or range) or other iterable objects.for item in my_collection:
fromUsed with import to import specific attributes (functions, classes, variables) from a module.from math import pi, sqrt
globalDeclares that a variable inside a function refers to a global variable, not a local one.global counter
ifUsed for conditional execution of code. The block is executed if the condition is True.if temperature > 25:
importUsed to import modules or packages into the current namespace.import os
import collections
in1. A membership operator, checking if a value is present in a sequence. 2. Used in for loops.if 'apple' in fruit_list:
for num in range(5):
isAn identity operator that checks if two variables refer to the exact same object in memory.if x is None:
lambdaUsed to create small, anonymous (unnamed) functions.add = lambda x, y: x + y
nonlocalDeclares that a variable in a nested function refers to a variable in an enclosing (but not global) scope.def outer(): x = 10; def inner(): nonlocal x; x = 20;
notA logical operator that negates a boolean value (True becomes False, and vice versa).if not is_valid:
orA logical operator that returns True if at least one of the operands is True.if age < 18 or has_parental_consent:
passA null operation; it does nothing. Used as a placeholder where a statement is syntactically required but no action is desired.def future_feature(): pass
raiseUsed to explicitly raise an exception.raise ValueError("Invalid input provided.")
returnExits a function and optionally sends a value back to the caller.return result_value
tryDefines a block of code to be tested for errors while it is being executed.try: # Code that might raise an error
whileUsed to execute a block of code repeatedly as long as a specified condition is True.while count < 10:
withUsed to wrap the execution of a block of code with methods defined by a context manager (e.g., for file handling, ensuring resources are properly closed).with open('data.csv', 'w') as csvfile:
yieldUsed in generator functions to produce a sequence of values. It pauses function execution and returns a value, resuming from where it left off on the next call.def generate_numbers(): yield 1; yield 2

Python Identifiers: Naming Your Code Elements

While keywords are the language's own vocabulary, identifiers are the names you give to your own programming elements: variables, functions, classes, modules, and so on. Choosing clear, descriptive identifiers is a cornerstone of writing readable and maintainable code. However, there are strict rules governing what constitutes a valid identifier in Python:

Rules for Naming Identifiers:

  • Allowed Characters: An identifier can consist of letters (a-z, A-Z), digits (0-9), and underscores (_). Examples: total_count, userName1, _internal_var.
  • Starting Character: An identifier cannot start with a digit. For example, 1st_item is illegal, but item_1st is perfectly valid.
  • Keywords are Forbidden: This is the most crucial rule for this article: you absolutely cannot use any of Python's keywords as an identifier. Attempting to do so will result in a SyntaxError.
  • No Special Symbols: Symbols like $, !, @, #, %, ^, &, *, (, ), -, +, =, {, }, [, ], |, \, ;, :, ', ", <, >, ., ?, /, `, or ~ are not allowed within identifiers.
  • No Whitespace: Identifiers cannot contain spaces. If you need multiple words, use underscores (snake_case) or camel case (camelCase / CamelCase).
  • Case-Sensitivity: Python is a case-sensitive language. This means myVariable and myvariable are treated as two entirely different identifiers.
  • Length: Python identifiers have no strict length limitation, though it's always best practice to keep them concise and meaningful.

Best Practices for Identifiers:

  • Be Descriptive: Use names that clearly indicate the purpose of the variable, function, or class (e.g., customer_name instead of cn).
  • Follow Naming Conventions:
    • For variables and functions, use snake_case (e.g., calculate_total_price).
    • For classes, use PascalCase (or CamelCase with the first letter capitalised) (e.g., MyClass).
    • For constants, use SCREAMING_SNAKE_CASE (e.g., MAX_CONNECTIONS).
    • Leading single underscore (e.g., _private_var) suggests an internal-use variable.
    • Leading double underscore (e.g., __mangled_var) triggers name mangling for class attributes.
    • Trailing single underscore (e.g., class_) is used to avoid conflicts with built-in names or keywords.

Common Pitfalls and Best Practices

Understanding Python keywords is crucial for avoiding common programming errors. Here are a few key points to remember:

  • Avoid Keyword Collisions: The most significant pitfall is attempting to use a keyword as an identifier. As demonstrated, this will always result in a SyntaxError. Python's strictness here is a feature, not a bug, guiding you towards valid code.
  • Version Compatibility: Be aware that the list of keywords can evolve with new Python versions. For example, async and await were introduced in Python 3.5 and became firmly established keywords from 3.7. If you're working with older Python environments, their keyword.kwlist might differ. Always check the documentation or use keyword.kwlist programmatically if in doubt about a specific environment.
  • Readability over Cleverness: While Python allows for very short identifiers, prioritising readability by choosing descriptive names (that aren't keywords!) will save you and others significant time in the long run.

Frequently Asked Questions (FAQs)

Q: Can I change the meaning of a Python keyword?
A: No, Python keywords have fixed, predefined meanings and cannot be redefined, modified, or overridden by the programmer. They are fundamental to the language's syntax and operation.
Q: Are Python keywords case-sensitive?
A: Yes, Python is a case-sensitive language, and this applies to keywords as well. For example, if is a keyword, but If, IF, or iF are not. The only exceptions to the all-lowercase rule are the boolean literals True, False, and the null value None, which begin with an uppercase letter.
Q: How many keywords does Python have?
A: The exact number of keywords can vary slightly between different Python versions. As of Python 3.7.3 (the version mentioned in the source material), there are 35 keywords. You can always get the current count for your Python installation by running len(keyword.kwlist).
Q: Why can't I use keywords as variable names?
A: Keywords are reserved by the Python language to perform specific operations and control program flow. If you were allowed to use them as variable names, it would create ambiguity for the Python interpreter, making it impossible to distinguish between a command and a user-defined name. This would lead to syntax errors and unpredictable program behaviour.
Q: What are "soft keywords" in Python 3.9+?
A: Soft keywords, like match and case introduced in Python 3.10 for structural pattern matching, are identifiers that can act as keywords only in specific syntactic contexts. Unlike regular keywords which are always reserved, soft keywords can still be used as ordinary identifiers outside their special context. However, it's generally good practice to avoid using them as identifiers to prevent confusion and potential issues in future Python versions or when refactoring code.

Understanding Python's keywords is more than just memorising a list of words; it's about grasping the core mechanisms that drive the language. By respecting these fundamental building blocks and employing sound identifier naming practices, you lay a strong foundation for writing clean, efficient, and error-free Python code. Keep exploring, keep building, and let Python's elegant design guide your programming journey.

If you want to read more articles similar to Unlocking Python's Core: Understanding Keywords, you can visit the Automotive category.

Go up