15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

146<br />

Declaring Variables<br />

Declaring the data type of a variable<br />

You can never stop users from typing in the wrong type of data, such as<br />

typing in the words twenty thousand instead of the number 20000. However,<br />

you can protect yourself from trying to do something wrong, like multiplying<br />

a number by text. In the Python <strong>programming</strong> language, the following program<br />

actually runs:<br />

salary = input(“What is your annual salary?”)<br />

taxrate = “Thirty percent”<br />

print “This is how much you owe in taxes = “, salary *<br />

taxrate<br />

In this program, the third line tries to multiple the salary variable by the<br />

taxrate variable. If the program asks the user, “What is your annual<br />

salary?”, and the user types 20000, the third line of the program tries to<br />

multiply 20000 (stored in the salary variable) by Thirty percent.<br />

Obviously, you can’t multiply a number by a word, so this program would<br />

appear to work but prints only:<br />

This is how much you owe in taxes =<br />

The problem occurs because the program multiplies the salary variable by<br />

the text Thirty percent. Even though the program appears to run, it<br />

doesn’t run correctly.<br />

If you’re writing a small program, you could examine your program, line-byline,<br />

to see where the problem might be, but in a large program that might<br />

consist of thousands of lines, trying to track down this simple problem could<br />

be time-consuming and frustrating.<br />

To avoid this problem, many <strong>programming</strong> languages <strong>for</strong>ce you to define<br />

(declare) your variable names plus the type of data they can hold. By doing<br />

this, you can have the compiler check your program to make sure you aren’t<br />

mixing data types accidentally, such as trying to multiply a number by text.<br />

If your program does try to mix data types by multiplying a number by text,<br />

the compiler refuses to run your program, displays an error message, and<br />

highlights the problem so you can fix it right away, as shown in Figure 2-2.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!