Hardware Reference
In-Depth Information
his small line actually achieves quite a lot. he irst part,
userName =
, tells Python to cre-
ate a new
variable
—a location for storing a piece of information—called
userName
. he
equals symbol tells Python that the variable should be set to whatever follows. However, in
this case what follows isn't just a piece of information, but another command:
raw_input
.
his is a tool designed to accept
string
(text) input from the keyboard, and allows for a mes-
sage to be printed to the default output so the user knows what to type. his helps keep the
program simple—without the ability to print a prompt telling the user what to type, a sec-
ond line with a
print
command would be required. Remember to leave a space at the end of
the prompt; otherwise, the user's input will begin immediately after the question mark.
When asking the user to type in text, always use
raw_input
. This provides security that the
input
command alone does not—if you just use
input
, a user may
inject
his or her own code
into your program and have it crash or work contrary to your intentions.
WARNING
With the user's name now stored safely in the
userName
variable, the program can begin to
get clever. Welcome the user using the following line:
print “Welcome to the program,”, userName
his line demonstrates a secondary function of the
print
command introduced in Example
1: the ability to print out the contents of variables. his
print
command is split into two:
the irst section prints everything between the two quotation marks, and the comma tells
print
that more should be printed to the same line. Simply typing the variable name
user-
Name
is enough for Python to know that it should print the contents of that variable, result-
ing in a message customised to the user's own name.
An easy way to achieve neat formatting when printing output is to use the
.format
instruction
at the end of a
print
command. If you're using
.format
, the
print
line could be as follows
instead:
TIP
print “Welcome, {0}, to this program.”.format(userName)
his example program is going to take the form of a simple but friendly calculator. Unlike
Example 1, it will continue to run until the user tells it otherwise. his is achieved using a
loop, just as in Scratch. Begin the loop by typing the following two lines:
goAgain = 1
while goAgain == 1: