Hardware Reference
In-Depth Information
choice is an example of a function that needs to be imported from the random package. In
the earlier example, the line import choice from random performs this role. You only
need to import a function once in a program, but you can use it multiple times.
Insult Your Friends by Name!
The programs so far have produced an output, but when run, have not taken any input from
the user. The next example asks the user for a name and then prints a personalised greeting.
To try this out, enter the following code:
name = raw_input(“What is your name?”)
print (“Hello “ + name)
raw_input became the input function in Python 3. If you're using IDLE 3, remember to
type input wherever you see raw_input in the examples in this topic.
TIP
he raw_input function (renamed to input in Python 3) takes a message to print as its
argument and returns the data the user entered. In this example, the variable name is
assigned the input from the user when the program is run.
This example also introduces how to join strings together. Strings are joined together, or
concatenated as a programmer may say, by placing + between the strings. It's important to
note that because the computer treats strings as just characters and not words, when strings
are concatenated, it does not automatically insert spaces. Therefore it is up to the program-
mer to add any spaces needed. In the preceding example, there is a space after Hello in the
quotes - without this, the computer would print something like HelloFred .
Help with Functions
When you type a function like choice in IDLE, a tooltip pops up telling you what arguments
the function takes and what it returns. This is a useful quick reference so you don't have to
remember exactly what parameters a function takes, and it's easier than looking up the full
reference online.
If you press the Ctrl key and the spacebar simultaneously, IDLE will attempt to autocom-
plete what you've typed thus far, which is useful if you can't remember exactly what a func-
tion is called. To try this out, type pri and then press Ctrl + space. You should see a list of
functions with print highlighted, as shown in Figure B-8. Press the spacebar again to have
IDLE finish off the typing for you.
 
Search WWH ::




Custom Search