Python 2: Branching logic and simple I/O


2.1 Getting user input from the keyboard

Integer input

import math
radius=int(raw_input("Please enter a radius: "))
print "For a radius of %s the area is %s"%(radius, area)
>>> For a circle of radius 2 the area is 12.5663706144

Note that () brackets and "" string quotes must balance.

Floating point input

radius=float(raw_input("Please enter a radius"))

String input

fname=raw_input("Please enter your first name: ")
lname=raw_input("Please enter your last name: ")
print name

Please enter your first name: Ebenezer  Please enter your last name: Scrooge  EbenezerScrooge 

The wrong kind of input

Please enter a radius: Fred
Traceback (most recent call last):
  File "", line 2, in ?
    radius=float(raw_input("Please enter a radius: "))
ValueError: invalid literal for float(): Fred

Trapping the ValueError

import math
  radius=float(raw_input("Please enter a radius: "))
  print "you entered invalid input"
  print "For a radius %s the area is %s" % (radius,area)

2.2 if, elif, and else program branches

mark=float(raw_input("Please enter a mark"))
if mark >= 40:
  print "You passed."
  print "Well done."
  print "You failed."
  print "too bad."

Syntax rules:

mark=float(raw_input("Please enter a mark"))
if mark < 40:
  print "fail"
elif mark < 50:
  print "pass"
elif mark < 70:
  print "credit"
  print "distinction"

You can also have 1 or more elif blocks each with their own test between the if and the else blocks. Each test only looks at cases excluded by tests already carried out.

2.3 Comparing numbers and strings

You can't compare numbers with strings, but you can compare like with like.

When we said:  if mark < 40:   we were comparing a number (the one referred to by mark) with another number, 40 in the middle bit of the if statement (the test part).

Test parts give a true or false result. What is truth ? Python defines false as:

None		The null object
0		Integer zero
0.0		Floating point zero
""		Empty strings
{}		Empty dictionaries
[]		Empty lists
()		Empty tuples

And if something isn't false it's true. In practice a test such as mark < 40 is replaced by the value 1 if the test is true. Comparison tests that can be done between numbers, strings and lists are:

<		less than
>		greater than
<=		less than or equal to
>=		greater than or equal to
==		equal to
!=		not equal to

If you want to check if a number is within a range you can test like this:   1 <= number <= 10   Here Python assumes the and combination you would need in other programming languages; this range test is equivalent to (1 <= number && number <= 10) in 'C' . Tests of this kind can also be used to compare strings in Python, with dictionary order being the decider of whether one string is "greater" than another. If you want case insensitive string comparisons you can get the lower-case version of the strings before comparing e.g:

import string
answer=raw_input("You want to buy my oranges gringo ?")
if string.lower(answer) == "y" :
    print "Man from Del Monte he say yes !!"

2.4 Combining tests with 'not','and' and 'or'

expects tests on both sides to be true for the whole test to be true

name=raw_input("Enter your name")
password=raw_input("Enter your password")
if name == "Aladdin" and password == "sesame":
  print "your wish is my command!"
  print "go away"

will work if either side is true e.g:

plant=raw_input("Hello who are you ? ")
if plant == "Bill" or plant == "Ben" :
  print "Hello flower pot man"
  print "Weed"

will test the opposite of something:

magic=raw_input("Hello who are you ? ")
if not (magic == "Florence" or magic == "Brian" or magic == "Dougal") :
  print '"Time for bed", said Zebedee '
  print '"Boing !" said Zebedee'

In the above test for Magic Roundabout characters, the or tests had to be surrounded by () brackets because or binds more tightly than not. Try testing this with Dylan (who is always sleepy) as well as with the wakeful Florence, Brian and Dougal.

2.5 Accessing files on disk

Disk files have to be opened before being read from or written to (accessed). If you are handling lots of files, or are going to access them differently, (e.g. writing to them after having read from them) it is a good idea to close them and reopen them between different kinds of access operation.

To learn how to do this using Python, it's a good idea to create and save test files which your program can read using an ordinary editor such as Notepad. When your program has written a file you can open it in Notepad to see if your program worked.

When you are confident that you know how to do simple file operations, you will then want to be able to store data used in an application in a disk file, reading it in when needed, updating the data in memory and then writing the updated data out to the file again.

Hint: To maintain program data in an external file between program runs you will need to carry out file access actions in the following sequence:

2.6 File opening

outp = open('/tmp/scratch','w')

outp is the filehandle used to access the Unix file /tmp/scratch in write ('w') mode.

inp = open('c:\\windows\\win.ini','r')

inp is the filehandle used to access the Windows file c:\windows\win.ini in read ('r') mode. To add onto the end of a file use 'a' append mode instead of 'w' write mode. Write mode will overwrite the existing file, if there was one.

If you don't want to have to double up backslashes in a Windows style filename, you could instead specify the raw string format e.g: inp = open(r'c:\windows\win.ini','r') uses a raw string. (The letter r in front of the quoted string makes it raw, so the backslashes become literals.)

2.7 File output

Once you have a filehandle created by open with a write or append mode, you can send a string or a line using the write method on the filehandle:

outp = open('/tmp/scratch','w')
outp.write('hello file\n')

This program will create or overwrite /tmp/scratch with contents of: hello file followed by a newline. If you have a number of lines stored in a list you could use the writelines method:

outp = open('scratch','w')
outp.writelines(['one line\n','another line\n','third line\n'])

This creates a file called scratch with contents:

one line
another line
third line

In practical applications you are more likely to supply write() and writelines() methods with references to the data you want saved, together with constant data you always want written e.g:

name=raw_input("Enter your name")
password=raw_input("Enter your password")

2.8 Input from files

You can read an entire file, or stated number of bytes using the read method on your filehandle e.g 1:

inp = open('scratch','r')
print lot

This prints:

one line
another line
third line

The second example prints the first 5 bytes: one l

inp = open('scratch','r')
print five

The readline() method reads the next line from the file, while readlines() reads all remaining lines into a list of strings:

inp = open('scratch','r')
print los

This prints using the default list representation, showing the octal values of the non-printable linefeed characters :

['one line\012', 'another line\012', 'third line\012']

2.9 Closing files

This frees the resource provided by the operating system in providing a connection between a program and an external file. You will need to do this before you re-open a file in a different mode, (e.g. writing after reading), or if you need to access many files. Otherwise you probably don't need to bother, as the file with close anyway when your program exits.

Use the close method on the filehandle returned by open() e.g: