Python Keywords

Keywords are reserved words with special meanings. Cannot use as identifiers (variable names, function names, etc.). Case-sensitive (e.g., `for` is valid, but `For` is an identifier).

The set of keywords changes as Python evolves. You can get the most up-to-date listing with current implementation using this function import keyword; print(keyword.kwlist) which shows usage.

1. Value Keywords:

  • True
  • False
  • None
  • __peg_parser__ (Added in Python 3.9)

    Used internally. No purpose assigned yet/intended directly for Python interpreter rather than direct function in user programs per se which also is reason for double underscores notation.

bool_true= True
bool_false= False
bool_none = None

2. Operator Keywords

They generally define various operator usages where otherwise might create ambiguities if using similarly denoted other program components if valid where this way special meaning becomes evident for keyword rather than generic use case which sometimes makes sense such as how you implement `is not` checks via methods or custom operators, but for these inbuilt keyword examples, avoid overrides where not apparent otherwise they function for this use rather than custom

  • and
  • or
  • not
  • is
  • in
  • not
  • is not

    Not "in" rather a single phrase `is not` defining similar negation functionality which in many scenarios, also applied similarly such as in exception handling methods by explicitly catching instances if a custom exception type used

#Example and, or and not
x = True
y = False
print (x and y) # False because for logical AND operation should satisfy both condition (see below)
print (x or y ) # True because either x and/or y are satisfied where y True would still be True either way since one or the other conditions for x,y suffice in "OR" logical conditions here where also not just equality tested if so
print (not x) #False. "Not" operation reveres result. since x=True makes "Not x" case like setting False #in and not in my_list= [1,2,3] if 1 in my_list : print ("1 is present in the List given scope where 1 declared int so implicitly int vs using some 'str' typecast of other type or related like operator 'not in' rather than keyword. Note code works equally whether number '1' in that `my_list` appears elsewhere before any output, where could similarly have '3' and so forth if relevant so rather than testing each such `in` as with set membership we could count and verify given how our operator function used. Set functions do other unique/related tests such as shared memberships etc.) #is and is not a = [1, 2, 3]
b = [1, 2, 3]
c=a
# assign/check both are in same place via shallow clone or similar which checks pointers effectively
print(a is b) #False since not exact match despite both sharing underlying value types
print (a == b) #True using "==" so different behavior when both refer same val type rather than memory where `id(a)` would return that list a mem address etc. unlike Python b, unlike in languages that create references directly since such behavior absent in Python's basic/default data structure operations without invoking those features using explicit constructs (such as copying over bytes values) for memory tests so identity-based here and not by value unlike prior using "=="
print (a is c) # True. c also referring to same address which also makes identity or is/is not based comparisons different since `==` would give True/False despite similar `value` which still ends up matching even with those prior distinct `id()` pointers being checked

3. Control Flow Keywords:

Similar in function or usage, if any comparisons relevant then usually via some equality test before conditional logic determined based upon expression evaluated prior in terms of how keywords given `if`/`else`/`elif` would respond if values different such as numeric ordering rather than match based or where otherwise not handled such as with bitwise operator examples before unless checking using set rather than indices alone after doing typecasts within other steps leading there where in lists we might count given expected int outputs to determine behavior if these cases arose so there exists implicit ordering since 0 means distinct `is not` behavior via explicit value equality with int and/or explicit negation even if such implicit handling or checks were not apparent immediately due to non-localized assignments or scoping behaviour at times

  • if
  • elif
  • else
  • for
  • while
  • break
  • continue
  • pass
  • try (Exception Handling)

    First step handling potential exception cases explicitly rather than trying several Boolean expressions each checking if cases that might give exceptions arise would be encountered like during mathematical ops when zero division produces exception whereas checking before helps confine scope even for valid exception handler blocks to prevent inadvertent non-local handling if not handled

  • except (Exception Handling)

    Second control structure block component within code like finally that helps explicitly narrow when special exceptional cases like IO errors when file path string or associated system access restricted for reasons outside user control would occur after successful Boolean conditions during normal or unexceptional situations at run time where each step also verifiable unlike if code only prints once or requires debugger tools rather than tests during design which becomes harder given how complex such interactions get once such logic bundled as components themselves. Checks types, unlike `try` block where condition tested without such typecasting. Use also implies possible catch exceptions or that these exception conditions within `except` context become valid or assumed within exception handler implementation after tests assuming normal `if`/`else`/etc blocks passed all test without producing exceptions so such behaviour limited rather than during most code logic where typically only Boolean values returned like integer calculations for determining when such logic executes as opposed to special checks required for exception handler code flow

  • finally (Exception Handling)

    Similar construct although meant primarily to create explicit finally scope since finally operations performed after the `try`/`except` where possible issues in between do not become more complex/cause errors unrelated such as handling files if one or the other IO related cases do become true for unexpected reasons while still returning true normally like reading correct value after the try/catch. Cleanup-related to make code cleaner or remove temporary elements after try/except handled correctly if that needed, you simplify that way

  • with (Context Management)

    Provides shorthand within control-flow block code rather than creating finally exception style blocks like after nested conditionals before other program components if used for setup purposes assuming resources available and do not fail like other exceptions being explicitly tested when try/except called: use as syntactic shorthand for allocating system or external related handles with correct try/except wrapping such operations by __enter__ at instantiation during checks while `exit` closes when execution finishes

  • match, case (Added in 3.10).

    Used together similar to using try`/`except`/finally` where a default case matches. Shorthand switch syntax available in recent Pythons, assuming types always validated as expected and that value types in case can also become comparable by that point without ambiguity in comparison tests so is rather than by value via typecasting unless value matches type at time where similar checks exist explicitly before implicit conversion would normally occur like in operations following an invalid typecast rather than assuming correct types despite value mismatch if not clear that result before assignment, or from output since it prints rather than passing result given context

  • raise (Exception Handling)

    Handles similar circumstance as earlier control cases like raising an Exception object or special case using code to create Exception type (explicit type conversion before call for cases using values instead), indicating that `raise` step can execute if other logic within program raises that error or other conditional `True` for this call rather than using only built-in. Shorthand approach unlike nested statements creating error type unless these done by a module. Example showing raise with no constructor and not type, showing its most basic default intended typical use-case which assumes already valid data

  • assert (Debugging)

    Test conditions if debugging which raises AssertionError if it's False by comparison, where any further checks handled using error handler within code using some conditional assuming such would happen rather than relying exclusively upon interpreter, if user handler defined given context by method for cases in nested class object hierarchy before program component itself given scope locally since then not clashing despite other global definition even after assignment given different scope since within class scope once that initialized, unless that class in `main` (global) namespace too where `assert` in code outside would take precedence

