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.
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.
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:
Once IDLE is open you should see a window that looks something like Figure 1-1.
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.
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.
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.
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!"
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?
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:
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.
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.
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.
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."
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.
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.
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:
yourName = raw_input("What is your name? ")
print "Hello " + yourName
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?
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.
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:
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.
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."
print story
Enter a name: John
Enter an object: pineapple
Enter a place: the kitchen
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.
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.
hasBiscuits = raw_input("Do you have any biscuits? ")
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.
else:
print "I don’t believe you"
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.
willShare = raw_input("Can I have one? ")
if willShare == "yes":
print "Thank you!"
else:
print "I guess computers don’t eat biscuits anyway..."
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"
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:
print "a: Cake"
print "b: Carrot"
print "c: Fish"
print "d: Soup"
choice = raw_input("Select an option (a, b, c or d): ")
if choice == "a":
print "Here is your cake. Yum!"
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."
else:
print choice + " is not a valid option. Have some air."
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.
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.
userName = raw_input("What is your name? ")
message = raw_input("Enter a message: ")
while message != "exit":
print userName + ": " + message
message = raw_input("Enter a message: ")
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.
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.
while True:
print "I’m in space!"
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.
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.
again = "yes"
while again == "yes":
praiseType = raw_input("Select a type of praise
a:
personality
b: appearance
c: intelligence")
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"
again = raw_input( "Would you like some more praise?")
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:
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.
The first thing you’ll do is set up some basic information about the ship.
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.
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.
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.
print ""
print "The spaceship " + shipName + " is currently
visiting " + location + "."
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: ")
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.
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
elif choice == "b":
print "Firing cannons"
time.sleep(1)
print "BANG!"
time.sleep(1)
elif choice == "c":
print "Opening airlock"
time.sleep(3)
print "Airlock open"
time.sleep(1)
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"
elif choice == "/exit":
print "Goodbye"
else:
print "Invalid input. Please select a, b, c or d.
/exit to exit"
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?
Python Command Quick Reference Table |
|
Command |
Description |
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. |
Achievement Unlocked: Accomplished the creation of basic Python programs with input and output.
3.147.83.176