ch01-pag23

YOU HAVE TRIED two basic Python programs when you set up your computer, but your real journey with Python starts here. Learning to program is a fun and powerful way to control computers. In the adventures in this book, you’ll learn the fundamentals of programming with Python and have a lot of fun as you travel through them. You’ll create pictures, games and a load of other great stuff. Best of all, you’ll develop skills and knowledge of the Python programming language, which you can go on to use to bring your own ideas to life!

On your Python programming journey, you’ll discover a new language, a new way to be creative and a new way to solve problems. In this adventure, you’ll start by learning some fundamentals and developing a solid foundation. In future chapters, you will revisit all the fundamentals you learn in this chapter and build on them to strengthen your ability as a programmer.

By the end of this adventure you’ll already have travelled a long way. You will understand the importance of sequencing in programming and using input and output in Python. You’ll have covered the basics of if statements and while loops, both of which you will use a lot in later adventures. And you will have created a control console for a spaceship to help you launch into your next adventures! Don’t be alarmed—that may sound a lot to digest for a beginner but you’ll take it one step at a time and it’s much easier than it sounds.

What Is Programming?

First things first: before you start your adventures with Python programming it’s a good idea for you to be clear about what programming actually is.

Put simply, programming is controlling a computer by giving it a set of instructions so that it can perform a particular task.

All of the programs and applications (known as apps) on computers have to be written by people, who use programming languages, such as Python, to tell the computer how to behave when it runs the programs. For example, the web browser you use to visit websites is a program that has been programmed by people, as are the games on your computer, the text messaging app on your phone and even the operating system that runs when you switch your computer on.

The programming concepts that you learn with Python are common to nearly every programming language. This means that, once you’ve learned Python, you’ll find it easier and faster to learn other programming languages.

Opening IDLE

In order to use Python you’ll need to open an application on your computer that can run Python. One of the applications used for writing and editing Python programs is called IDLE, and this is installed by default when you install Python. If you haven’t already installed Python, do so now—you will find instructions on how to do this in the introduction. Check carefully that you install Python 2.7, and not Python 3, as there are some slight differences between them.

Done? Good—now you can open IDLE. The way you do this varies slightly depending on system you’re using:

  • On Windows 7, select Start⇒All Programs⇒IDLE.
  • On Windows 8.1, press the Windows key on your keyboard, type IDLE to search for the program and double-click IDLE when it has been found.
  • On Mac, select Finder⇒Applications⇒IDLE.
  • On Raspberry Pi, select Start⇒Programming⇒IDLE.
  • On Ubuntu Linux, select Launch⇒IDLE.

Once IDLE is open you should see a window that looks something like Figure 1-1.

9781118951798-c01f001.png

FIGURE 1-1 IDLE is ready for you to start programming!

IDLE is an Integrated Development Environment, or IDE for short. This means that it not only lets you write code but also includes a useful set of features for running, testing and editing your programs. In fact, you could write your programs in a basic text editor, such as Notepad, but the extra features of an IDE make it easier to manage your programs. There are many different IDEs available for Python, such as Eclipse, Geany, NINJA IDE and a whole load more. IDLE is a good IDE for starters, but as you go along you might want to try out other IDEs that have more features that support you when you're programming.

Returning to Your First Python Program

In the introduction to this book, you created two short Python programs. You completed them to quickly see some examples of what Python can do. In this section, you’ll return to the first of these programs to understand what it is doing and how you can change it to use in it your own programs.

Once IDLE is open, that’s it! You can start giving commands to Python. At the beginning of the bottom line, you’ll notice there are >>> characters. These mean that IDLE is waiting for you to tell it what to do (see Figure 1-2). The >>> is called the command prompt as it is prompting you to give it an instruction or command.

9781118951798-c01f002.png

FIGURE 1-2 The command prompt in a Python shell

The window into which you type the commands is called a python shell. It takes one command at a time and runs it before you can type the next line. A single line of Python code is called a statement, although you will see later that some statements can be more than one line long.

Place your cursor after the command prompt and type the following statement:

print "Hello world!"

