The Zen of Python (PEP-20)

The Zen of Python (PEP-20)

The PEP contains the index of all Python Enhancement Proposals which are known as PEPs. PEP numbers are assigned by PEP editors. Now somewhat you probably know what does it mean by “The Zen of Python (PEP-20)”.

Tim Peters introduced very interesting 20 new “guiding principles”. But only 19 principles have been officially written and accepted, which influences in Python programming language development. The last one- 20th principle, “for Guido to fill in” were not considered which was referred to Guido Van Rossum, the original author of the Python language.

Import this ?

Import this! What? Tim Peters says, just import this! It means importing “this” package – The Zen of Python theory! Go ahead and see the result by firing command “import this” on your python shell or command prompt.

The Zen of Python (PEP-20)

>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those!

Where is this.py?

You must have wondering from where this package is getting imported! You can easily find this! Since this is officially accepted, it is available with standard python.File location might be differ depending on your installation and operating system. You can see the details by using this command. Here is my this.py file situated.

 >>> this
  < module 'this' from 'C:\TekkieHead\Programs\Python\Python37\lib\this.py'>
 >>>

What is exactly inside this.py?

It should be exactly same lines written with print command, I assumed. But there is totally different content present in the this.py file, may be in different language! Have a look at it and help me to recognize this language in the comment box.Go to file location, write click and open (This.py) with IDLE or text or notepad++ or…

this.py
s = “””Gur Mra bs Clguba, ol Gvz Crgref
Ornhgvshy vf orggre guna htyl.
Rkcyvpvg vf orggre guna vzcyvpvg.
Fvzcyr vf orggre guna pbzcyrk.
Pbzcyrk vf orggre guna pbzcyvpngrq.
Syng vf orggre guna arfgrq.
Fcnefr vf orggre guna qrafr.
Ernqnovyvgl pbhagf.
Fcrpvny pnfrf nera’g fcrpvny rabhtu gb oernx gur ehyrf.
Nygubhtu cenpgvpnyvgl orngf chevgl.
Reebef fubhyq arire cnff fvyragyl.
Hayrff rkcyvpvgyl fvyraprq.
Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff.
Gurer fubhyq or bar– naq cersrenoyl bayl bar –boivbhf jnl gb qb vg.
Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh’er Qhgpu.
Abj vf orggre guna arire.
Nygubhtu arire vf bsgra orggre guna *evtug* abj.
Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg’f n onq vqrn.
Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.
Anzrfcnprf ner bar ubaxvat terng vqrn — yrg’f qb zber bs gubfr!”””
d = {}
for c in (65, 97):
for i in range(26):
d[chr(i+c)] = chr((i+13) % 26 + c)
print(“”.join([d.get(c, c) for c in s]))

If you are lazy to find location for this.py, write click and open with idle, etc. 

Here is the trick for you! 

print(this.s) command prints the text content of this.py file.

>>> print(this.s)

Lets play with this !

While going through the Zen of Python notes, I have got something very interesting which you might love it! May be its good idea for you to try same lines and come up with the new interesting lines, of course I would love to read from you!Here you go ! you-love-this

>>>import this
.
.
>>> love=this
>>> you=love
>>>
>>> love is love
True
>>> you is you
True
>>> love is you
True
>>> this is not you
False
>>> love is not you
False
>>> you is not love
False
>>> love is this
True
>>>

What is opposite of this? May be THAT !

Daniel Greenfeld come up with the sort of opposite theory of Zen of python called as The Anti-Zen of Python! This is exactly opposite of what Time Peter have introduced. Game of words!
Warning:
This is a joke. Don’t use these bits unless you want to be hated. :-p :-p

The Anti-Zen of Python

You can have a look at the principles on your shell by importing that using command “import that.” That package is not distributed with standard Python.If you still attempt to import that then you will get this error – ModuleNotFoundError: No module named ‘that’.You need to install that package using pip.

Install that !

Open command prompt/terminal and follow these instructions

Install that !!

$ pip install that
$ python
>>> import that

