Hardware Reference
In-Depth Information
not equal (!=), less than (<), greater than (>), less than or equal (<=) and greater than or
equal (>=).
In this example, you'll make your insult generator change what it prints depending on the
age of the user. To achieve this conditional behaviour, you'll tell the program to do one thing
if something is true, or if not true, do something else. As a quick test of conditional behav-
iour enter the following code in an empty ile:
age = 12
if (age < 16):
print (“young”)
else:
print (“old”)
Run the program and you should ind it prints young . Change the age variable to be larger
than 15 and run the program again. his time it should print old .
Note that these print statements are indented by typically four spaces or a tab from the
beginning of the line. Unlike some other languages, indentation matters in Python. If you
don't get spaces in the right place, either Python gets confused and raises an error, or your
program won't do what you expect! You should always indent code properly.
Create a Stream of Insults!
In the next part of this project, you're going to change the program to produce multiple
insults, which is a good example of the use of functions. You're going to deine your own
function that you can call whenever you want an insult, and then create a loop that calls the
function multiple times.
Making Your Own Functions
You deine functions in Python by writing def (for deinition) followed by the name of the
function and the parameters it takes and a colon (:), followed by the indented body of the
function.
As a simple example, enter the following in an interactive Python window to deine a simple
function that will print a personalised greeting:
def printHelloUser (username):
print (“Hello “ + username)
 
Search WWH ::




Custom Search