miércoles, 14 de febrero de 2018

Try and Except in Python


Earlier I wrote about Errors and Exceptions in Python. This post will be about how to handle those. Exception handling allows us to continue our program (or terminate it) if an exception occurs.

Error Handling

Error handling in Python is done through the use of exceptions that are caught in 
try blocks and handled in except blocks. 

Try and Except

If an error is encountered, a try block code execution is stopped and transferred
down to the except block. 

In addition to using an except block after the try block, you can also use the
finally block. 

The code in the finally block will be executed regardless of whether an exception
occurs.

Raising an Exception

You can raise an exception in your own program by using the raise exception 
[, value] statement. 

Raising an exception breaks current code execution and returns the exception
back until it is handled.

Example

A try block look like below
try:
    print "Hello World"
except:
    print "This is an error message!"

Exception Errors

Some of the common exception errors are:

IOError
If the file cannot be opened.

ImportError
If python cannot find the module

ValueError
Raised when a built-in operation or function receives an argument that has the
right type but an inappropriate value

KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or Delete)

EOFError
Raised when one of the built-in functions (input() or raw_input()) hits an
end-of-file condition (EOF) without reading any data

Example

Let's have a look at some examples using exceptions. 
except IOError:
    print('An error occured trying to read the file.')
    
except ValueError:
    print('Non-numeric data found in the file.')

except ImportError:
    print "NO module found"
    
except EOFError:
    print('Why did you do an EOF on me?')

except KeyboardInterrupt:
    print('You cancelled the operation.')

except:
    print('An error occured.')

There are a number of built-in exceptions in Python. 
http://www.pythonforbeginners.com/error-handling/python-try-and-except

domingo, 4 de febrero de 2018

while True:

#!/usr/bin/env python

import sys


while True:

    n = raw_input("Please enter your 'skill':")


    if n.strip()== "php" :

       print("you re a web developer")

    if n.strip()== "exit" :

      print("Good bye !")

      sys.exit()

    else:

       print("you re not a web developer")


While loops

Usage in Python

  • When do I use them?
While loops, like the ForLoop, are used for repeating sections of code - but unlike a for loop, the while loop will not run n times, but until a defined condition is no longer met. If the condition is initially false, the loop body will not be executed at all.
As the for loop in Python is so powerful, while is rarely used, except in cases where a user's input is required*, for example:
n = raw_input("Please enter 'hello':")
while n.strip() != 'hello':
    n = raw_input("Please enter 'hello':")
However, the problem with the above code is that it's wasteful. In fact, what you will see a lot of in Python is the following:
while True:
    n = raw_input("Please enter 'hello':")
    if n.strip() == 'hello':
        break
As you can see, this compacts the whole thing into a piece of code managed entirely by the while loop. Having True as a condition ensures that the code runs until it's broken by n.strip() equaling 'hello'.

  • Another version you may see of this type of loop uses while 1 instead of while True. In older Python versions True was not available, but nowadays is preferred for readability.
  • https://wiki.python.org/moin/WhileLoop

viernes, 2 de febrero de 2018

python classes basic

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'
x = MyClass()
print(x.f())




class Dog:

    kind = 'canine'         # class variable shared by all instances

    def __init__(self, name):
        self.name = name    # instance variable unique to each instance
d = Dog('Fido')
print(d.name)
print(d.kind)
e = Dog('Boby')
print(e.name)
print(e.kind)