H:>pip install that
Collecting that
  Downloading https://files.pythonhosted.org/packages/64/72/12dc208c9086e2584f15f681fcd03c74179341d0295a6/that-1.0.7.tar.gz
Installing collected packages: that
  Running setup.py install for that ... done
Successfully installed that-1.0.7
You are using pip version 18.1, however version 19.0.3 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
H:>

Oops..! I’ve got the warnings to upgrade the pip comand version. Don’t worry, if you also get one. Let’s continue to upgrade it or you may skip this!

H:>python -m pip install --upgrade pip
Collecting pip
  Downloading https://files.pythonhosted.org/packages/d8/f3/413bab4ff08e1fc4828dfc59996d721917df25dceff/pip-19.0.3-py2.py3-none-any.whl (1.4MB)
    100% |████████████████████████████████| 1.4MB 6.4MB/s
Installing collected packages: pip
  Found existing installation: pip 18.1
    Uninstalling pip-18.1:
      Successfully uninstalled pip-18.1
Successfully installed pip-19.0.3
H:>

Import that !

>>> import that

The Anti-Zen of Python, by Daniel Greenfeld

Ugly is better than beautiful.
Implicit is better than explicit.
Complicated is better than complex.
Complex is better than simple.
Nested is better than flat.
Dense is better than sparse.
Line code counts.
Special cases are special enough to break the rules.
Although purity beats practicality.
Errors should always pass silently.
Spelchek iz fur loosers.
In the face of ambiguity, one guess is as good as another.
There should be many ways to do it.
Because only a tiny minority of us are Dutch.
Get things running, then fix them later.
If the implementation is hard to explain, it's enterprisey.
If the implementation is easy to explain, it won't take enough time to do.
Namespaces are too hard, just use "from module import *"!
>>>

Photo Credits: Pixeles ; References: Python PEP-20  The Anit-Zen Python

Python Object-Oriented Programming(OOP)

python oop

Python OOP

In this article we will go through the Python OOP Concepts. OOP is termed as Object Oriented Programming and it is distinguished based on various concepts such as objects, class and methods etc. There is one more type of language exists called as
Procedural Oriented Programing language(POP). You probably heard that most of
the expert started their career with C- language and this is a procedural Oriented Programming. 

There are many limitations and complexity with POP hence the new concept originated – Object Oriented Programming language(OOP) with its various useful features. OOP languages are very famous and used in almost all existing popular languages, also it is getting considered for new languages which are currently under development. 

The major need for developing such languages was to manage the ever-increasing size and complexity of programs.

Now question is, why OOP languages are so popular and why everybody liked to acquire those concepts. You will get to know in-and-out about OOPs features in this article – stay tuned!!

Python is an Object-Oriented Programming Language and here we will discuss OOPs concept by taking reference of simple python programs. Don’t worry, if you do not know Python.  It is not necessary to know python in advance to understand OOPs concept in general or OPPs with Python.

PYTHON OOP : Basic Concept

Any complex language starts with the simple concept irrespective of complexities
involved in that areas. There are few simple python OOP features but it is base of python programming models.

Python OOP features

1.  Class

2.     Object

3.     Abstraction

4.     Polymorphism

5.     Inheritance

6.     Encapsulation

Class

In simple
way, class is a grouping of data and its associated functions. Once a class has
been defined, we can create any number of objects associated with that class.

For example, Account_Number, Balance, Credit() and Debit() are the member of Class Bank. If Bank has been defined as a class, then the statement Bank-Balance , will create an object Balance belonging to the class Bank.

[table id=6 /]

Object

Object is an
instance of a class. In other words, Object is a way to access features of a
class. As described above a class contains the associated data and its function
but to access its features Objects play major role. 

Consider class
– Bank from above example and try to understand the power of object. You
already have defined class- Bank with associated data and functions to perform
credit and debit operations. The normal operation happening in bank system is
account holder debit some money from account or credit some money into account. 

Assume,
customer 1 has defined cust1 as an object of class Bank and customer 2 has
defined cust2 as an object of same class Bank.

Let’s try to credit some amount into customer 1’s account and debit some amount from customer 2’s account by accessing features of Class Bank through objects cust1 and cust2 respectively.

 
# Credit 1000 in customer-1 account
cust1.credit(1000)
# Debit 500 from customer-2 account
cust2.debit(500)

Abstraction

An abstraction is very important aspect to hide complexity or internal background
processes and represent essential features. To understand this concept more
clearly, take the same example of class Bank. 

In first two points, we have already seen credit and debit example while describing class and object. Observe those examples, you are just calling function by pointing
out correct class object with value. In this process you need not to know what is
happening inside when you are calling credit or debit functions. How and What process happening inside is hidden from you. 

This is
abstraction, where you only know the essential things to operate on banking
system without knowing the background details of actual complex calculations.

It gives flexibility
and simplicity to the users to use complex application knowing minimal required
things to operate on.

Polymorphism

In simple
words, A single function name can be used to handle different operations by
passing necessary arguments. This is something similar to a particular word
having several different meanings depending upon the context. 

For example,
you have a class shape, and you have to draw the shapes. But they draw
differently. Here, the “draw” behavior is polymorphic in the sense
and depends on the shape. So, the abstract “shape” concept does not
actually “draw”, but specific shapes (like circle or rectangle) have
a concrete implementation of the action “draw”.

PS-Function overloading is not supported in Python OOP.

Polymorphism
plays an important role in allowing objects having different internal
structures to share the same external interface. Polymorphism is extensively
used in implementing inheritance.

Inheritance

Inheritance
is the process of creating new class based on an existing class. In other words,
it is the process by which objects of one class acquired the properties of
objects of another classes. It supports the concept of hierarchical
classification.

The one whose properties are acquired is known as a base class or parent class and the new class is known as a derived class or child class.

Inheritance can be easily described with class computer. In the computer class we have defined all its accessories and features. Another class created for – Laptop by
inheriting its properties from class computer. In this case, Computer is the base or parent class and Laptop is the derived or child class.

Encapsulation

Encapsulation
is also an important feature of object-oriented programming language. The
wrapping up of data and function into a single unit (called class) known as
encapsulation. If you are creating class, you are doing encapsulation.

The data abstraction and encapsulation go hand-in-hand. An abstraction is used to hide internal details and show only functionalities, it can be only achieved through
encapsulation.

Photo Credits: Pixeles

Python Function Arguments

python function arguments

In python, you can define a generic function which can be used by passing arguments or parameters. Even we use built-in functions by passing its required arguments.

You might have seen print() function used since our first article where we have passed character string to print() function to print “Hello World” message.

Arguments

In python function topic, we have learned about how to define functions and calling it. In this article we will see what complications can encounters with python function if we don’t provide proper parameters to the function. Also, we will go through different types of function arguments.

Here is the simple example.

 
# Define python function
def Name(FirstName, LastName):
    print("First Name :", FirstName)
    print("Last Name :", LastName)
# Call python function with arguments
Name("Tekkie", "Head")

Output


>>> Name("Tekkie", "Head")
First Name : Tekkie
Last Name : Head
>>>

Observe this example carefully where we have provided all the required arguments while calling the Name() function. Let’s see what happens if we provide only one argument where we actually required two arguments.


 >>> Name("Tekkie")
Traceback (most recent call last):
  File "", line 1, in 
    Name("Tekkie")
TypeError: Name() missing 1 required positional argument: 'LastName'
>>>

Or try to call Name() function without any argument.


>>> Name()
Traceback (most recent call last):
  File "", line 1, in 
    Name()
TypeError: Name() missing 2 required positional arguments: 'FirstName' and 'LastName'

There are mainly four types of function arguments in python.

1. Python Required Arguments

In this type of argument, you need to provide same number of arguments which are necessary for that function and with its exact datatypes. 

Observe this example where addition() function expect two numeric arguments and see what happens with different test cases.

 
# Define function
def addition(a,b):
    result=a+b
    print("Addition result :", result)

Tast Cases & its Result:

addition()

TypeError: addition() missing 2 required positional arguments: ‘a’ and ‘b’

>>>

addition(10, “Character_String”)

result=a+b

TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

>>>

addition(10, 20)

Addition result : 30

>>> 

2. Python Default Arguments

In this type of argument, the parameter values are exactly mapped one-to-one to the variables in the function.

Here is an example of default argument type where we have defined default value for variable – b and passing the value for variable – a. Also observe, what happens if you still provide value for variable – a which you have already defined.

 
# Define function
def addition(a,b=0):
    result=a+b
    print("Addition result :", result)

addition(10)

Addition result : 10

>>>

addition(10, 20)

Addition result : 30

>>>

In case-1, you have just provided one argument which are mapped to first variable –  a and default specified value taken for variable b    (i.e. b=0), hence we got result, 10+0=10

In case-2, we have tried to pass two arguments. first argument mapped to first variable (i.e. a) likewise second argument mapped to second variable (i.e. b) by overwriting its default value zero. Hence we got addition result, 10+20=30

You need to very careful when you define some value for variable in function but at the same time trying to pass value for same variable while calling the function.

3. PYTHON Keyword ARGUMENTS

As discussed in the first two argument types, when we call function with values, these values get assigned to the arguments according to its variable position.

In above example first value always assigned to first variable – a and second value assigned to second variable – b.

Python gives you flexibility to assign values for arguments by specifying its variable name. You could call this function as addition(a=10, b=20) or addition(b=20, a=10). In both the cases you will get the same results.

 
def addition(a,b):
    result=a+b
    print("Addition result :", result)

addition(a=10, b=20)

Addition result : 30

>>>

addition(b=20, a=10)

Addition result : 30

>>>

Also, there is possibility to call function in a mixed way – passing default arguments along with keyword arguments but here you need to keep in mind one important rule.

Rule: When you are calling a function, you must provide all the positional(default) arguments first, then you can pass keyword arguments.

Having a positional (default) arguments after keyword arguments can result into an error. Here are few examples.

addition(10, b=20)

>>> addition(10, b=20)

Addition result : 30

>>>

addition(b=10, 20)

>>> addition(b=10, 20)

SyntaxError: positional argument follows keyword argument

>>>

Here is one very interesting scenario – In case if you attempt multiple arguments refer to same variable then it will result into an error.

addition(10, a=20)

Traceback (most recent call last):

  File “<pyshell#15>”, line 1, in

  addition(10, a=20)

TypeError: addition() got multiple values for argument ‘a’

Here, you have already provided value for variable – a by passing position argument (10) but still you have provided value for variable- a again through keyword argument (a=20) and it ends up with an error.


 

4. Variable Length or Arbitrary Arguments

If you are not sure how many argument values to be passed to the function, then these arbitrary arguments come in picture by defining its variable argument length.

Mostly such type of argument used where we are passing values from outside to the loop statements.

The asterisk * used with variable name (*a) to decide its variable argument length.


def addition(*a):
    sum=0
    for var in a:
        sum=sum+var
    print("Addition Result :", sum)
# call function
addition(10,20,30,15,20)

Output


Addition Result : 95
>>>

In this example we have called function with multiple arguments.  These argument gets wrapped into tuple and values gets assigned to it. Inside function we have used for loop to retrieve those arguments back.

An example which describes combination of default argument and arbitrary argument.


def addition(b, *a):
    sum=0
    for var in a:
        sum=sum+var
    print("Addition Result :", sum)
    print("Value of variable b :", b)
# call function
addition(10,20,30,15,20)

Above program gives following result – 


Addition Result : 85
Value of variable b : 10
>>>

Here, we have assigned value 10 for variable – b and rest arguments are assigned for variable – a and it retrieved back further with for – loop, hence we got the final result – 85

Python Define Functions

python define function

What are Python Functions?

