Hardware Reference
In-Depth Information
choice
is another function that you have been using, perhaps without realising it. Its argu-
ment is a list of items, and the processing it does is to select one at random. Its output is an
item from the list, which it returns.
If you ind yourself writing the same code in multiple parts of a program, or using copy and
paste, you should think about putting the repeated code into your own function.
here are so many functions that if all of them were available at once, it would be over-
whelming to the programmer. Instead, Python contains only a few essential functions by
default, and others have to be
imported
from packages of functions before they can be used.
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!
he programs so far have produced an output, but when run, have not taken any input from
the user. he 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.
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 result of the
raw_input
function, which is what the user types when the pro-
gram is run.
his 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. herefore 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
.