Saturday, July 9, 2022

[FIXED] What really is a keyword in Python?

Issue

We can get a list of Python keywords as follows:

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', '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']

Cool, but I didn't expect to see False, None, and True there. They are builtin objects.

Why are True, False, and None keywords, but int isn't? What really makes something a keyword in Python?

Edit: I am talking about Python 3


Solution

Keywords are reserved names, so you can't assign to them.

>>> True = 0
  File "<stdin>", line 1
SyntaxError: can't assign to keyword

int is a type; it's perfectly possible to reassign it:

>>> int = str
>>>

(I really wouldn't recommend this, though.)



Answered By - Daniel Roseman
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.