In the python programming context, function is a named collection of python statements combined together to perform specific task. Python def keyword is used to define the function in python. It is a package of generic python code which you can be used whenever required in your code.

There are many built in functions available in the python. Also, there are possibility to create new customised, user written functions in python using python def keyword.

Built-in Function

Python built-in functions are already predefined into python standard library hence you don’t need to import any modules to use built-in functions.

You have already seen many python functions since my first article –What is python? Starting from basic program to print “Hello World” to more complicated and lengthy codes. You might have written “print” statement thousands of time, but did you ever wonder how print – statement works?

Similarly, there are other functions we use regularly such as – input, eval, int, float, range, and type. These are the common built-in functions included in the python standard library hence can be available at any time. 

Apart from this we do have many other built in functions in python but to use those functions you need to import related modules in the beginning of your code.

Use defined function

The function we define /creates by ourselves to perform any specific task known as user defined function. Python def keyword is used to define user defined functions.

The whole concept of functions revolves around two things – first, how you define / write your function and second, how and where you call that function by supplying necessary parameters to the function.

Syntax:

 
#define your python function (python def Keyword)
def FunctionName(parameters) 
	. . . . . . . . . 
	. . . . . . . . .
#call python function
def FunctionName(parameters)

Try to understand simple python function – show() to display some predefined text message whenever this function gets called in the code.

 
#define show() function
def show():
    print("Show function executed")
#call show() function
show()



Python_Functions.py


Show function executed
>>>

Output

Observe this example – show() is your user defined/created function but inside show() function we are calling built-in print() function. 

Now we know when we call show function, it will execute lines of code written inside the function. In a similar way, when we are calling print() function – some sort of python code executes which is available in the python standard library. 

There are many generic codes already written in python and imported into python standard library. In function irrespective of its types- either built-in or user defined, there are some rules needs to be followed as per logic written inside that function in ordered to reuse the code.

Example:

Python Function to add two numbers

This example demonstrates simple python function to add two numbers by taking inputs from user.

 
#definefun function - add()
def add(a,b):
    result=a+b
    print("Addition of two numbers :", result)
#take input from user
a=int(input("Enter First Number :"))
b=int(input("Enter Second Number :"))    
#call add() function to perform addition.
add(a,b)

Python_add.py


Show function executed
Enter First Number :25
Enter Second Number :100
Addition of two numbers : 125
>>> 

Output

Python try except and finally

Python try except and finally - exceptional handling

An exception is a very known to every programmer! Afterall we most of the time seems to be playing with this keyword. Python try except and finally statements allow you to handle these exceptions.

Python exception or error doesn’t indicate that there is always something wrong with the logic or algorithm. 

There are some circumstances where your program is absolutely correct, still you encounter run-time error that situation is known as an EXCEPTION.

At this point, our run time errors resulted in a termination of program execution. Rather terminating the program execution, program could detect the error before hand and handle it in a very smart way, that concept is called as Exceptional handling.

An Exceptional handling is a standard python mechanism allows programmers to deal with the run-time errors. 

Examples of exceptional errors: integer division by zero, attempting to convert a non-number to an integer, accessing a list with an out-of-range index, and using an object reference set to None.

Few common python exceptions are described here but if you want to go through all the exception list then visit this page Python built-in Exception.

PYTHON EXCEPTIONS

1. ZeroDivisionError: division by zero

You have a program where you are doing some calculations. You have defined two integer variables and assigned value to them. Now you are trying to attempt division operation.

N1=int(input(“Enter first Number – N1 :”))

N2=int(input(“Enter Second Number – N2 :”))

Result=N1/N2

print(“Result :”, Result)

Your code is absolutely perfect, and it will give you division answer but what will happen if user enters 0 value for variable N2! Always remember, you never have a control over an end user. 

In this case program execution will be terminated with error – ZeroDivisionError: division by zero

Output

Enter first Number – N1 :100

Enter Second Number – N2 :0

Traceback (most recent call last):

File “C:/Users/Python37/exceptional_handling.py”, line 3, in

Result=N1/N2

