Writing simple games in Python We are now getting closer to writing interactive programs and games in Python. Before we can do this, we are going to learn about some really important ideas: data types, if/else statements and importing libraries which will open up the power of python! Example 1 – Words and numbers We are going to look at two data types: words (which are called strings) and numbers (which are called floating points). To find out more, copy it and test this function: What does it do? What can you say about the function input? Try entering a word instead of a number… what happens? I actually wanted the function to double the number entered by the user... so I changed the function to this: What have I changed? What does this change do? Create your own program that requires the user to input a number, and returns something different (e.g. the number squared, or something else). Example 2 – if… else… Here is a function I wrote called bestTeacher: copy it up and test it out. Look at the function carefully: Which bits are new? Can you work out what they do? The if/else lines are really important – what do they do? Adapt the function to do something different. Try out the function below and work out what it does. Can you write a similar function? Can you write a function using an if statement to do something different? Hard challenge: Can you write a function to test whether a number is a prime number or not? Note: You have to be careful with the syntax – look at mine closely! Example 3 – Importing libraries We have seen that Python contains lots of built-in functions, like input and float. There are more libraries with lots more functions that we can import and use in our programs; we are going to import a library called random that generates random numbers. Here is a simple function that uses it: What different outputs do you get when you use this function? Can you alter this function to give a random whole number between 0 and 100? Challenge: Can you create a program that simulates throwing a coin? Super Challenge: Can you create a program that simulates throwing a coin many times? [Hint: you will need to put a while loop in there!] Here is a function I wrote that helps me decide how many detention minutes to give out – test it for yourself: Can you work out how it works? What is the flaw in this program?? And finally… let’s make a game! Here’s a much more complicated program that uses all the ideas from this lesson (plus a few more) to play rock-paper-scissors! Copy it up and test it out… can you see how it works? Find out how anything that is new to you works… [for example, what do the square brackets on line 2 and 5 do?] Now write a game of your own that uses randomness!