TIME NOW
World current time now,
CALENDAR
Calendar monthly, yearly
login CONVERT LENGTH
login CONVERT TEMPERATURE
login DICTIONARIES, LISTS
login SCIENCE EDUCATION RELIGION
login WORK CALCULATOR
login CALCULATE LIFE

Python 3 programming language, learn python, tutorial

Previous articlePage bottomNext article  ALL TOPICS

Python 3. Error handling

 1. Syntax error. Source:
while True print('Hello world')

Error:
File "hello.py", line 1
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax

There is no error:
while True: print('Hello world')

2. Other errors:
a)
print (10 * (1/0))

b)
print (4 + meters*3)

c)
print ('2' + 2)

2a. Common errors:

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

NameError: Raised when a local or global name is not found. This applies only to unqualified names. The associated value is an error message that includes the name that could not be found. No function name.

3. Handling errors. Syntax is OK, but not valid number:
while True:
    try:
        x = int(input
("Please enter a number: "))
        break
    except
ValueError:
        print("Oops!  That was no valid number.  Try again...")

4. Handlers:
https://docs.python.org/3/library/exceptions.html#KeyboardInterrupt

sys.exc_info() - This function returns a tuple of three values that give information about the exception that is currently being handled.
raise -  This function re-raise the exception.
import sys
 
try:
    # 1 no file
    f = open('nofile.txt')
    s = f.readline()
 
    # 2 no module
    import nomodule
 
    # 3 bad data
    i = int(s.strip())
 
except OSError as err:
    print("OS error: {0}".format(err))
 
except ValueError:
    print("Could not convert data to an integer.")
 
# Uncomment
#except ModuleNotFoundError:
#    print("No module")
# Uncomment: raise error
#    raise
 
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise
 
print ("END")

4a. Module reload. Python versions 2 and 3, you can use the following:
try:
    reload  # Python 2.7
    print (1)
except NameError:
    try:
        from importlib import reload  # Python 3.4+
        print (2)
    except ImportError:
        from imp import reload  # Python 3.0 - 3.3
        print (3)

5. With else. sys.argv is a list in Python, which contains the command-line arguments passed to the script. 
else clause is better than try clause because it avoids accidentally catching an exception. File is run with arguments: hello.py a b:
import sys
for arg in sys.argv[1:]:
    try:
       
f = open(arg, 'r')
    except IOError:
        print('cannot open', arg)
    else:
        print
(arg, 'has', len(f.readlines()), 'lines')
        f.close()

File has one key -r, which deletes content of listed files.
import sys

# print ("\n", sys.argv, "\n")


# -r = remove content (empty file)
# python file.py -r workfile nofile
# python file.py workfile nofile

if (sys.argv[1]=='-r'):
    index=2
    command='w'
else:
    index=1
    command='r'
    
for
arg in sys.argv[index:]:
    try:
       
f = open(arg, command)
    except:
       
print('cannot open', arg)
    else:
        if
( command != 'w' ):
            print(arg, 'has', len(f.readlines()), 'lines')
        else:
            print (arg,"emptied")
        f.close()

###
### task
###

# deal with "IndexError"; use try, except
# add -a operation, which adds record (new line) "test test test" to files.

6. With function:
def this_fails():
    x = 1/0

try:
    this_fails()

except ZeroDivisionError as err:
    print('Handling run-time error:', err)

7. The raise statement allows the programmer to force a specified exception to occur. For example:
raise NameError('HiThere')
 
try:
    raise
NameError('HiThere')
except NameError:
    print('An exception flew by!')
    raise

8. Execute after error:
try:
    raise
KeyboardInterrupt
finally:
    print
('Goodbye, world!')

9. Lets try all cases of the function:
def divide(x, y):
    try:
       
result = x / y
    except ZeroDivisionError:
        print("division by zero!")
    else:
        print
("result is", result)
    finally:
        print
("executing finally clause")

divide(2, 1)

# divide(2, 0)

# divide("2", "1")

10. Predefined Clean-up Actions. File is not closed. Problem with memory - lack of memory:
for line in open("myfile.txt"):
    print(line, end="")

File is closed automatically:
with open("myfile.txt") as f:
    for line in f:
        print(line, end="")
After the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines. 

Task 1. 
Ip address file ip.log:
10.0.0.1 320 x
188.1.1.1 10 x
199.1.1.1 5 
199.1.5.5 1

Create module and demonstration: data view and operations - delete record, add record, sort file, mark/unmark IP, edit record, reset count to zero. Create functions:
  1 | 10.0.0.1    |  320 | x
  2 | 188.1.1.1   |   10 | x
  3 | 199.1.1.1   |    5 |    
  4 | 99.1.5.5    |      |

Delete (d1), add (a) , sort according field and save to file (s1), mark/unmark x (m1), edit ip (e1), reset counter (r1):

Please use error handlers (try , except). For sorting please use this example, (number sorting):
list = [['G', 10], ['A', 22], ['S', 1], ['P', 14], ['V', 13], ['T', 7], ['C', 0], ['I', 219]]

print (sorted(list, key=lambda x: -x[1]))

or:
from operator import itemgetter

sort = [['c', 2], ['d', 1], ['a', 9]]

print (sorted(sort,key=itemgetter(0)))
print (sorted(sort,key=itemgetter(1)))

-- 
Previous articlePage topNext article  ALL TOPICS



 Use username: Guest, Anonymous, Programmer






QUOTES:
Failure is the tuition you pay for success.
Walter Brunell
At the touch of love, everyone becomes a poet.
Plato
Whoever cares to learn will always find a teacher.
German proverb