ZeroDivisionError: division by zero

>>>

2. ValueError: invalid
literal for int()

To continues with same above example where you expect user should enter integer number(digits) but consider user has entered some random characters or numbers in a word (say five instead of 5) for variable N1 then WHAT? It will throw this exception – ValueError: invalid literal for int()

Enter first Number – N1 :five

Traceback (most recent call last):

  File “C:/Users/Python37/exceptional_handling.py”, line 1, in <module>

    N1=int(input(“Enter first Number – N1 :”))

ValueError: invalid literal for int() with base 10: ‘five’

>>> 

3. OverflowError:
integer division result too large for a float

To continues with the same example, now user has entered very large number for variable N1. Observe what happened with your result – error  OverflowError: integer division result too large for a float

python exception handling OverflowError

Looking for Solution?

Yes, it is absolutely possible to write a code to avoid such kind of errors in python like other programming languages, but python has unique features which you can apply.

Python has built in conditional execution structure to handle the situation where you might encounter expected or unexpected run-time errors.

1.    Try

2.    Except

3.    Else

4.    Finally

Python Try and except

try/except block to be added where you think potential exception can occur in your program. 

Syntax:

try:

                  #It contains code that might raise an exception.

except:

                  #It contains code to execute Only when try block raise an exception.

Back to our previous example and we will see how it works. Now you know where possible exception error can come in our example so try to add try/except block into it.

Firstly, we will try display text message to the user so they can understand what went wrong! The technical error user might not understand so let’s change default error message with simple plain English text.

try:

    N1=int(input(“Enter first Number – N1 :”))

    N2=int(input(“Enter Second Number – N2 :”))

    Result=N1/N2

    print(“Result :”, Result)

except ValueError:

    print(“Oops!! Seems you have entered invalid Number”)

except OverflowError:

    print(“Oops-ERROR!! Result value seems to be too large to display”)

print(“Program execution continues….”)

Scenario #1

Enter first Number – N1 :five

Oops!! Seems you have entered invalid Number

Program execution continues….

>>> 

Scenario #2

python try except exception handling

Summary

  • Program execution doesn’t terminate when you use try except block and exception occurs.
  • An except block doesn’t execute unless try block don’t raise an exception.
  • Multiple except block can be written for one try block.

Python else

If try block raise an exception, then only except block gets executed otherwise else block will be executed.

In other words, else block only executed when try block do not raise an exception.

try:

    N1=int(input(“Enter first Number – N1 :”))

    N2=int(input(“Enter Second Number – N2 :”))

    Result=N1/N2

    print(“Result :”, Result)

except ValueError:

    print(“Oops!! Seems you have entered invalid Number”)

else:

print(“Division Successful!”)

print(“Program execution continues….”)

Python finally

finally block always executes after try/except block execution. It does nothing extraordinary, just creates the space for you to execute something after try/except block.

try:

    N1=int(input(“Enter first Number – N1 :”))

    N2=int(input(“Enter Second Number – N2 :”))

    Result=N1/N2

    print(“Result :”, Result)

except ValueError:

    print(“Oops!! Seems you have entered invalid Number”)

finally:

print(“Executing finally…block!”)

print(“Program execution continues….”)

So far, we have seen basic use of try/except, else and finally block in python. Mostly it is being used with the conditional loop statements and allow users to try one more time – with proper message on screen when they enter wrong values, for instance.

Example

Write a program to demonstrate an
exceptional handling case with Loop statements!

In this example users can input any small integer value less than 100. They can enter number greater than 100 to complete the program execution. This code will not fail or terminate the execution if try block raise ValueError exception.

x = 0

while x < 100:

    try:

    # I hope the user enters a valid Python integer!

        x = int(input(“Please enter small integer Number: “))

        print(“x =”, x)

    except ValueError:

        print(“Oops!! Input cannot be parsed as an integer – Please try again”)

print(“Program finished”)

 

Output

Please enter small integer Number: 25

x = 25

Please enter small integer Number: 50

x = 50

