THIS BLOG IS COLLECTION OF DIFFERENT TOPICS RELATED TO COMPUTERS.
USE TABS FOR GOING THROUGH DIFFERENT TOPICS
ashrafedu.blogspot.com
THIS BLOG IS COLLECTION OF DIFFERENT TOPICS RELATED TO COMPUTERS.
USE TABS FOR GOING THROUGH DIFFERENT TOPICS
An exception is an error that occurs while a program
is running, causing the program to abruptly halt. Some exceptions cannot be
avoided regardless of how carefully a program is written.
Python,
like most modern programming languages, allows you to write code that responds to
exceptions when they are raised, and prevents the program from abruptly
crashing. Such code is called an exception handler and is written with
the try/except statement. There are several ways to write a try/except
statement, but the following general format shows the simplest variation:
try:
statement
statement
etc.
except
ExceptionName:
statement
statement
etc.
First the key word try appears, followed by a
colon. Next, a code block appears which we will refer to as the try suite.
The try suite is one or more statements that can potentially raise an
exception.
After the try suite, an except clause appears.
The except clause begins with the key word except, optionally followed by the
name of an exception, and ending with a colon. Beginning on the next line is a
block of statements that we will refer to as a handler.
When the try/except statement executes, the
statements in the try suite begin to execute. The following describes what
happens next:
• If a statement in the try suite raises an
exception that is specified by the ExceptionName in an except clause,
then the handler that immediately follows the except clause executes. Then, the
program resumes execution with the statement immediately following the
try/except statement.
• If a statement in the try suite raises an
exception that is not specified by the ExceptionName in an except
clause, then the program will halt with a traceback error message.
• If the statements in the try suite execute without
raising an exception, then any except clauses and handlers in the statement are
skipped and the program resumes execution with the statement immediately
following the try/except statement.
Handling Multiple Exceptions
In many cases, the code in a try suite will be
capable of throwing more than one type of exception. In such a case, an except
clause for each type of exception has to be written that you want to handle.
def main():
# Initialize
an accumulator.
total = 0.0
try:
# Open the sales_data.txt file.
infile = open('sales_data.txt', 'r')
# Read the values from the file and
# accumulate them.
for line in infile:
amount = float(line)
total += amount
# Close the file.
infile.close()
# Print the total.
print(format(total, ',.2f'))
except
IOError:
print('An error occured trying to read the file.')
except ValueError:
print('Non-numeric data found in the file.')
except:
print('An error occured.')
# Call the main function.
main()
If an exception occurs in the try suite, the Python
interpreter examines each of the except clauses, from top to bottom, in the
try/except statement. When it finds an except clause that specifies a type that
matches the type of exception that occurred, it branches to that except clause.
If none of the except clauses specifies a type that matches the exception, the
interpreter branches to the except clause.
Using One except Clause to Catch All Exceptions
Sometimes you might want to write a try/except statement
that simply catches any exception that is raised in the try suite and,
regardless of the exception’s type, responds the same way. This can be accomplished
by a try/except statement by writing one except clause that does not specify a
particular type of exception.
def main():
# Initialize
an accumulator.
total = 0.0
try:
# Open the sales_data.txt file.
infile = open('sales_data.txt', 'r')
# Read the values from the file and
# accumulate them.
for line in infile:
amount = float(line)
total += amount
# Close the file.
infile.close()
# Print the total.
print(format(total, ',.2f'))
except:
print('An error occured.')
# Call the main function.
main()
Displaying
an Exception’s Default Error Message
When
an exception is thrown, an object known as an exception object is
created in memory. The exception object usually contains a default error
message pertaining to the exception. When an except clause is written, the
exception object can be optionally assigned to a variable, as shown here:
except
ValueError as err:
This
except clause catches ValueError exceptions. The expression that appears after
the except clause specifies that we are assigning the exception object to the
variable err.
The
else Clause
The
try/except statement may have an optional else clause, which appears after all
the except clauses. Here is the general format of a try/except statement with
an else clause:
try:
statement
statement
etc.
except
ExceptionName:
statement
statement
etc.
else:
statement
statement
etc.
The
block of statements that appears after the else clause is known as the else
suite. The statements in the else suite are executed after the statements
in the try suite, only if no exceptions were raised. If an exception is raised,
the else suite is skipped.
The
finally Clause
The
try/except statement may have an optional finally clause, which must appear after
all the except clauses. Here is the general format of a try/except statement
with a finally clause:
try:
statement
statement
etc.
except
ExceptionName:
statement
statement
etc.
finally:
statement
statement
etc.
The
block of statements that appears after the finally clause is known as the finally
suite. The statements in the finally suite are always executed after the
try suite has executed and after any exception handlers have executed. The
statements in the finally suite execute whether an exception occurs or not. The
purpose of the finally suite is to perform cleanup operations, such as closing
files or other resources.
The data that is stored in a file is frequently
organized in records. A record is a complete set of data about an item, and a
field is an individual piece of data within a record.
Each
time a record is written to a sequential access file, the fields that make up the
record, are written one after the other.
When
a read is made of record from a sequential access file, the data for each field
is read one after the other, until we have read the complete record.
Programs
that store records in a file typically require more capabilities than simply
writing and reading records such as adding records to a file, searching a file
for specific records, modifying a record, and deleting a record.
When
a program uses a file to write or read a large amount of data, a loop is
typically involved. Quite often a program must read the contents of a file
without knowing the number of items that are stored in the file.
In
Python, the readline method returns an empty string (' ') when it has attempted
to read beyond the end of a file. This makes it possible to write a while loop
that determines when the end of a file has been reached.
Here
is the general algorithm, in pseudocode:
Open
the file
Use readline to read the first line from
the file
While the value returned from readline
is not an empty string:
Process
the item that was just read from the file
Use
readline to read the next line from the file.
Close
the file
Using
Python’s for Loop to Read Lines
The
Python language also allows you to write a for loop that automatically reads
line in a file without testing for any special condition that signals the end
of the file.
Here
is the general format of the loop:
for
variable in file_object:
statement
statement
etc.
In
the general format, variable is the name of a variable and file_object
is a variable that references a file object. The loop will iterate once for
each line in the file.
Example:
#
This program uses the for loop to read
#
all of the values in the sales.txt file.
def
main():
# Open the sales.txt file for reading.
sales_file = open('sales.txt', 'r')
# Read all the lines from the file.
for line in sales_file:
#
Convert line to a float.
amount
= float(line)
#
Format and display the amount.
print(format(amount,
'.2f'))
#
Close the file.
sales_file.close()
# Call the main function.
main()
Data is saved in a file, which is usually stored on
a computer’s disk. Once the data is saved in a file, it will remain there after
the program stops running. Data that is stored in a file can be retrieved and
used at a later time. Programs that are used in daily business operations rely
extensively on files.
Programmers usually refer to the process of saving
data in a file as “writing data to” the file. The term output file is
used to describe a file that data is written to. The process of retrieving data
from a file is known as “reading data from” the file. The term input file is
used to describe
a file that data is read from.
There are always three steps that must be taken when
a file is used by a program.
1. Open the file: Opening a file creates a
connection between the file and the program. Opening an output file usually
creates the file on the disk and allows the program to write data to it.
Opening an input file allows the program to read data from the file.
2. Process the file: in this step data is
either written to the file (if it is an output file) or read from the file (if
it is an input file).
3. Close the file: when the program is
finished using the file, the file must be closed. Closing a file disconnects
the file from the program.
In general, there are two types of files: text and
binary.
A text file contains data that has been encoded
as text, using a scheme such as ASCII or Unicode. Even if the file contains
numbers, those numbers are stored in the file as a series of characters. The
file may be opened and viewed in a text editor such as Notepad.
A binary file contains data that has not been
converted to text. The data that is stored in a binary file is intended only
for a program to read.
Most programming languages provide two different
ways to access data stored in a file:
sequential access and direct access.
In order for a program to work with a file on the
computer’s disk, the program must create a file object in memory. A file
object is an object that is associated with a specific file and provides a
way for the program to work with that file. In the program, a variable
references the file object. This variable is used to carry out any operations that
are performed on the file.
Opening
a File
The open function creates a file object and
associates it with a file on the disk. Here is the general format of how the
open function is used:
file_variable = open(filename, mode)
In the general format:
• file_variable is the name of the variable
that will reference the file object.
• filename is a string specifying the name of
the file.
• mode is a string specifying the mode
(reading, writing, etc.) in which the file will be
opened.
File modes used are:
When
you pass a file name that does not contain a path as an argument to the open
function, the Python interpreter assumes that the file’s location is the same
as that of the program.
If
to open a file in a different location, specify a path as well as a filename in
the argument that is passed to the open function. If you specify a path in a
string literal (particularly on a Windows computer), be sure to prefix the
string with the letter r.
Here
is an example:
test_file
= open(r 'C:\Users\Ashraf\temp\test.txt', 'w')
The
r prefix specifies that the string is a raw string. This causes the
Python interpreter to read the backslash characters as literal backslashes. Without
the r prefix, the interpreter would assume that the backslash characters were
part of escape sequences, and an error would occur.
Writing
Data to a File
Once
you have opened a file, you use the file object’s methods to perform operations
on the file. File objects have a method named write that can be used to write
data to a file. Here is the general format of how you call the write method:
file_variable.write(string)
In
the format, file_variable is a variable that references a file object,
and string is a string that will be written to the file. The file must
be opened for writing (using the 'w' or 'a' mode) or an error will occur.
Once
a program is finished working with a file, it should close the file. Closing a
file disconnects the program from the file. The process of closing an output
file forces any unsaved data that remains in the buffer to be written to the
file.
In
Python you use the file object’s close method to close a file. For example, the
following statement closes the file that is associated with customer_file:
customer_file.close()
A
module is simply a file that contains Python code. A large program can be made
into smaller modules, and each module contains functions that perform related
tasks. With this Large programs are
easier to debug and maintain when they are divided into modules.
This approach, which is called modularization,
makes the program easier to understand, test, and maintain.
Modules also make it easier to reuse the same code
in more than one program. Import the module in each program that needs to call one
of the module functions.
import circle
When the Python interpreter reads this statement it
will look for the file circle.py in the same folder as the program that is
trying to import it. If it finds the file, it will load it into memory. If it
does not find the file, an error occurs. Once a module is imported you can call
its functions.
Random
numbers are useful for lots of different programming tasks. The following are
just a few examples.
•
Random numbers are commonly used in games.
•
Random numbers are useful in simulation programs.
•
Random numbers are useful in statistical programs that must randomly select
data for analysis.
•
Random numbers are commonly used in computer security to encrypt sensitive
data.
Python
provides several library functions for working with random numbers. These
functions are stored in a module named random in the standard library.
To
use functions form random module, import statement is used at the top of your program:
import
random
This
statement causes the interpreter to load the contents of the random module into
memory.
1. randint ( random-number
generating function)
The
following statement shows an example of how you might call the randint
function.
number
= random.randint (1, 100)
this
function takes two arguments for range to generate random numbers.
2. The randrange, random, and uniform Functions
The
randrange function takes the same arguments as
the range function. The difference is that the randrange function does not
return a list of values. Instead, it returns a randomly selected value from a
sequence of values.
For
example, the following statement assigns a random number in the
range
of 0 through 9 to the number variable:
number
= random.randrange(10)
The
argument, in this case 10, specifies the ending limit of the sequence of
values. The function will return a randomly selected number from the sequence
of values 0 up to, but not including, the ending limit.
The
following statement specifies both a starting value and an ending limit for the
sequence:
number
= random.randrange(5,10)
When
this statement executes, a random number in the range of 5 through 9 will be
assigned to number
The
following statement specifies a starting value, an ending limit, and a step
value:
number
= random.randrange(0, 101, 10)
Both
the randint and the randrange functions return an integer number.
The
random
function returns a random floating-point number. No arguments are passed to the
random function. When a call is made to it, it returns a random floating point number
in the range of 0.0 up to 1.0 (but not including 1.0).
Here
is an example:
number
= random.random()
The
uniform
function also returns a random floating-point number, but allows specifying the
range of values to select from.
Here
is an example:
number
= random.uniform(1.0, 10.0)
In
this statement the uniform function returns a random floating-point number in
the range of 1.0 through 10.0 and assigns it to the number variable.