Press Enter and the "Hello world!" message will be displayed, as shown in Figure 1-3.

9781118951798-c01f003.png

FIGURE 1-3 Your first Python program running in the Python shell

You can type whatever you like between the speech (quote) marks. Whenever you use the print instruction, whatever text you enter is displayed in the IDLE shell. The text inside the quote marks is called a string.

Try changing your message by typing different words between the quote marks. You could try changing the print statement to display your name in the IDLE shell, for example by typing:

print "Hello Ellen!"

It Isn’t Working—Grrr!

There will be times when you will find yourself jumping up and down in frustration, wondering why your program doesn’t work. It’s best to cover this now rather than waiting until later in the book, so you know what to do when this happens—because it will happen!

If your program doesn’t work, it means you have made a mistake in the instructions you have typed in. Let’s go through some common mistakes you can make. You’ll still make them—everyone does!—but if you know what mistakes you might have made it means you’ll know what to look for when your program doesn’t work as intended.

In an IDLE shell, type the following line after the command prompt and press Enter:

Print "I like trains"

What happens? You get an error message like the one in Figure 1-4. Can you work out why this happened?

9781118951798-c01f004.png

FIGURE 1-4 An error message in the Python shell

Python expects things to be written in a certain way and capitalisation is extremely important for Python. So, for example, if you capitalise any letter in the print command, Python will get confused.

Although you know what you want the computer to do, computers aren’t actually all that clever. They have to be given very precise instructions; if your instructions aren’t in exactly the right form, your computer can’t guess what you really meant. That’s why you have to stick to the rules of the programming language in order for the computer to understand you. These language rules are called syntax. When you don’t stick to the rules of the syntax, you get a syntax error like the one in Figure 1-4.

Errors are also called bugs. The process of finding and fixing bugs in your code is called debugging. Let’s have some debugging practice. Here are some other pieces of code with syntax errors in them. What are the bugs in this code and how would you fix them?

pirnt "Something"
print 'Cakes"
print Beep
print Sharks"
 print "Shakes"

Found them? Here are the bugs in order:

  1. print is spelled incorrectly. You can fix the error simply by fixing the spelling of the command.
  2. The speech marks do not match; one is single and one is double.
  3. The speech marks are missing, therefore Python doesn’t know that you meant to create a string.
  4. The opening speech mark is missing.
  5. There is a space at the start of the line. Did you spot that?

Debugging is a skill in itself. Everyone makes mistakes but being able to find and correct your mistakes is what will make you into a great programmer. Take your time when you start; it may be frustrating to see error messages, but it is a great feeling when you fix a problem.

Using a File Editor

The IDLE shell is great for trying out bits of Python code quickly, but it can be very time consuming when you have to write out your code one line at a time, every time you want to use it.

Using a file editor in IDLE, instead of the interactive shell, enables you to create programs with many lines of code. It also allows you to save these programs so that you can use them again and again. Another advantage of the file editor is that it waits for you to tell it to run the program, unlike the shell, which runs a program whenever you end a statement. The following steps guide you through writing a program using a file editor.

  1. Open the file editor in IDLE by selecting File⇒New Window (this may be called New File in some versions of IDLE). A new IDLE window will appear. This will look something like Figure 1-5.
    9781118951798-c01f005.png

    FIGURE 1-5 The IDLE file editor window

    You might notice that there is no command prompt (>>>) at the start of the line. You might also notice that when you press Enter it does not run your code. Don’t panic! This is what is supposed to happen.

  2. Let’s make the most of being able to create programs across several lines—such luxury. Type the following code into the file editor:

    print "Space:"
    print "A really big place"
    print "that contains a lot of stuff"
    print "and a lot of nothing between the stuff."
    print "This is why it is called space."

  3. To run the program, select Run⇒Run Module from the menu at the top of the window.
  4. When you are asked if it is OK to save, click Yes. Create a folder called Adventure 1 and save your file as space.py.

After a short while, the Python shell will appear and the message will be printed to it.

Another major benefit of the file editor is that, unlike the shell, you can change your programs and then rerun them. You’re going to try that now.

