This section discusses some functions you'll be using a lot: print, for putting information on the screen, raw_input, for getting data from the user, and a host of other tools for moving data between the program, the user, and files on the computer.
3.1. The print statement
This is by far the most important function for a basic program. The word 'print' tells Python to take a value and output it to the screen. Here's the traditional "Hello, World!" program in Python:
print("Hello, World!")
That's it, really. You can do some other tricks with print:
Printing a blank line
print()
Printing a variable
string = "Hello, World"
print(string)
Printing multiple things on one line
fivesquared = 5*5
print("Five squared is ", fivesquared)
You can even do the math inside the statement:
print("Five squared is ", 5*5)
Note that the comma is important here to distinguish the items to be printed.
3.2. Getting user input: the input() function
The input function is what you use to get information from your user interactively. When the Python interpreter runs into a input statement, it pauses execution of the script to allow the user to enter some keyboard data, reads it until the Enter key is pressed, and then returns the data the user entered as a string. Since this data is a string, it may need to be processed to be used further:
print("Enter a number:")
number = input()
print("Your number, squared: ", (float(number))**2)
Running this code results in:
Enter a number:
1.1
Your number, squared: 1.21
You can also present a prompting question to the user on the same line as the data requested by giving a string argument to the raw_input function:
number = float(input("Enter a number: "))
print("Your number, squared: ", number**2)
Running this code results in:
Enter a number: 1.2
Your number, squared: 1.44
3.3. File operations
Frequently you will want to get data from a file, or save program output to a file. You do both of these via the "open" statement, which opens a connection (a filehandle, so called as it gives you a handle on the file to manipulate it) to a file for reading or writing. The syntax for the open statement is as follows:
filehandle = open(filelocation, mode)
filelocation must be a string that can be interpreted as the location on your system of a file (for example, "C:\Windows\MyData.dat" or "MyData.dat").
The different modes in which a file can be accessed are:
r - Read-only: The file must exist previously; it will not be modified and data will be read from it
a - Append: The file does not need to exist previously; new data will be added to the file starting at the end of the file. If the file does not exist it will be created and writing will start from the first line.
w - Write-only: The file does not need to exist previously (in fact, if it already exists, it will be erased!), and data will be written to it but cannot be read from it.
r+ - Read-write: The file can be both written to and read from. (Avoid using this unless you really need to! it is easy to lose data with this mode)
As an example:
filehandle = open("/tmp/MyOutputData.dat", 'w')
Note that if no mode is specified, Python assumes read mode.
Note also that if, on a Windows or Mac computer, you need to read or write binary data, you may add a 'b' to the mode string (e.g. 'wb'). Unix/Linux systems make no distinction between binary and text files, so the 'b' is ignored on these systems.
If you are having trouble getting this command to work, check to make sure you have permissions to do what you are trying to do--for example, you can't write to a read-only file, or read a file that you don't have access to, or read a file that doesn't exist where you think it does. (This happens more often than you might suspect.)
Once a file handle has been opened, manipulation of the file operates via a few different mechanisms.
Reading from a file:
To read a line from a file that's been opened for reading as 'filehandle', use the 'readline' method:
filehandle.readline()
Repeated calls of this function will return successive lines in the file.
For example:
print(filehandle.readline(),end='') # prints the first line of the file, without adding an extra blank line
print(filehandle.readline(),end='') # prints the next line of the file
(The end='' keyword is included in these print statements to prevent the print function adding a blank line after the line!)
Usually you will want to do something to every line in the file. It is possible to repeat the readline() call until you run out of lines, but it's faster to use one of the two following options:
a) filehandle.readlines() will return an array containing all the lines in the file:
for line in filehandle.readlines():
print(line,end='') # prints every line in the file.
b) or, you can directly loop over the filehandle object:
for line in filehandle:
print (line,end='')
If you use method b), do not also use the readline() or readlines() function (or the read(size) function, which returns a specific number of characters). If you do this might affect the internal file reference that Python uses to track where it is in the file.
Writing to a file:
To write a string to a file, use the write() method of the filehandle:
line = "Hello, World!\n" #the \n is a special symbol that adds a carriage return after the line
filehandle.write(line) #filehandle needs to be writeable
The data printed must be a string (you may wish to refer to Section 5.5.1 on string methods).
After you're done with a file, whether reading or writing, you must close the filehandle:
filehandle.close()
Storing & Restoring data
Say you have an array of data that your Python program calculated, and you'd like to use this data in another Python program later. Rather than writing some complex text file interpretation code for writing the data to a file and then reading it later, you can use the 'pickle' module (so named because you're preserving the data!). You need a filehandle that's open for writing (let's call it filehandle), and some data (which can be pretty much anything - a string, an array, an array of arrays, whatever), which we'll call data.
import pickle
pickle.dump(data, filehandle)
To get the data back, you can open the same file for reading, and use the following code:
data = pickle.load(filehandle)
Up to Index
Previous: 2. Operators | Next: 4. Control flow