Python Keywords
Keywords are the reserved words in Python.
We cannot use a keyword as a variable name, function name or any other
identifier. They are used to define the syntax and structure of the Python
language.
In Python, keywords are case sensitive.
There are 33 keywords in Python 3.7. This number can vary slightly over the
course of time.
All the keywords except True , False and None are in lowercase and they must
be written as they are. The list of all the keywords is given below.
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
The above keywords may get altered in different versions of Python. Some
extra might get added or some might be removed. You can always get the list
of keywords in your current version by typing the following in the prompt.
>>> import keyword
>>> print([Link])
['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']
True, False
True and False are truth values in Python. They are the results of comparison
operations or logical (Boolean) operations in Python. For example:
>>> 1 == 1
True
>>> 5 > 3
True
>>> True or False
True
>>> 10 <= 1
False
>>> 3 > 7
False
>>> True and False
False
True and False in python is same as 1 and 0 . This can be justified with the
following example:
>>> True == 1
True
>>> False == 0
True
>>> True + True
2
None
None is a special constant in Python that represents the absence of a value or
a null value.
We must take special care that None does not imply False , 0 or any empty list,
dictionary, string etc. For example:
>>> None == 0
False
>>> None == []
False
>>> None == False
False
>>> x = None
>>> y = None
>>> x == y
True
as
as is used to create an alias while importing a module. It means giving a
different name (user-defined) to a module while importing it.
As for example, Python has a standard module called math . Suppose we want
to calculate what cosine pi is using an alias. We can do it as follows using as :
>>> import math as myAlias
>>>[Link]([Link])
-1.0
async, await
The async and await keywords are provided by the asyncio library in Python.
They are used to write concurrent code in Python. For example,
import asyncio
async def main():
print('Hello')
await [Link](1)
print('world')
To run the program, we use
[Link](main())
In the above program, the async keyword specifies that the function will be
executed asynchronously.
Here, first Hello is printed. The await keyword makes the program wait for 1
second. And then the world is printed.
break, continue
break and continue are used inside for and while loops to alter their normal
behavior.
break will end the smallest loop it is in and control flows to the statement
immediately below the loop. continue causes to end the current iteration of the
loop, but not the whole loop.
This can be illustrated with the following two examples:
for i in range(1,11):
if i == 5:
break
print(i)
Output
1
2
3
4
for i in range(1,11):
if i == 5:
continue
print(i)
Output
1
2
3
4
6
7
8
9
10
class
class is used to define a new user-defined class in Python.
Class is a collection of related attributes and methods that try to represent a
real-world situation. This idea of putting data and functions together in a class
is central to the concept of object-oriented programming (OOP).
class ExampleClass:
def function1(parameters):
…
def function2(parameters):
…
def
def is used to define a user-defined function.
Function is a block of related statements, which together does some specific
task. It helps us organize code into manageable chunks and also to do some
repetitive task.
The usage of def is shown below:
def function_name(parameters):
…
del
del is used to delete the reference to an object. Everything is object in Python.
We can delete a variable reference using del
>>> a = b = 5
>>> del a
>>> a
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
NameError: name 'a' is not defined
>>> b
5
Here we can see that the reference of the variable a was deleted. So, it is no
longer defined. But b still exists.
del is also used to delete items from a list or a dictionary:
>>> a = ['x','y','z']
>>> del a[1]
>>> a
['x', 'z']
except, raise, try
except, raise, try are used with exceptions in Python.
Exceptions are basically errors that suggests something went wrong while
executing our
program. IOError , ValueError , ZeroDivisionError , ImportError , NameError , Typ
eError etc. are few examples of exception in Python. try...except blocks are
used to catch exceptions in Python.
We can raise an exception explicitly with the raise keyword. Following is an
example:
def reciprocal(num):
try:
r = 1/num
except:
print('Exception caught')
return
return r
print(reciprocal(10))
print(reciprocal(0))
Raise
The raise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the user.
Raise a TypeError if x is not an integer:
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
output: Traceback (most recent call last):
File "demo_ref_keyword_raise2.py", line 4, in <module>
raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed
Python Try Except
he try block lets you test a block of code for errors.
The except block lets you handle the error.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the try-
and except blocks.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.
These exceptions can be handled using the try statement:
Example
The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
Else
You can use the else keyword to define a block of code to be executed if no
errors were raised:
Example
In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
output: Hello
Nothing went wrong
from, import
import keyword is used to import modules into the current namespace. from…
import is used to import specific attributes or functions into the current
namespace. For example:
import math
will import the math module.
Now we can use the cos() function ,this can done using from as
from math import cos
in
in is used to test if a sequence (list, tuple, string etc.) contains a value. It
returns True if the value is present, else it returns False . For example:
>>> a = [1, 2, 3, 4, 5]
>>> 5 in a
True
>>> 10 in a
False
The secondary use of in is to traverse through a sequence in a for loop.
for i in 'hello':
print(i)
Output
h
e
l
l
o