Click on the file editor again. Remember that the file editor doesn’t have a command prompt (>>>) and that’s how you can tell the difference between the shell and the file editor.

Add the following lines of code to what you’ve already written:

print ""
print "This definition of space is stupid."

Run the program again (choose Run⇒Run Module) and the changes to the program will be included in the output, as shown in Figure 1-6. Notice that the line with the empty speech marks ("") prints out a blank line.

9781118951798-c01f006.png

FIGURE 1-6 The completed program and output in IDLE

So far in Python you’ve written commands in the shell and the file editor, and used the print statement to output text onto the shell. Next you’ll find out how to change what your program does by inputting different strings when you run it.

Asking Questions with Variables

In the last example, you used the print statement to display strings in the IDLE shell. The strings didn’t change each time you ran the program. But how would you like to be able to change the program every time it runs? For example, you could have the program address each user by name. You are now going to do this by using two new things in Python: variables and the raw_input() function. You’ll learn more about variables and functions shortly but, to get started, try this example:

  1. In IDLE, open a new file editor window by clicking File⇒New Window.
  2. Type in this code, exactly as it is shown here, including the spaces:

    yourName = raw_input("What is your name? ")
    print "Hello " + yourName

  3. Now run the program by clicking Run⇒Run Module. Save your program as question.py in the Adventure 1 folder, which you created in the previous exercise.
  4. When the Python shell appears, the question What is your name? should be displayed, as shown in Figure 1-7.
    9781118951798-c01f007.png

    FIGURE 1-7 The command prompt waiting for you to input a name.

  5. Type your name after the question and press Enter. (Don’t press Enter immediately without typing a name—if you do that, the program will not do what you want it to do.)
  6. The computer will say hello to you; for example, it will print (or “output”) Hello Ellen.
  7. To run the program again, select the File Editor window and click on Run⇒Run Module.

The + sign between the Hello string and the yourName string variable joins these two strings together. This is called string concatenation. The + sign is necessary for joining the two string values.

Run the program again, but this time enter a different name when the computer asks you what your name is. Is the output different? What happens if you input a word that isn’t a name? What happens if you input a sentence?

A Bit About Variables

Variables are super-useful. They store values so that you can reuse them later. This makes your programs more manageable as you don’t have to change loads of lines of code whenever you just want to change a single value.

For example, when you use someone’s name in a long program, it makes more sense to use a string variable, instead of writing the name out in a new string every time. Using a variable means that when you want to change the name of the person using the program you only need to change the value of the variable instead of changing it every time the name appears in the program.

You write variables using a name, an equals sign and a value. You can name the variable almost anything you want, although it is a good idea to call it something that clearly describes what it is, so you will remember it easily. In the example you just did, the variable was called yourName—but you could have called it anything. You could call it kittens if you wanted, and the computer would deal with it in exactly the same way, although it wouldn’t make much sense to someone else reading it.

So far, you’ve created a variable that stores a string value. Variables that store strings can be placed anywhere you would expect a string, including after the print statement or as an argument in the raw_input() function.

Using Variables for a Fill-in-the-Blanks Story

In this part of the adventure, you’ll use variables again to create a fill-in-the-blanks story. Using input, your program will include three variables—a name, an object and a place—as details in a mini-story. By using input to change the values for these three variables, you can create a slightly different story every time:

  1. Open IDLE and open the file editor with File⇒New Window.
  2. For this program, the first thing you will need is a way to get the user to input the name, object and place variables. The following code will do this:

    personName = raw_input("Enter a name: ")
    anObject = raw_input("Enter an object: ")
    place = raw_input("Enter a place: ")

    Notice the space at the end of each string. Python carries out any commands you give it exactly as you type them. This means that if you don’t leave a space at the end of the line, there won’t be a gap between the prompt and the input.

  3. Now you are going to write a story using the variables to represent certain words in the story, which will be stored in the story variable. Add this code to your program:

    story = personName + " was walking through " + place + ". " + place + " was not usually very interesting. " + personName + " spotted a small " + anObject + ". Suddenly the " + anObject + " jumped up and ran away. " + personName + " decided not to go to " + place + " again."

  4. Finally, you’re going to output the story using the print statement, by adding this to your program:

    print story

  5. Run the program with Run⇒Run Module. Save your file as story.py in the Adventure 1 folder.
  6. When the program runs, enter a name, object and location as you are prompted for each (see Figure 1-8). For example:

    Enter a name: John
    Enter an object: pineapple
    Enter a place: the kitchen

    9781118951798-c01f008.png

    FIGURE 1-8 The finished program

  7. Once the program runs, you should see the story with your input included.

