Keywords
play an essential role in every programming language. Keywords in every
language provide language implemented logic that can be directly used in the
user programs.
This
article will explain the keywords available in Python with examples.
To
find the available keywords in the Python language, we can use the snippet
import keyword
print keyword.kwlist
print keyword.kwlist
Which
will print all the available keywords.
Here
are the list of Keywords available in Python.
['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']
We
will see one by one
True & False - True and False are mainly used when evaluating
things. They are the results of the Comparison Operations or logical ( Boolean)
operations in Python. True and False in python is same
as 1 and 0.
>>>
1 == 1
True
>>>
5 > 3
True
>>>
5 < 3
False
>>>
True + True
2
>>>
False + False
0
None
- None in python is just a value that is commonly used to say either
"Empty" or "No value there". None in Python is a signal
object which means Nothing. There will be only one copy of the None Object in a
Python interpreter session.
The
same None is available in other languages as Null or Undefined. None in Python
is very different as it is not a primitive type rather it is a Object for the
Class NoneType.
Variables
names are something like a sticker in Python. So you just need to change the
Sticker if you assign a new value. When you write
F
= "fork"
you
put the sticker "F" on a string object "fork". If you
then write
F
= None
you
move the sticker to the None object.
Normally
in Python we didn't write the sticker "F",
there was already an F sticker on the None, and
all you did was move it,
from None to "fork". So when you type F = None,
you're "reset[ting] it to its original, empty state
if
we decided to treat None as meaning empty state`.
- Let's confirm the type
of None first
- print type(None)
print
None.__class__
Output
<type
'NoneType'>
<type
'NoneType'>
Basically, NoneType is
a data type just like int, float, etc.
None
is a singleton object (meaning there is only one None), used in many places in
the language and library to represent the absence of some other value.
For example:
if d is a dictionary, d.get(k) will return d[k] if it exists, but None if d has no key k.
apple
= "apple"
print(apple)
>>>
apple
apple
= None
print(apple)
>>>
None
None
means nothing, it has no value.
None
evaluates to False.
Void
functions that do not return anything will return a None object
automatically. None is also returned by functions in which the
program flow does not encounter a return statement.
>>>
def void_function():
... a=1
... b=2
... c = a + b
...
>>>
print void_function()
None
import - import keyword is used to import packages into our
name spaces. That can be used as
>>>
import keyword
>>>
print keyword.iskeyword("in")
True
As
– is a keyword used with import keyword . this is used when creating a alias
for a module. It gives a different name to the module while importing
>>>
import math as hai
>>>
hai.cos(hai.pi)
-1.0
Assert - is a keyword
used in debugging Purpose. While programming we may need to check if the
statements are True or not.
Assert
helps us to do this . assert is followed by a condition. If the condition is
true nothing happens and else throws a Assertion Error
>>>
a = 4
>>>
assert a < 5
>>>
assert a> 5, "oops an Error"
Traceback
(most recent call last):
File "<stdin>", line 1, in ?
AssertionError:
oops an Error
Break and 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
>>>
for i in range(1,11):
... if i == 5:
... break
... print i
...
1
2
3
4
>>>
for i in range(1,11):
... if i == 5:
... continue
... print i
...
1
2
3
4
6
7
8
9
10
def
- defining a Function
In
order to define a function in python, we need to follow some syntax
1)
Function blocks begin with a keyword def
followed by function name and Parentheses(:)
2)
All Parameters or arguments needs to be placed in side the Parentheses.
3)
The first line in the function should be a Docstring, which tells us what this
function do
4)
Code blocks starts after the (:)
5)
A statement return [expression] exits a function, optionally passing back an
expression to the caller
Example
–
>>>
def myFucntion():
... """ This is My Sample
Function Doc String"""
... print "this is Sample Function"
...
>>>
myFucntion()
this
is Sample Function
del
- del is used to delete the reference to an object. Everything is object
in Python
>>>
a =5
>>>
print a
5
>>>
del a
>>>
print a
Traceback
(most recent call last):
File "<stdin>", line 1, in ?
NameError:
name 'a' is not defined
>>>
a = [ 1,2,3]
>>>
del a[2]
>>>
print a
[1,
2]
IN
:Member ship operators – The Membership operators are the ones that check
whether a String or Number is available in a Data Type or any other Type. This
“IN” operator is one of the most used one as
>>>
str1 ="i have a Lazy Dog"
>>>
str1
'i
have a Lazy Dog'
>>>
"dog" in str1
False
>>>
"Dog" in str1
True
>>>
list = [1,2,3,4,5]
>>>
'1' in list
False
>>>
2 in list
True
As
seen above the “IN” Operator can be used to find if an element exists in a Type
IS
- Identity Operators – The Identity operators can be used to check the memory
location and tell if both are equal. The “IS” Operator is used to perform the
operation of checking. This checks whether the values are same as well are the
data types.
>>>
i = 10
>>>
b = 20
>>>
if i is b:
... print "hai"
...
else:
... print "bye"
...
bye
>>>
i = 10
>>>
b = 10
>>>
if i is b:
... print "hai"
...
else:
... print "Bye"
...
Hai
Not
- There is another Variables called “Not” which can be used to check whether
they are not available or not
If
not a :
Print
“not available”
For
- A simple for construct would like this,
>>>
fruits = ["apple","mango","grape"]
>>>
for fruit in fruits:
... print fruit
...
apple
mango
grape
That
reads, for every element that we assign the variable fruit, in the list
fruits print out the variable fruit
Other
example looks as,
>>>
numbers = [1,10,20,30,40]
>>>
sum = 0
>>>
for number in numbers:
... sum = sum + number
... print sum
...
1
11
…..
While - The While loop tells to perform an Operation as long
as the condition defined is met. An basic example would look like this,
>>>
fruits =
["apple","mango","banana","grape","
raspberry"]
>>>
i = 0
>>>
while i < len(fruits):
... print fruits[i]
... i = i+1
...
apple
mango
banana
grape
raspberry
If - An if Statement consists of a Boolean expression
followed by one or more statements. Below is an example of the standard if
statement
>>>
var = 100
>>>
if (var == 100 ) : print "value us 100"
...
value
us 100
If-else : An If-else statement can be followed by an optional
else Statement which executes when the Boolean Expression is False. A snippet
of how the If-else works is shown below.
>>>
age = input("enter the age?")
enter
the age?20
>>>
if age<0:
... print "age is Less than 0"
...
elif age==10:
... print "age is equal to 10"
...
else:
... print "age is Greater than 10"
...
age
is Greater than 10
elif
- An Extension to the if-else statement which will check for the condition when
if case is bypassed. An example would be
>>>
age = input("enter the age?")
enter
the age?10
>>>
if age<0:
... print "age is Less than 0"
...
elif age==10:
... print "age is equal to 10"
...
else:
... print "age is Greater than 10"
...
age
is equal to 10
del
- Deletion - Python provides a feature which is not available in many high
level languages called “del”. Using this we can delete a reference to a number
object.
The
syntax of the del statement is − del var1[,var2[,var3[....,varN]]]]
You
can delete a single object or multiple objects by using the del statement. For
example −
del
var
Anonymous Functions - lambda - Python supports the creation of anonymous functions
(i.e. functions that are not bound to a name) at runtime, using a construct
called "lambda".
One
important thing to remember is that Lambda does not include a return statement
since it’s an expression that is retuned.
The
general format for lambda form is:
lambda
parameter(s): expression using the parameter(s)
An
example will be,
>>>
k= lambda y: y + y
>>>
k(30)
60
>>>
k(40)
80
except, raise, try - Exception
Handling
#!/software/python/2.7
def
run(num):
try:
r = 1/num
except:
print "Exception Raised"
return
return r
print
run(10)
print
run(0)
[djas999@vx181d
testing]$ python test1.py
0
Exception
Raised
None
Finally - finally is used with try…except block
to close up resources or file streams. Using finally ensures that the
block of code inside it gets executed even if there is an unhandled
exception.
finally is
for defining "clean up actions".
The finally clause is executed in any event before leaving
the try statement, whether an exception (even if you do not handle
it) has occurred or not.
Global - global is used to declare that a variable
inside the function is global (outside the function). If we need to read the
value of a global variable, it is not necessary to define it as global.
Pass
- pass is a null statement in Python. Nothing happens when it is executed.
It is used as a placeholder. Suppose we have a function that is not implemented
yet, but we want to implement it in the future. Simply writing,
def
function(args):
pass
We
can do the same thing in an empty class as well.
Return - return statement is used inside a function to
exit it and return a value. If we do not return a value
explicitly, None is returned automatically.
Class - A Class is a user-defined prototype for an object that
defines a set of attributes that characterize any object of the class. The
attributes are data members ie Class variables and instance variables, methods
accessed via a dot notation.
Creating Class
In
order to create a Class in Python we use the Class Keyword like,
class
Emp:
""" Common Base Class for
EMP"""
empCount = 0
def __init__(self,name,age):
self.name=name
self.age=age
empCount +=1
def disEmp(self):
print "Total Emp
are",Emp.empCount
def disDT(self):
print "Emp Details
are",self.name,self.age
Logical
Operators - and, or , not
Not
- Negation of a Condition ( not )
>>>
a =[ 1,2,3,4]
>>>
if 1 not in a:
... print "hai"
...
>>>
if 1 in a:
... print "hai"
...
Hai
>>>
not True
False
>>>
not False
True
and
- Or : Logical Operators
var
= "hello"
var1 = "mello"
if var =="hello" and var1 =="mello":
print "This is Implementation of and"
elif var == "hello" or var1=="mello":
print "This is a Implementation of Or"
else:
pass
var1 = "mello"
if var =="hello" and var1 =="mello":
print "This is Implementation of and"
elif var == "hello" or var1=="mello":
print "This is a Implementation of Or"
else:
pass
Yield - yield statement pauses the function saving all its
states and later continues from there on successive calls. yield is just like
return. It returns whatever you tell it to. The only difference is that the
next time you call the function, execution starts from the last call to the
yield statement.
As
an scenario, consider a case where you have a function which will return from 1
to 10. When you use yield we can get the numbers from 1 to 10 , yield will save
the state of the function that gave the number. So if that gave a number 5 now
, yield statement will save the state of function that it has to return 6 when
the same function was used at any time in the program.
With
– With keyword allows us to cleanly close the resources that are being
used. For example a classic example of opening a file , zipping the file can be
done using the file Operations but using With
keyword we can write the same thing as
with
open(file_path, 'r+') as f_in, gzip.open(file_path+".gz", 'wb') as
f_out:
f_out.writelines(f_in)
os.remove(file_path)
No comments :
Post a Comment