MonsieurBeilto
MonsieurBeilto

Reputation: 938

Python, different types of keywords

In python, one can attribute some values to some of the keywords that are already predefined in python, unlike other languages. Why? This is not all, some.

> range = 5
> range
> 5

But for

> def = 5
  File "<stdin>", line 1
    def = 5
        ^
SyntaxError: invalid syntax

One possible hypothesis is - Lazy coders with unique parsing rules.

For those new to python, yeah, this actually works, for keywords like True, False, range, len, so on. I wrote a compiler for python in college and, if I remember correctly, the keywords list did not have them.

Upvotes: 2

Views: 150

Answers (3)

Falko
Falko

Reputation: 17877

While range is nothing but a built-in function, def is a keyword. (Most IDEs should indicate the difference with appropriate colors.)

Functions - whether built-in or not - can be redefined. And they don't have to remain functions, but can become integers like range in your example. But you can never redefine keywords.

If you wish, you can print the list of all Python keywords with the following lines of code (borrowed from here):

import keyword
for keyword in keyword.kwlist:
    print keyword

Output:

and
as
assert
break
class
continue
def
del
elif
else
except
exec
finally
for
from
global
if
import
in
is
lambda
not
or
pass
print
raise
return
try
while
with
yield

And for Python 3 (notice the absence of print):

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

In contrast, the built-in functions can be found here: https://docs.python.org/2/library/functions.html

Upvotes: 4

Daniel Roseman
Daniel Roseman

Reputation: 599610

You are confused between keywords and built-in functions. def is a keyword, but range and len are simply built-in functions. Any function can always be overridden, but a keyword cannot.

The full list of keywords can be found in keywords.kwlist.

Upvotes: 1

Jos&#233; Molero
Jos&#233; Molero

Reputation: 118

The keyword 'range' is a function, you can create some other vars as well as sum, max...

In the other hand, keyword 'def' expects a defined structure in order to create a function.

def <functionName>(args):

Upvotes: 1

Related Questions