This is Part II of Understanding Programming: A Primer, an exclusive series for EDUKWEST designed to teach you the basics of computer programming. This series is designed to be a tutorial and you will be the most successful if you work through the tutorial with your text editor open. Key in the code as it appears and try to make it run correctly yourself. You’ll find that by the end of this series, you’ll be able to develop simple programs and understand the process of computer programming.
In this tutorial we’re going to look more closely at input and output, which are, perhaps, the two most critical concepts in any program. In the previous article we looked closely at the output that can be produced with the print command. With print we were able to output three types of data to the command line screen: strings, integers and floating point numbers. The programs we wrote, however, how no capacity to take input and process data. In this article we’re going to look closely at two types of input. Input statements will allows us to programmatically request input from the user. We’ll then use command line parameters to provide inputs to our program.
As we look at output, we’ll also look at directing our output to a file instead of back to the command line.
So now it’s time to put on your favorite programming music (I suggest The Cure), open your nano or vi text editor and let’s start coding…
We’re going to start with a program that calculates the area of a rectangle based on the length of a sideA input and a sideB input. Let’s start with the code. Key the following Python in to your text editor.
print “RECTANGLE AREA CALCULATOR”
sideA = input(“What is the length of sideA? “ )
sideB = input(“What is the length of sideB? “ )
area = sideA * sideB
print “The area of your rectangle is”, area
Once you are sure you have keyed in the program correctly, go ahead and run the program on the command line. I saved mined as square.py. Your output should look similar to the screenshot below.
Figure 1.1: Execution of the square.py program which takes inputfrom the user via the Python input() function.
Based on context and the program execution, you’ve probably already guessed what the input() function does. Let’s break it down:
age = input(“How old are you?“)
In the example above, whatever the user types at the prompt “How old are you?” is going to be assigned to the variable age. We’re going to take a closer look at variables in the next lesson– for right now just consider variables a temporary storage place for values. These values can be strings, floats or integers.
Let’s try a new example. Create a new file in your text editor called stringInput.py. You can do this in vi, for example, by typing the following command on the command line: vi stringInput.py.
Key in the following code:
name = input(“What’s your name?”)
print “Hello, “, name
Exit your text editor and execute the program from your command line with the command python stringInput.py. The result may not be what you expect.
Figure 1.2: Uh-oh. This can’t be good. My name isn’t defined? Disturbing.
So what happened? Instead of running to completion the program exited with an error. Luckily the error is easy to fix. The input() function automatically converts whatever data is entered in to a floating point number or integer. When you enter an actual string, it causes the error above. We have another version of the input() function that is intended for string use. Edit your code as follows
name = raw_input(“What’s your name?”)
print “Hello, ” , name
NOTE: For a few of you this may have worked fine– The reason is you are using a different version of Python that permits string usage with the input() function.
Figure 1.3: So much better with raw_input()!
When you’re working with strings you should use the raw_input() function which does not attempt to convert the data entered in to a number. It keeps the data “raw” just as entered by the user.
A second way in which input can be submitted in to a Python program is through the command line when the program is run. This is done through command line arguments. Right now when you run your program in the command line, you type the python command followed by the filename of the program you’re trying to run. However , if you include parameters, it would look more like this:
$ python moreInput.py arg1 arg2 arg3
In the example above, we still use the python command and the filename of the program we’d like to run but we follow it with the arguments that will be the input in the program For example if we wanted a program to receive the users name and age as input, the parameters might look something like this:
$ python moreInput.py Mark 40
The values “Mark” and “40”, which are separated by a single space, are passed to the program and can be used as input. Let’s see how. Key in the following example and save it as moreInput.py.
print “Your name is “, sys.argv
print “Your age is “, sys.argv
print “All the arguments: “, sys.argv
Next let’s run the program and supply command line arguments as input:
$ python moreInput.py Mark 40
You should get a result similar to the one pictured in the screenshot below:
Figure 1.4: Command line parameters being processed as input on the Mac command line.
On the first line of this program, we encounter our first import statement. Imports are used in many languages and they are used to add an additional library of commands to the language that are not in the language core. In this case we’re adding the sys library which contains commands regarding the Python system itself. It has the necessary code commands that allow us to access the command line arguments.
NOTE: The terms parameter and argument can be used interchangeably.
The arguments come in to Python numbered sequentially, so, in our case the user’s name is argument number one and the age is argument number two. In code we call these sys.argv and sys.argv respectively. The last line of the program tells Python to output all of the command line parameters. If you study the screenshot carefully, you may notice something interesting– sys.argv is not the first parameter.
The first parameter is the name of the file we’re running with Python. This is sys.argv. The name of the file that we run is actually an argument of the Python command that we issue. This is often a point of confusion when working with command line arguments in Python.
Output to a Filestream
Your output does not have to be directed back to the command line– It can be directed to a file for more permanent storage. Being able to store data (more or less) permanently is an important skill for programmers to learn. Let’s write a program in which we as the user to enter several pieces of data and we then store those in a file.
Key in the following code:
name = raw_input(“What is your name? “)
email = raw_input(“What is your email? “)
favoriteBand = raw_input(“What is your favorite band? “)
outputString = name + “|”+ email + “|” + favoriteBand
fileName = name + “.txt”
#open the file
file = open(fileName, “wb”)
print outputString , ” is written to file ” , fileName
This is definitely the most complex program we’ve written yet. Go ahead and run it on the command line and make sure you don’t get any errors. Your command line should look something like this if everything runs correctly:
Figure 1.5: The program stored the data in a file called Mark Lassoff.txt which is now available in the directory listing by using the ls command on the command line.
While the code for this program is somewhat longer than what you are used to at this point, it is still fairly straight forward. When the program runs we prompt the user for their name, email and name of their favorite band. We store that information in variables. We then create a new variable called outputString which contains the information the user typed and some formatting to make the information readable when stored.
Every file has to be stored under some filename so we create the filename out of the name that was entered by the user and store it in a variable fileName. The next part of the program is where the action happens:
file = open(fileName, “wb”)
print outputString ,” is written to file ” , fileName
The first line of this series opens a file, using the fileName created earlier. wb is the file mode which indicates that we are opening the file with permission to write to it. file.write() obviously writes the actual data to the file that has been opened. We then alert the user to what has occured and use file.close() to close the actual file that we’ve written.
Figure 1.6 We opened “Mark Lassoff.txt” in the text editor and you can see the data that has been written to the disk.
Congratulations! You’ve written a program that stores data permanently as output. You are well on your way to being a programmer!
Please contact the author at firstname.lastname@example.org if you are interested in this and similar lessons for classroom use.
If you are interested in a formal version of this course for yourself or others, LearnToProgram has a special discount for EDUKWEST readers. Programming for Absolute Beginners is the starting point for our Development Club which provides over 30 self-paced courses, and as many live courses as you want to take. For more information and to access the EDUKWEST reader discount, visit: