Hardware Reference
In-Depth Information
This small line actually achieves quite a lot. The first 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 .
This 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. This 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
This line demonstrates a secondary function of the print command introduced in Example
1: the ability to print out the contents of variables. This print command is split into two:
the first section prints everything between the two quotation marks, and the second comma
tells print that more should be printed to the same line. Simply typing the variable name
userName is enough for Python to know that it should print the contents of that variable,
resulting in a message customised to the user's own name.
This 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. This is achieved using a
loop, just as in Scratch. Begin the loop by typing the following two lines:
goAgain = 1
while goAgain == 1:
The first line creates a new variable called goAgain and sets it to 1 . The second line begins the
loop, and tells Python that while the goAgain variable is equal to 1 , it should continue to
loop through the following code. As the next few lines are written, they will need to be indented
by inserting four spaces at the start of each line. These spaces tell Python which lines are part of
the loop and which lines are outside the loop. If you're using IDLE, the spaces will be inserted
automatically; if you're using a text editor, remember to insert the spaces manually.
 
Search WWH ::




Custom Search