Python Keywords
Keyword is reserved word in python program. This are used to special meaning and purpose. Normally this are used to define statement and data type and perform special operation. In this post we are learning about that the how to use Python keyword in our program.
Let first check how many number of keywords are provided by Python version 2.7 and 3.5. We can display all available keyword using of this program.
import keyword
#display keywords
print(keyword.kwlist)
Python 2.7.12 keywords
['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']
Python 3.5.2 keywords
['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']
False | True | and | as |
assert | break | class | continue |
def | del | elif | else |
elif | else | except | exec |
finally | for | from | global |
if | import | in | is |
lambda | not | elif | else |
or | pass | raise | |
return | try | while | with |
yield | None |
True False keywords
True and False is boolean data type.
#check data type
print(type(True))
print(type(False))
#operation results
result=True
print(result) #True
result=False
print(result) #Talse
result=True+True+True
print(result) #3
result=True != False
print(result) #True
result=True+False
print(result) #1
When we are perform some arithmetic operation such as addition, subtraction, divisions etc. Then boolean data type are internal used integer value (0=False,1=True). And comparison operator are produced boolean values.
Output
<class 'bool'>
<class 'bool'>
True
False
3
True
1
and keywords
and keyword are used to comparing of two expression and values. This is alternate of '&'.
# Example of and keyword
# And operator working
# True and True --> True
# 1 and 1 --> 1
# False and False --> False
# 0 and 0 --> 1
# binary of 1 = 0 0 0 1
# binary of 1 = 0 0 0 1
#--------------------------
# and= 1 = 1
result=1 and 1
print(result) #1
# binary of 1 = 0 0 0 1
# binary of 0 = 0 0 0 0
#--------------------------
# and= 0 0 0 0 =0
result=1 and 0
print(result) #0
result=(1 != 0) and (1==1) #check given expression
print(result) #True
#Multiple and
result=1 and 1 and 1
print(result) #1
result= True and True
print(result) #True
result= False and False
print(result) #False
Output
1
0
True
1
True
False
as keyword
This keyword can used to provide a new name of import modules. for example
import keyword as special
#display keywords
print(special.iskeyword('as'))
Output
True
assert keyword
Assertions is an statement or state that are work on boolean expression. if condition is true then it will execute next line. If other case if condition is false then it will stop execution of program and throw an error. This error is user defined. For example.
def test(number):
# if condition is false then throw error
assert(number>0),"oops number is zero"
print(number)
#test cases
test(1)
test(2)
test(5)
test(-1)
Output
1
2
5
Traceback (most recent call last):
File "test.py", line 10, in <module>
test(-1)
File "test.py", line 3, in test
assert(number>0),"oops number is zero"
AssertionError: oops number is zero
if elif and else statement keywords
This is specially used to check condition statements. That are check an expression, If that is true then executed all statement of specified block.
if statement are work on given expression is not False and zero. For example.
if(1):
print("one")
if(True):
print("True")
if(-5):
print(" -5")
if(0):
print("zero") #not execute
if(5>4 and 5<6):
print("Valid condition")
if(False):
print("False value") #not execute
Output
one
True
-5
Valid condition
elif are used to check multiple condition. if statement expression are not valid then elif (else if) statement will be checking of expression. for example.
number=10
#check given number is equal to 1
if(number==1):
#statements
print("number is one")
#check given number is less then 3
elif(number<3):
#Block statements
print("number is less than 3")
#check number between (2 to 5)
elif(number>=2 and number<=5):
#Block statements
print("number between (2 to 5)")
elif(number==10):
#Block statements
print("number is ten")
elif(number==100):
#Block statements
print("number is hundred")
else :
print("Invalid number")
Output
number is ten
and else statement are work. when if and related elif condition are not satisfied. for example.
#else statement example
#test case 1
number=5
if(number==0):
print("Zero")
elif(number==1):
print("One")
else :
print("Number is not zero and one")
#test case 2
if(number<0):
print("negative number",number)
else:
print("positive number",number)
Output
Number is not zero and one
('positive number', 5)
for keyword
for is an looping keyword that are used to iterate statement in specified condition.
#Example of for keyword
#Case 1: working on constant list
for i in [1,2,True,False,"Ok"]:
print(i)#display value of list
#Case 2: execute loop between constant value
for i in range(6,10):
print(i)
#case 3 key value pair
record={"os Name":"linux",
"os Type":"64 bit",
"Memory":"7.7 GB"}
for key,value in record.items():
print key," :",value
#Case 4 key value pair with constant
for key,value in [('1', 'python'), ('2', 'cpp')]:
print key," :",value
Output
Number is not zero and one
('positive number', 5)
while keyword
'while' is looping keyword, that are iterate inside block of code when given expression result is valid.
i=0
#case 1: simple case
while i<5:
print(i) #display i value
i+=1
i=10
#case 2: while and else case
while i<15:
print(i) #display i value
i+=1
else:
print("Else code")
Output
0
1
2
3
4
10
11
12
13
14
Else code
break continue keyword
break and continue statement are used within the loop. break statement are stop current loop execution. sometime special case we are need to terminate loop before the given terminating condition. so break are useful to stop execute of loop. for example.
#break statement example
#case 1: using of within for loop
for i in range(1,1000):
if(i==5):
#break statement
break
else:
print(i)
i=i+1
i=1000
#case 1: using of within while loop
while i<2000:
print(i);
if i==1004: #condition to break loop
break; #break statement
i=i+1
Output
1
2
3
4
1000
1001
1002
1003
1004
continue statement are used to change execution follow of loop. This statement are used in inside a loop in specified condition. When continue statement are executed they are not execute next remaining statement of loop body. and control are move back to beginning of the loop. note that this statement are used only inside a loop. this will used on (for ,while) loops. for example.
#continue statement example
#case 1: using of within for loop
for i in range(0,5):
i=i+1
if(i==2 or i==4):
#continue statement
continue
else:
print(i)
i=50
#case 1: using of within while loop
while i<60:
i=i+1
if i>=54 and i<=57:
continue; #continue statement
else:
print(i);
Output
1
3
5
51
52
53
58
59
60
in keyword
This is an operator that are check a value of given sequence are exist or not. if exist then returning the value of true otherwise it will returning the value of false.
result = 1 in [1,2,3,4,5]
print(result) #True
result = 28 in {1,2,6}
print(result) #False
result = 1 in {1,2}
print(result) #True
for i in range(1,5):
print(i)
Output
True
False
True
1
2
3
4
is keyword
is are used to compare similar type of variables or object. if both are same type then it will return True otherwise False.
#Example to use is keyword
print(type(1) is int)
print(type(1.3) is float)
print(type(1.4) is int)
value=12
if(type(value) is int):
print("Integer value")
elif(type(value) is float):
print("Float value")
else:
print("value is",type(value))
Output
True
True
False
Integer value
not keyword in python
"not" keyword is used to negation of boolean result.
#Example to use not keyword
print(not True)
print(not False)
print(type(1) is not int)
print(type(1.3) is not float)
print(type(1.4) is not int)
print(11 not in [1,2,3])
Output
False
True
False
False
True
True
def keyword
this are used to define a function.
#Example of def keyword in python
def test():
#function statements
print("Test Function")
def config(num):
#function statements
print("config function :",num)
test()
config(1)
Output
Test Function
('config function :', 1)
del keyword
del keyword are used to delete object.
#Example of del keyword in python
data=10 #assign 10 to data object
print(data) #display value
del data #free object
print(data) #error this is undefined
Output
10
Traceback (most recent call last):
File "test.py", line 6, in <module>
print(data)
NameError: name 'data' is not defined
try except finally keyword in python
try block are used to define statement and expression that are produced an runtime error(exception). if try block are found any error then relevant except block are executed. finally block always work when it is exception are occurred or not. for example
def divide(dividend,divisor):
try:
print dividend/divisor
except ZeroDivisionError:
print "Opp's can't divide by zero."
finally:
print "Done execution"
#test case
divide(10,4)
divide(10,0)
divide(15,3)
Output
2
Done execution
Opp's can't divide by zero.
Done execution
5
Done execution
exec keyword in python
code="print(1+2)"
exec(code) #execute string code
Output
3
from keyword in python
from math import *
print(dir())
Output
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
global
data=10
#case 1 : without global
def display1():
data=12
print(data)
display1()
print(data)
#case 1 : with global
def display2():
global data
data=12
print(data)
display2()
print(data)
Output
12
10
12
12
import
import keyword are used to importing a module or file in our program. for example.
import keyword
print(keyword.iskeyword("in"))
print(keyword.iskeyword("out"))
Output
True
False
lambda
anonymous function
increment = lambda x : x + 1
print(increment(5))
Output
6
print keyword
print keyword are used to print result for console.
#example of print
print(1)
print "Welcome"
print("1","2","3")
print "name:","python"
Output
1
Welcome
('1', '2', '3')
name: python
from keyword
from keyword are used to include specific function, class of module.
#example of from keyword
#import factorial function from math modules
from math import factorial
print(factorial(3)) #use function
Output
6
return keyword
return is a statement is control execution of function, that are return back to caller statement. that is used in within the function. and that are capable to send one value.
#case 1: not return any value
def simple():
print("Simple function")
#return statement
return #control back
#this statement not execute
print("This is statement of simple function")
#case 2: return a list
def advance():
print("advance function")
return [1,2,3]
print simple() #display None
print advance() #display return value
Output
Simple function
None
advance function
[1, 2, 3]
or keyword
if(1 or 1):
print("one")
"""
x or y
if x and y similar the result=x or y
otherwise check if x (left side) not false and zero
then result will be = x
otherwise check y (right side)
is not False and zero then result=y
"""
result=1 or 0
print(result) #1
# if x and y similar the result=x or y
# check if 3 not false and zero theb result=3
# otherwise check 5 is not False and zero then result=5
result=3 or 5
print(result) #3
#conditional statement
#0<1 condition true
result= 0<1 or 0>8
print(result) #True
result=False | 5
print(result) #5
# if x and y similar the result=x or y
result=False | False
print(result) #False
Output
one
1
3
True
5
False
class keyword
#class example
class Calculate:
#constructor of class
def __init__(self,x,y):
self.x=x
self.y=y
#member function
def sum(self):
result=self.x+self.y
print self.x,"+",self.y,"=",result
obj1=Calculate(10,20)
obj1.sum()
obj2=Calculate(4,6)
obj2.sum()
Output
10 + 20 = 30
4 + 6 = 10
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment