Python programming Quick Start Chapter 1 practical project reference answers, python Quick Start

Source: Internet
Author: User

Python programming Quick Start Chapter 1 practical project reference answers, python Quick Start

 

This chapter describes how to debug the python program. When the program has bugs or exceptions, how can we debug the code to find out the problems. In fact, when we practice in the previous chapters of this chapter, we will encounter various errors and exceptions, at first, print statements were used to output and debug the code without knowing where the program went wrong. Yes, print is also a tool for debugging code. It is intuitive and simple, and has some disadvantages. It is also troublesome to delete the code after debugging, this chapter introduces assert, logging, and various debugging tools.

First, let's review python exceptions.

I. Common exception types in python

 

Exception name Description
BaseException All abnormal base classes
SystemExit Interpreter request to exit
KeyboardInterrupt User interrupted execution (usually input ^ C)
Exception Base class with regular errors
StopIteration The iterator does not have more values.
GeneratorExit Generator exception to notify exit
StandardError All base classes with built-in standard exceptions
ArithmeticError Base classes with incorrect numeric calculation
FloatingPointError Floating Point Calculation Error
OverflowError The value operation exceeds the maximum limit.
ZeroDivisionError Except (or modulo) zero (all data types)
AssertionError Assertion statement failed
AttributeError The object does not have this property.
EOFError No built-in input, reaching the EOF tag
EnvironmentError Operating System Error base class
IOError Input/Output operation failed
OSError Operating System Error
WindowsError System Call failed
ImportError Import module/object failed
LookupError Base class for invalid data query
IndexError This index is not found in the sequence)
KeyError The ing does not contain this key.
MemoryError Memory overflow error (not fatal for Python Interpreter)
NameError Object not declared/initialized (no attribute)
UnboundLocalError Access uninitialized local variables
ReferenceError Weak reference attempts to access garbage collection objects
RuntimeError General running errors
NotImplementedError Unimplemented Methods
SyntaxError Python syntax error
IndentationError Indentation Error
TabError Mix Tab and Space
SystemError General interpreter system error
TypeError Operation that is invalid for the Type
ValueError Invalid parameter passed in
UnicodeError Unicode errors
UnicodeDecodeError Unicode decoding error
UnicodeEncodeError Unicode Encoding Error
UnicodeTranslateError Unicode Conversion error
Warning Warning base class
DeprecationWarning Warning about discarded features
FutureWarning Warning about future semantic changes in Construction
OverflowWarning Old warning about automatic upgrade to long (long)
PendingDeprecationWarning Warning that features will be discarded
RuntimeWarning Warning of suspicious running behavior (runtime behavior)
SyntaxWarning Warning of suspicious syntax
UserWarning Warning generated by user code

 

Ii. python exception handling

The complete statement for handling exceptions in python is as follows: Not every statement in the program must be used in combination.

 

try:
    try_suite
except Exception1,Exception2,...,Argument:
    exception_suite
......   #other exception block
else:
    no_exceptions_detected_suite
finally:
    always_execute_suite

For detailed usage, see:

python2:http://www.runoob.com/python/python-exceptions.html

python3:http://www.runoob.com/python3/python3-errors-execptions.html

Iii. Throw an exception

Throw an exception and use the raise statement.

Syntax: raise Exception ('string of error information ')

If this statement runs in interactive mode, an error is reported and a string in the Exception function is returned. Generally, raise statements are used in functions. In the code that calls this function, try and retry t statements receive exception functions as parameters in the retry t statement.

except Exception as err:

      print(‘An exception happened:’ + str(err)

4. the traceback module uses the traceback module to track exceptions and obtain more detailed error information. In fact, if the program does not handle exceptions, but the exception does exist, from the information output on the screen, we will all look at the detailed error information, including which line of error, what error, and so on. This should be the information returned by the traceback module, but python itself throws an exception.

In interactive mode, import the traceback module first and view the help information of traceback through help.

import traceback

help(traceback)

2 common functions

Format_exc () returns a string, and print_exc () is printed directly.

5. assert

Use the assert statement for check. If the check fails, an exception is thrown.

Syntax:

Assert condition, 'exception information'

For example:

In [16]: p = 1

In [17]: assert p==0,'error'
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-17-11c0bd0cc9d4> in <module>()
----> 1 assert p==0,'error'

AssertionError: error

6. logging Log Module

The logging module of Python provides a common log system for third-party modules or applications. This module provides different log levels and records logs in different ways. There are 5 levels in total.

Level Log Functions Description
DEBUG Logging. debug () Minimum level for small details. Usually you care about this information only when diagnosing the problem.
INFO Logging.info () Used to record general event information in the program or to confirm that everything works properly
WARNING Logging. warning () Used to indicate possible problems. It does not stop the program from working, but may
ERROR Logging. error () Used to record errors. It causes the program to fail to do something.
CRITICAL Logging. critical () The highest level. Used to indicate a fatal error. It causes or causes the program to stop completely.

Syntax:

In [18]: import logging

In [19]: logging.basicConfig(level=logging.debug,format='%(asctime)s - %(levelname)s - %(message)s')

In [20]: logging.debug('some debugging details')
2017-04-28 23:36:39,795 - DEBUG - some debugging details

Format defines the order, structure, and content of the final log information.

% (Name) s Logger name
% (Levelname) s Log Level in text format
% (Message) s user-Output message
The current time in the string format of % (asctime) s. The default format is "16:49:45, 896 ". The comma is followed by a millisecond
% (Levelno) s Log Level in digital form
% (Pathname) s indicates the complete path name of the module that calls the log output function.
% (Filename) s name of the module that calls the log output function
% (Module) s calls the module name of the log output function
% (FuncName) s name of the function that calls the log output function
% (Lineno) d code line in which the statement that calls the log output function is located
% (Created) f current time, expressed by floating points of time in UNIX standard
% (RelativeCreated) d Number of milliseconds since Logger was created when the log information is output
% (Thread) d thread ID. Not possible
% (ThreadName) s thread name. Not possible
% (Process) d process ID. Not possible

Disable logs

In [21]: logging.disable(logging.debug)

Write logs to files

In [22]: logging.basicConfig(filename='mylog.txt',level=logging.debug,format='%(asctime)s - %(levelname)s - %(message)s')

7. Answers to practical projects

#!/usr/bin/env python3.4
# debug.py
# create by mfyang 2017-04-28
import random
import logging
logging.basicConfig(level=logging.DEBUG,format=' %(asctime)s - %(levelname)s -%(message)s')
#logging.disable(logging.DEBUG)
logging.debug('start of program')
guess = ''
while guess not in ('heads','tails'):
    print('Guess the coin toss! Enter heads or tails:')
    guess = input()
    logging.debug('you input is:' + str(guess))
toss = random.randint(0,1)
coinresult = ''
if toss == 0:
    coinresult = 'tails'
if toss == 1:
    coinresult = 'heads'
logging.debug('toss is(0 is tails 1 is heads):' + coinresult)
if coinresult == guess:
    print('you got it!')
else:
    print('Nope! Guess again')
    guess = input()
    logging.debug('you input is:' + str(guess))
    if coinresult == guess:
        print('You got it!')
    else:
        print('Nope. You are really bad at this game.')
logging.debug('end of debug')

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.