Please enter small integer Number: five

Oops!! Input cannot be parsed as an integer – Please try again

Please enter small integer Number: 5

x = 5

Please enter small integer Number: 200

x = 200

Program finished

>>> 

 

Read More: Python raise Keyword

Python raise keyword

python raise keyword

Python raise keyword. In python we can raise exception by using raise keyword. We have already gone through detailed overview on in-built Python exceptions and how it is being handled with python try except & finally statements.

All these exceptions are default and python interpreter decide when to raise the exception but WHAT if you want to raise an exception?

Python raise

Python gives your flexibility to raise exception whenever you want in the program. It is very powerful keyword and having unique features in it.

Mostly people are using python raise – keyword in conditional block to decide when and where to raise an exception.

Syntax:

raise  <exception>

When you specify raise keyword in your code and the moment program execution reaches that point – immediately exception is being raised by skipping further statements. 

An interpreter doesn’t see, whether do you really have an error in your code or not. It simply raises an exception as per specified exception name.

Example

Python_raise.py

var=10

print(“Var= “, var)

raise ValueError 

print(“Program execution continues….”)

Output:

Var=  10

Traceback (most recent call last):

  File “C:/Users/Documents/Python_raise.py”, line 3, in <module>

    raise ValueError

ValueError

>>> 

Python raise keyword most often used in try block for various reasons for instance, to cross verify whether exceptions are properly getting raised and check its execution flow, to avoid the program execution termination, etc.

python_raise.py

try:

    var=10

    print(“Var= “, var)

    raise ValueError

except ValueError:

    print(“Oops!! Value error raised “)  

print(“Program execution continues….”)

 

Output

Var=  10

Oops!! Value error raised

Program execution continues….

Use raise keyword in try except

It is very effective way to check whether your exceptional handling code – try/except block working properly without involving end user. 

If there would be chances of an exception can occur in your code where you already applied, try/except blocks but you want to test it then you can add raise keyword there.

Observe this example – We are performing division of two numbers by taking inputs from users.

In this case we know ValueError exception can occur if user enter non-digit number. We have already seen this example here.

Now we could test this exception by raising ValueError exception manually in the code, irrespective of user inputs. 

Python_raise.py

try:

    N1=int(input(“Enter first Number – N1 :”))

    N2=int(input(“Enter Second Number – N2 :”))

    Result=N1/N2

    print(“Result :”, Result)

    raise ValueError

except ValueError:

    print(“Oops!! Seems you have entered invalid Number”)

print(“Program execution continues….”)

Note this result – we have entered correct input values still ValueError exception encountered due to raise keyword specified in try block code.

Output

Enter first Number – N1 :100

Enter Second Number – N2 :12

Result : 8.333333333333334

Oops!! Seems you have entered invalid Number

Program execution continues….

>>> 

 

Read More: Python try except and finally

Python Exception and Errors

Python Exception and error

python error & built-in exceptions

There are many built-in python exception an interpreter raises whenever the extraordinary situation encounters in the program. 

People often gets confused with error and exception as both looks very similar but these two operates in a very different way.

Python Error

Error encounters in the program when something wrong with the code. In error situation, program execution gets terminated and there is no way to handle this case unless you don’t fix the error.

Most common error observed with programmer is – syntax error. Observe this example to understand how error looks like in python.

This example demonstrates syntax error with if statement. You can see, semicolon is missing in if statement.

var=100

if var>10

    print (“Variable – var=”, var)

  File “C:/Users/Documents/Python_raise.py”, line 2

    if var>10

            ^

SyntaxError: invalid syntax

Python built-in Exceptions

The built-in exceptions are raised by interpreter or built-in functions whenever an extraordinary error situation occur in the code. 

When an exception encounter in your code, program execution will get terminated unless you don’t handle specific situation in your code. HOW to handle an exception? Visit this page – Python try/except and finally Statements.

There is also possibility to raise built-in exception manually by using raise keyword. Visit this page to learn more about Python raise keyword.

[table id=1 /]