Making the Program Make Decisions: Conditionals

So far, you’ve been able to make your programs input and output data. You can do a lot with this, but the output of the programs will still look pretty much the same when you run them. To make your programs even better, you can use if statements to make the computer make decisions automatically and change the output depending on certain conditions.

Using if Statements

In this part of the adventure, the Python program will ask Do you have any biscuits?. If the answer is yes then the program will print They look delicious. If the answer is no or anything else, it will print I don't believe you.

  1. As usual, you need to open IDLE and create a new file editor window with File⇒New Window (remember, this is New File in some versions of Python).
  2. In the file editor, type the following code:

    hasBiscuits = raw_input("Do you have any biscuits? ")

  3. Next the program will need to use the if statement to check whether the input is yes. If the input is yes, the program will then print They look delicious.

    if hasBiscuits == "yes":
      print "They look delicious"

    Next, you need the code that will run if the answer is not yes. To do this you use an else statement. An else statement is used after an if statement. The code it contains will only run if the condition of the if statements is not True. In this example, it will run when hasBiscuits is not yes.

  4. Add the following code to your program. Make sure you don’t indent the first line, but do indent the second line by four spaces:

    else:
       print "I don’t believe you"

  5. Run the program in the usual way by clicking Run⇒Run Module. Save this program as biscuits.py in the Adventure 1 folder.
  6. Run the program (see Figure 1-9). Type yes with a lower case y, and press Enter. What do you think would happen if the y was capitalised?
    9781118951798-c01f009.png

    FIGURE 1-9 The finished program running alongside the Python code

  7. Run the program again and change the input to no. What do you think would happen if you input something other than “yes” or “no”? You can see the program running in Figure 1-9.

Nested if Statements

Sometimes after getting the answer to one question, you will want to ask a subsequent question. For example, in the last example, the program asked if you had any biscuits. You now want it to ask if it can have a biscuit if the answer is yes.

You can use if statements to do this by putting one if statement inside another; this is called nesting and creates a nested if statement. Try it out with this next example.

  1. Open your last program, the one you saved as biscuits.py in the Adventure 1 folder.
  2. After the line that reads print "They look delicious", add the following Python code (note that the first line is indented by four spaces):

       willShare = raw_input("Can I have one? ")
       if willShare == "yes":
           print "Thank you!"
       else:
           print "I guess computers don’t eat biscuits anyway..."

  3. The full program should look like this (see Figure 1-10). Remember to make your indentation match the example code:

    hasBiscuits = raw_input("Do you have any biscuits? ")
    if hasBiscuits == "yes":
       print "They look delicious"
       willShare = raw_input("Can I have one? ")
       if willShare == "yes":
          print "Thank you!"
       else:
          print "I guess computers don’t eat biscuits anyway..."
    else:
       print "I don’t believe you"

    9781118951798-c01f010.png

    FIGURE 1-10 An if statement nested inside another if statement

  4. Save the program and run it using Run⇒Run Module. When the program runs, it will now ask an extra question if the answer “yes” is given to the first question. You can see this in Figure 1-11.
9781118951798-c01f011.png

FIGURE 1-11 Replying “yes” to the first question will cause the program to ask a second question.

Creating an Imaginary Vending Machine

To get more practice using conditionals, you are now going to make a program for a vending machine that dispenses food. You’ll have to use your imagination here as the program won’t actually give you food! For that to happen you’d have to make your program control motors and buy the food. That will all be possible when you know more, but for now you’re just trying to write some Python. So on with the program!

To create your imaginary vending machine program, first you’ll display a list of choices for the user. Each choice is a type of food that can be ordered from the vending machine:

  1. Open IDLE and create a new file with File⇒New Window.
  2. In the new window, type the following lines of code to create a list of options:

    print "a: Cake"
    print "b: Carrot"
    print "c: Fish"
    print "d: Soup"

  3. Next add a raw_input() function that will take the user’s option and store it in a choice variable:

    choice = raw_input("Select an option (a, b, c or d): ")

  4. Now add an if statement for when the user selects option a (which is cake):

    if choice == "a":
       print "Here is your cake. Yum!"

  5. Sometimes you need more than the two options that an if and else statement gives you. An elif statement allows you to include additional options. The following lines of Python give three options that use an elif statement. Add these lines of Python to your program:

    elif choice == "b":
       print "Carrots are orange. Have some."
    elif choice == "c":
       print "Fish live in water. Enjoy!"
    elif choice == "d":
       print "Today’s soup is tomato. Spoons are located behind you."

  6. Finally, add an Else statement to handle all inputs that aren’t a, b, c or d. An else statement will always come last, after if statements and elif statements, however it is not mandatory, so you could leave it out. This else statement is included as you want to handle invalid options as well as valid options:

    else:
       print choice + " is not a valid option. Have some air."

  7. Run your code using Run⇒Run Module (see Figure 1-12). Save it as vending.py in the Adventure 1 folder.
9781118951798-c01f012.png

FIGURE 1-12 The finished vending machine code and the Python shell waiting for you to make a choice

Repeating Code with Loops

Until now, every time you wanted to go back to the start you had to rerun your program. You also had to copy and paste code if you wanted it to repeat several times. How inconvenient are you finding that? It wastes time and can make your programs hard to maintain. But never fear—there is a simpler way to do it, by using loops. Loops are a way to make your program repeat blocks of code.

Using while Loops

You’re now going to use a while loop to create a basic messaging program. This program is so basic that you’re effectively sending messages to yourself and no one else.

When the program starts it will ask for a user name. It will then ask the user to input messages, which are then output to the Python shell. The messages will repeat—loop—as long as the input isn’t exit.

  1. Open IDLE and open the file editor with File⇒New Window.
  2. You first want the program to ask for a user name and store this in the userName variable, then ask the user to enter a message. Type this code in your file editor:

    userName = raw_input("What is your name? ")
    message = raw_input("Enter a message: ")

  3. Next, you’ll add a loop to check the user’s input and display it. Enter these three lines of Python—these three lines will repeat over and over until the user enters exit as an input (see Figure 1-13):

    while message != "exit":
       print userName + ": " + message
       message = raw_input("Enter a message: ")

    9781118951798-c01f013.png

    FIGURE 1-13 This program repeats until the user types exit

  4. Run the program with Run⇒Run Module. Save it as chat.py in the Adventure 1 folder.
  5. Enter some messages into the program. When you are finished, type exit and press Enter.

While loops are used to repeat a block of code several times. This is a great thing to know how to do. It means you don’t have to copy and paste code in order to make it repeat several times. It also means that you can control how many times the block of code repeats, whether that is once, not at all, six times or an infinite number of times.

Infinite while Loops

It’s possible to make programs that repeat forever; this is done using a while loop. You’ll try out this next program in a Python shell as it is only two lines long, but you could also do it in a file editor.

  1. Open a Python shell. Remember that a Python shell is distinguishable from a file editor as it has a command prompt (>>>) at the start of each line.
  2. Copy these two lines of code into the Python shell:

    while True:
       print "I’m in space!"

  3. Press Enter. Watch the text scroll infinitely up the screen, as in Figure 1-14.
    9781118951798-c01f014.png

    FIGURE 1-14 The loop makes the code repeat infinitely.

It can be quite good fun to take over your friend’s computer while they’re not looking and type this quickly. Change the string in the print statement to something like "I am great" and watch the message appear hundreds of times before your friend has even noticed what’s happening. Of course, you also need to know how to stop the program before violence breaks out. You can stop the loop from repeating by resetting the shell: On the menu bar at the top of the IDLE window, simply click Shell⇒Restart Shell.

Praise Generator

So far, you’ve done quite a lot in Python, so take a minute to notice how far you’ve come already, and congratulate yourself. You’ve learned about input and output, variables, if, else and elif statements, and while loops. The flexibility of programming is that you can combine these basic pieces of Python code together in different ways to control what happens.

Let’s put it all together. You’re now going to combine if statements with loops to make a program that gives you praise. You’ll use a loop to make the code repeat and an if statement to select which praise to output.

  1. Create a new file editor by opening IDLE and clicking File⇒New Window.
  2. First you’ll create a variable called again. The first time the program is run this variable is set to "yes", which will mean the loop runs at least once.

    again = "yes"

  3. Next add the following code to make the program repeat and ask the user what type of praise they would like:

    while again == "yes":
       praiseType = raw_input("Select a type of praise a:
      personality b: appearance c: intelligence")

  4. The if statements are used to respond to the input and output the response:

       if praiseType == "a":
          print "You are an interesting person"
       elif praiseType == "b":
          print "You are smart"
       elif praiseType == "c":
          print "You look good"
       else:
          print "That wasn’t an option"

  5. The final line asks the user if they want to continue. Inputting anything other than “yes” will make the program end.

       again = raw_input( "Would you like some more praise?")

  6. Run the program with Run⇒Run Program. Save the program as praise.py in the Adventure 1 folder.
  7. When the program runs, choose option a, b or c. The program will loop as long as you type “yes” when asked if you want some more praise (Figure 1-15).
9781118951798-c01f015.png

FIGURE 1-15 The program displays a compliment when you enter a, b or c.

A Bigger Adventure: Spaceship Control Console

Spaceships are amazing. They have loads of computer systems to do all sorts of tasks.

There’s usually a master computer in a spaceship that controls the other computers. The captain of the ship gives the master computer commands via a console to control everything the ship does.

In the final part of this adventure, you’ll build a spaceship command console using all the Python concepts that you’ve covered in this chapter.

The console will enable your ship to:

  • Travel to another planet
  • Fire cannons
  • Open the airlock
  • Self-destruct

On top of that, your command console will be password-protected so that no one can take control of your ship without permission.

Each part of the system will be built in stages so that you can test that it works as you go along.

Set-Up and Password

The first thing you’ll do is set up some basic information about the ship.

  1. Open IDLE and open the file editor using File⇒New Window.
  2. Copy the following code into the file editor:

    import time
    shipName = "Nastrama"
    captain = "Wallace"
    location = "Earth"
    password = "Buttercups"

    You can change the values of these variables to whatever you want, of course. Notice how easy it is to understand what each variable stores, based on its name.

  3. Next it’s time to create the password check. Below the variables you just input, add these lines to your code:

    pAttempt = raw_input("Enter the password: ")
    while pAttempt != password:
       print "Password incorrect"
       pAttempt = raw_input("Enter the password: ")
    print "Password correct. Welcome to the " + shipName

    This bit of code will ask the person trying to use the command console to enter the password. If they get it wrong it will keep asking them until they get it right or give up. As soon as they get it right, the program will welcome them to the ship.

  4. Save the program as spaceShipConsole.py in the Adventure 1 folder. Click Run⇒Run Module. Test the program to see if the password verification works. If you enter the wrong password it will say "Password incorrect", but if you enter the right password it will welcome you to the ship.

    Naturally, the first thing the console will do after the captain has entered the correct password is give some basic information about the ship, including its name and current location. Continue writing your program as follows.

  5. Below the code you’ve written, add the following lines:

    print ""
    print "The spaceship " + shipName + " is currently
     visiting " + location + "."

  6. Next, you want the program to ask the captain what he or she wants to do and list a set of commands the captain can give the ship:

    choice = ""
    while choice != "/exit":
       print "What would you like to do, " + captain + "?"
       print ""
       print "a. Travel to another planet"
       print "b. Fire cannons"
       print "c. Open the airlock"
       print "d. Self-destruct"
       print "/exit to exit"
       print ""
       choice = raw_input ("Enter your choice: ")

  7. Save the program and run it using Run⇒Run Module.
  8. Enter the correct password. The program should then ask what you want to do, so you need to test whether the four possible choices work—but there’s a problem! Whatever input you type in, it won’t do anything other than ask you what you want to do again. For now, typing /exit is the only command that will work. When you type /exit the program should finish.

    Using the Console to Do Things

    When the captain inputs a command the console needs to respond to it—so how do you make that happen? In this section, you’ll deal with the commands one at a time.

    The "Travel to another planet" command will ask where you want to travel, take a certain amount of time while the ship travels there and then tell you that the ship has arrived.

  9. Add this code to your program inside of the while loop:

       if choice == "a":
          destination = raw_input("Where would you like to
                                  go? ")
          print "Leaving " + location
          print "Travelling to " + destination
          time.sleep(5)
          print "Arrived at " + destination
          location = destination

  10. Next, add the code for the command to fire the cannons:

       elif choice == "b":
          print "Firing cannons"
          time.sleep(1)
          print "BANG!"
          time.sleep(1)

  11. Now add the code for opening the airlock:

       elif choice == "c":
          print "Opening airlock"
          time.sleep(3)
          print "Airlock open"
          time.sleep(1)

  12. Finally, add the code for making the ship self-destruct:

       elif choice == "d":
          confirm = raw_input("Are you sure you want
                               the ship to self-destruct?
                               (y/n)")
          if confirm == "y":
             print "Ship will self-destruct in"
             print "3"
             time.sleep(1)
             print "2"
             time.sleep(1)
             print "1"
             time.sleep(1)
             print "Goodbye"
             print "BOOM"
             choice = "/exit"

  13. You need some code in case the user wants to exit, too:

       elif choice == "/exit":
          print "Goodbye"

  14. Finally, add some code in case the user types something that is not a valid choice:

       else:
          print "Invalid input. Please select a, b, c or d.
          /exit to exit"

  15. Save the program as spaceShip.py in the Adventure 1 folder and run it using Run⇒Run Module.

Figure 1-16 shows the full program. Once the program is running you can give it some commands. Try flying to a new planet or firing the cannons. What happens if you don’t use one of the main commands?

9781118951798-c01f016.png

FIGURE 1-16 The finished program

Python Command Quick Reference Table

Command

Description

print

The print statement is used to output values onto the Python shell. For example print "cats" would output the word cats.

"string"

Strings are the data type to use when you want to store text in your program. A string stores characters, letters and symbols.

raw_input("question")

Use the raw_input() function to input string from the users into a program.

"Hello " + "Dave"

Concatenation uses the plus sign (+) to combine two or more strings. It is particularly useful when combining strings with strings that are stored in variables.

name = "Ellen"

Variables store data, which can be reused and changed in the program. Strings can be stored in variables.

if condition == True:

An if statement is used to control whether or not a section of code runs. It uses a condition to decide whether or not the code it contains should run. If the condition evaluates to True, it will run; otherwise it will not.

==

The equals to comparator is used with if statements and while loops to check whether the value of two things are the same. If they are the same it will evaluate to True; otherwise it will evaluate to False.

if..else

An else statement is used with an if statement. It will run code in the body of the else statement if the condition of the if statement evaluates to False.

if..elif..else

An elif statement is used with an if statement. It has its own condition and will run if this condition evaluates to True and the condition of the accompanying if statement evaluates to False.

while

A while loop will repeat a block of code. Like an if statement, it has a condition and will only repeat while its condition is True. If the condition is False it will not repeat.

!=

The not equals to comparator will check whether two values are not equal to each other. If they are equal it will evaluate to False, otherwise it will evaluate to True.

The escape sequence is used in strings to create a new line.

import time

The import statement allows your program to use other pre-written modules with extra functions. The time module is one such module. It allows your programs to use timing instructions, such as waiting a few seconds.

time.sleep(5)

The sleep() function makes the program wait and do nothing for a number of seconds. The number of seconds is given as an argument inside the brackets. It can only be used if the time module has been imported.

1-badges-unlocked.png

Achievement Unlocked: Accomplished the creation of basic Python programs with input and output.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.83.176