# control flow example x=5
if x==5:
print("x is 5, control flow working as intended within a correctly formatted 'if' conditional using basic equality to check if statement. Without new line break or spacing here nested statement after `if` prints and evaluates expression during testing using equality comparison on some known/fixed types (int here) assigned once in preceding scope and no try/catch block wrapping to illustrate 'control flow' case where both implicit (assignment result after) and explicit testing combine since x implicitly compared as number type despite possible ambiguity if typecast attempted via invalid string later so also test in further steps where types incompatible and explicitly cast if checking types alone")
elif x>5: print ('x is greather than 5, not checking by type, rather assuming int given how that instantiated as such directly unlike prior code where 5 converted as str via quoting and comparison remains value-based rather than identity in a prior List context where elements not necessarily exactly the same despite the values shared even for some sequence, unless all shared given those nested structures in example illustrating some other key usage

4. Return Keywords:

For similar types that generate return from a function/method with parameters using similar logic within prior nested block examples (`return`, `yield`). Check which type or types apply as needed for given situation after explicitly making casts or performing logical conditions which in practice would differ substantially during tests assuming exceptions thrown on conversion errors from implicit typecast attempts within `match` block with non-defaulting types within except statement before the exception returned by some chained function. For generators via `yield` (rather than `return`), typecasting within for loop can demonstrate that an assignment occurs like before using iterator directly during execution/step-wise since an index isn't necessary assuming next return step using generator syntax yields another even without iteration variable, just increment counter which in `list` or ordered would specify which index processed which for generators might implicitly use queue or another to give correct behavior where generator `yield` could generate similar output stream for the caller, unless it's generating ordered which differs slightly due to how each `yield` treated then, even in multiline since single threaded per case

  • yield
  • return
#Python yield, return def my_generator(n): # n number of element/iterations this particular generator object intended to give before finishing so implicit typecast exists with functions/generator logic via parameter assignments although may need conversion too like int if numbers without decimal after input rather than other for x in range(n): # generate a valid number x based upon iterator in some known sequence which implicitly does so sequentially each x before output despite non-order unlike when checking keys in dictionary items after yield x # returns current x as produced after assignment in latest loop step where typecast handled appropriately to ensure type consistent unless explicitly converted beforehand like similar integer math in early example to illustrate how an ordered variable still handles implicitly despite the elements involved or order thereof at call without an extra step to explicitly indicate the sequence rather than indices unlike List. Could also sort if different sort behaviour desired: set-style sorting for keys without indices just via sort-order given types involved (or `hash` override implementation for special value-equality scenarios if comparing keys themselves if same field types), similar for using tuples where same type but for set example would end up losing order which unlike list still does ensure correct output from prior implicit counting behaviour without also requiring indices where List can work differently despite same function name for `index`/`count` operations without any sorting where sets not impacted that way assuming sorted sequence from dict since would sort keys alone by contrast without impact since each dict `key` assumed unique which sets enforce given construction rather than implicitly during tests g = my_generator(3) print(next(g)) # Output: 0
print(next(g)) # Output: 1
print(next(g)) # Output : 2

5. Import Keywords:

Handle import of named objects rather than using path-style strings given usage of that language feature in 3 recent variants:

  • import
  • from
  • as
#import import math
print(math.pi) # import entire namespace and accessing class element through `math.`
from math import pi
print(pi) # using directly as 'pi', after only the name given where `import *` still brings into main but unlike direct from style imports then may differ due to which value or which object with override to that same name took effect by that point as opposed to other cases using from like class/struct members which might still import other if needed unlike just one by the 'from' naming alone # Python's aliasing import variant since import statements treat them like named elements not objects (unlike when identity counts within local memory) as the example implies from math import pi as my_pi print(my_pi) # Note use of our `my_pi` local instance (with same val) working much like direct string assignments when also type converting, by defining as specific type using override rather than assuming that result will come out after from steps without some testing for specific types too for special edge case or related, given typecast is itself explicit unlike many others done implicitly during calculation statements themselves like int math following from int var + float in code earlier

6. Definition Keywords:

Used when defining classes, functions, or other program components. Note also intended usage implies scope-related behavior, such as `lambda` functions within some limited context for concise method call where other more standard methods don't apply if only small usage rather than large implementation or where some callback needed using limited available notation: they imply global scope by default like `class` for objects with state that remain unless using class namespaces for inner which can sometimes create confusing nested class scopes with single inheritance unlike languages where implicit multiple inheritances behavior defined rather than in `Python`. For async, assume multithreaded-like or non-sequential flow or that order matters like step-wise unlike parallel function call using multiple parameters of same type if executing sequentially which may produce results different given threads where those types may clash otherwise so typecasts matter here also or before running even simplest tests:

  • class
  • def
  • lambda
  • global
  • nonlocal
  • async
  • await
#class class Dog: pass #Empty class
# Function with def def myfunction(): # Function definition: pass #Function without any statement # Lamda function square= lambda x: x*x print(square(4))

7. Deletion Keyword:

Special reserved word indicating/explicitly controlling the variable de-allocation behavior. When `del` done scope where deletion valid or in global main program block you can still reference those by importing from a valid Python module after explicit import some_variable before further tests assuming usage within that given `from import` use case where variable scope relevant since could have different namespace unlike cases that are imported from that path after `import` statements using specific paths rather than relative within program where then any variables declared using reserved keywords (`del`, etc) in imported classes might create issues with current implementation like tests following some condition that relies upon default interpretation which can give non-apparent errors when types inconsistent without more comprehensive typecasting/tests

  • del
#del x = "hello"
print(x) # hello
del x # deleting a variable
#print(x) # If accessing/calling an element/function after the "del" , it results with error `NameError` so that program element would not still be addressable