Read More : Python try except and finally statements.

Python Loop Control/Jumping Statements- break, continue & pass

python loop control or jumping statements break continue and pass

Apart from common control statements – IF-ELSE, WHILE-loop, FOR-loop, etc we do have something in python called as Loop Control or jumping statements. 

There are three such statements used for special purposes which is standard control statements can’t perform effectively.

     1. BREAK

     2. CONTINUE

     3. PASS

Each statement has its own features and will be very useful to control your program execution. It gives you flexibility to re-route program execution to achieve the desired result or build a more generic and powerful solution. 

Follow each statement carefully to understand its features. 

1. break

Sometimes you are in a situation where you want to skip a part of loop  (in WHILE or FOR – loop) from execution and continue with the next iteration. You can use break or continue statements to handle such situations.

 

You are now already known to FOR loop- range control statement hence we will take the same example to demonstrate break statement.

Read more about for-loop

Example 1: We will try to break the for-loop as soon as your program reach to count 5 in a range value of 0 to 10 and print the values to understand execution better.

Example 2: We will try to break the for-loop as soon as your program reach found the character “t” in a string(word) – “P-y-t-h-o-n” and print the characters to understand execution flow better.

#Example 1

for i in range(0, 10):

    if i==5:

        break

    print(“Range Value :”, i)

 

#Example 2

for var in ‘Python’:

    if var == ‘t’:

        break

    print (“Current Letter :”, var)

 

Output:

Range Value : 0

Range Value : 1

Range Value : 2

Range Value : 3

Range Value : 4

Current Letter : P

Current Letter : y


 

2. continue

The continue statement in python allows you to skip further statements for that specific iteration and send control back to top, beginning of loop. 

It can be used in the WHILE or FOR loops.

Let’s modify above examples by just replacing break keyword with continue keyword and see the result.

#Example 1

for i in range(0, 10):

    if i==5:

        continue

     print(“Range Value :”, i)

 

#Example 2

for var in ‘Python’:

    if var == ‘t’:

        continue

    print (“Current Letter :”, var)

      The output of example 1 with continue keyword – It will print all the range values (0 to 10) except 5.

      The output of example 2 with continue keyword – It will print all the characters (P-y-t-h-o-n) except “t”

Range Value : 0

Range Value : 1

Range Value : 2

Range Value : 3

Range Value : 4

Range Value : 6

Range Value : 7

Range Value : 8

Range Value : 9

Current Letter : P

Current Letter : y

Current Letter : h

Current Letter : o

Current Letter : n

3. pass

The pass command in python used where you don’t want to execute any piece of code in the loop. It allows you to skip the block of code from execution. 

It is mostly used in the development phase of your program as you may specify pass statement where you feel possibilities that code execution can go in the flow and you want to nullify the block. 

Of course, you can track all your pass statements by adding print statement under pass block with appropriate comment.

Let’s discuss same examples – 

Example 1: If you want to pass the block of code when counter or range value reach at 5 and everything else should print as-is.

Example 2: If you want to pass the block of code when character “t” found in the string (word) “P-y-t-h-o-n” and everything else should be printed as-is.

#Example 1

for i in range(0, 10):

    if i==5:

        pass

        print(“pass block for range value(5)”)

    print(“Range Value :”, i)

print(“Good bye- Example 1”)

 

#Example 2

for var in ‘Python’:

    if var == ‘t’:

        pass

        print(“pass block for range value(t)”)

    print (“Current Letter :”, var)

print(“Good bye- Example 2”)

Output:

Range Value : 0

Range Value : 1

Range Value : 2

Range Value : 3

Range Value : 4

pass block for range value(5)

Range Value : 5

Range Value : 6

Range Value : 7

Range Value : 8

Range Value : 9

Good bye- Example 1

Current Letter : P

Current Letter : y

pass block for range value(t)

Current Letter : t

Current Letter : h

Current Letter : o

Current Letter : n

Good bye- Example 2

Read More: Python IF-ELSE   For-Loop  While-Loop