Hour 4
Getting Input and Displaying Output

Input and output are the cornerstones that enable programs to interact with the outside world. In the previous hour, you learned how important the output process is to programming because through output, your program displays information. A program must get some of its data and control from the user’s input, so learning how to get the user’s responses is critical as well.

The highlights of this hour include the following:

Image Displaying output in Python

Image Printing multiple occurrences per line

Image Separating output values

Image Using variables to hold information

Image Getting data in Python

Image Prompting for data input

Image Sending output to your printer

Printing to the Screen with Python

In Python, the primary method for displaying output on the screen is to use the print() function. You’ve already seen the print() function in action in the programs presented in the first two hours of the book. Almost every program you write will output some data to the screen. Your users must be able to see results and read messages from the programs that they run.

Note

In programming, a function is a collection of programming statements that perform a specific task. When programming, if you find yourself needing to do the same thing over and over again, you will save time by creating a function. Most programming languages include a series of predefined functions for output, input, and many mathematical operations. Some of Python’s built-in functions are covered in this book, but there are many more available. The Python functions that you learn in this book generally have comparable functions in other programming languages; once you learn one, it should be pretty easy to understand other similar functions in other languages.

The output to the screen in most programs is a combination of unchanging and changing information. Luckily, the print() function can handle both. The following statements show some examples:

print('2 + 3 = ',2+3)
print('Math is fun!')

These statements produce the following output:

2 + 3 = 5
Math is fun!

Remember that with the print() function in Python, you need to put what you plan to print in the parentheses. Without that, you will not get a result; instead, your code will generate an error message. You may be wondering about the information between the parentheses in the lines of code. There’s a string of characters between the two single quote marks in both, and that first single quote tells Python “print all characters you see from here on out until you get to the second, closing single quote mark.” The quotation marks are not printed; they mark the string to be printed. But what if you want to print quotation marks? Python has an easy solution. If you enclose your string to be printed in double quote marks, you can then include the single quotation mark as something to print. For example, if you changed the second line to the line:

print("Isn't math fun?")

the output would be:

Isn't math fun?

Whether you use single or double quotation marks, understand that numbers and mathematical expressions will print as is inside the string. Python will not do any math within a string. If you write:

print('2 + 3')

Python doesn’t print 5 (the result of 2 + 3). Because quotation marks enclose the expression, the expression prints exactly as it appears inside the quotation marks. However, as you can see in the second half of the first statement, if you print an expression without the quotation marks, Python prints the result of the calculated expression:

print(5 + 7)

prints 12.

Note

Don’t worry too much about understanding the calculations in this hour’s programs. Hour 5, “Data Processing with Numbers and Words,” explains how to form calculations in Python.

Here is the output you see if you run the program in Listing 4.1:

The area of a circle with a radius of 3 is
28.2744
The area of one-half that circle is
14.1372

Note that in Python, each time you call the print() function, it begins its output on a new line. You can also force the output to a second line by using the newline character ( ). For the newline character to work, it must be typed as the backlash character immediately followed by an n. For example, in the previous code, if you wanted the output in the first statement to span two lines but didn’t want to write two print() statements, you could alter the code to:

print("The area of a circle 
with a radius of 3 is ");

and the output of that line of code would be:

The area of a circle
with a radius of 3 is

Storing Data

As its definition implies, data processing refers to a program processing data. That data must somehow be stored in memory while a program processes it. In Python programs, as in most other languages’ programs, you must store data in variables. You can think of a variable as if it were a box inside your computer holding a data value. The value might be a number, a character, or a string of characters.

Note

Data is stored inside memory locations. Variables keep you from having to remember which memory locations hold your data. Instead of remembering a specific storage location (called an address), you only have to remember the name of the variables you create. The variable is like a box that holds data, and the variable name is a label for that box that lets you know what’s inside.

Your programs can have as many variables as you need. Variables have names associated with them. You don’t have to remember which internal memory location holds data; you can attach names to variables to make them easier to remember. For instance, Sales is much easier to remember than the 4,376th memory location.

You can use almost any name you want, provided that you follow these naming rules:

Image Variable names must begin with an alphabetic character such as a letter.

Image Variable names can be as long as you need them to be.

Image Uppercase and lowercase variable names differ; MyName and MYNAME refer to two different variables.

Image After the first alphabetic character, variable names can contain numbers and underscores.

Caution

Avoid strange variable names. Try to name variables so that their names help describe the kind of data being stored. Balanc19 is a much better variable name for an accountant’s 2019 balance value than X1y96a, although Python doesn’t care which one you use.

Here are some examples of valid and invalid variable names:

Valid Invalid
Sales04 Sales-04
MyRate My$Rate
ActsRecBal 5ActsRec
row if

Caution

Don’t assign a variable the same name as a Python statement, or Python will issue an invalid variable name error message.

Variables can hold numbers or character strings. A character string usually consists of one or more characters, such as a word, a name, a sentence, or an address. Python lets you hold numbers or strings in your variables.

Assigning Values

Many Python program statements use variable names. Often, Python programs do little more than store values in variables, change variables, calculate with variables, and output variable values.

When you are ready to store a data value, you must name a variable to put it in. You must use an assignment statement to store values in your program variables. The assignment statement includes an equal sign (=). Here are two sample assignment statements:

sales = 956.34

salesperson = "Tina Grant"

Tip

If you learn another language, it may require that you use a keyword to first declare a variable, so keep that in mind.

Think of the equal sign in an assignment statement as a left-pointing arrow. Whatever is on the right side of the equal sign is sent to the left side to be stored in the variable there. Figure 4.1 shows how the assignment statement works.

images

FIGURE 4.1
The assignment statement stores values in variables.

If you want to store character string data in a variable, you must enclose the string inside either single or double quotation marks. Here is how you store the phrase Python programmer in a variable named myJob:

myJob = "Python programmer" # Enclose strings in quotation marks

After you put values in variables, they stay there for the entire run of the program or until you put something else in them. A variable can hold only one value at a time. Therefore, the two statements:

age = 67;
age = 27;

result in age holding 27 because that was the last value stored there. The variable age cannot hold both values.

You can also assign values of one variable to another and perform math on the numeric variables. Here is code that stores the result of a calculation in a variable and then uses that result in another calculation:

pi = 3.1416;
radius = 3;
area = pi * radius * radius;
halfArea = area / 2;

Getting Keyboard Data with input()

So far, the programs you’ve created have used specific pieces of information and data coded right into the programs. Even variables have been defined with specific values, such as the radius of the circle in Listing 4.1. While this is interesting, it’s ultimately limiting. To make programs more valuable, you need to get information from your user.

The input() function is sort of the opposite of print(). The input function receives values from the keyboard. You can then assign the values typed by the user to variables. In the previous section, you learned how to assign values to variables. You used the assignment statement because you knew the actual values. However, you often don’t know all the data values when you write a program.

Think of a medical reception program that tracks patients as they enter the doctor’s office. The programmer has no idea who will walk in next and so cannot assign patient names to variables. The patient names can be stored in variables only when the program is run.

When a program reaches a prompt call, it creates a dialog box that stays until the user types a value and clicks or taps the OK button. Here is an input:

input("What is your favorite color?");

When program execution reaches this statement, the computer displays a dialog box or prompt with the message you type in the quotation marks. The dialog box is a signal to the user that something is being asked, and a response is desired. The more clear you make the statement you send to the prompt, the easier it will be for the user to enter the correct information.

Inputting Strings

Unlike in many programming languages, a variable in Python can hold either a number or a string. Any type of variable, numeric or string, can be entered by the user through a prompt dialog box. For example, this line waits for the user to enter a string value:

fname = input("What is your first name");

When the user types a name in response to the question, the name is put into the fname variable.

Caution

If the user only clicks or taps OK, without entering a value in response to the prompt, Python puts a value called null into the variable. A null value is a zero for numeric variables or an empty string for string variables. An empty string—a string variable with nothing in it—is literally zero characters long.

Tip

Python’s ability to combine the string asking the user to enter information and the prompt for the data itself is not a feature all programming languages share. When you use other languages (such as C), you may have to have a separate output statement telling the user what you need and an input statement to receive the information.

This program gets two strings from the user—a first name and a last name—and then combines them in two different formats in print() statements. There are other ways to combine strings, as discussed in the next lesson. The other issue is that there is no checking to ensure that the user entered the correct information. With strings, the program accepts numbers and treats them as strings. So if your user enters Helga as their first name and 11 as their last name, Python will set the full name as Helga 11.

While numbers can be treated as strings, the opposite is not true (for strings being entered as numbers). In Listing 4.3, if the user enters a series of letters for the radius, the program returns an error. When you are writing programs that take input, you often need to ensure that the user has entered the expected value. This is known as data validation, and this topic is covered in more detail in Hour 6, “Controlling Your Programs.”

Figure 4.3 shows the output of this program. As you can see, this type of program could be helpful for a small store. Obviously, it is unlikely that a store would only have three items, but once you learn some additional features of Python (such as dictionaries), you can quickly and easily build a more robust set of data for any need you have, personally or professionally.

You might be wondering about the character that appears in several of the last 10 lines that print out the receipt. This is another example of a formatting character you can use in Python. When Python encounters a in a string, it tabs over (as in a word processor) before continuing to print. This can be extremely useful if you are looking to line up columns when printing out output, as this program does for the quantities and totals of items purchased. The print() statements also perform formatting you have seen before, including using to jump down a line and %.2f to limit the digits to the right of the decimal points to two, which is all you should see in a financial transaction. When asking for purchase amounts, this program has lines for each item in inventory. While this works, it can be inefficient. Later on, in Hour 6, you will learn some tricks to loop through identical or similar code lines with fewer total lines. This might not seem like a big deal when you’re only dealing with 3 products, but what if you had 20 or more? In such situations, you can really improve your coding efficiency by taking advantage of loops.

images

FIGURE 4.3
Running the cash register program produces this output.

Note

Again, there is a lot you can do with input and output in Python, but this lesson just covers programming basics. If you want to learn more, please pick up a tutorial devoted to the language; your programs will thank you if you do!

Summary

Proper input and output can mean the difference between a program that your users like to use and one they hate to use. If you properly label all input that you want so that you prompt your users through the input process, the users will have no questions about the proper format for your program.

The next hour describes in detail how to use Python to program calculations using variables and the mathematical operators, as well as some handy string-manipulation tricks.

Q&A

Q. How can I ensure users enter information in the proper format for my program?

A. As mentioned earlier in the hour, techniques known as data validation can check to make sure the information entered is expected. If it isn’t you can either generate an error message or give the user another chance to enter the information. Data validation is covered more in later hours, but it will become an important consideration of any program that features user interaction.

Q. Why don’t I have to tell Python what type of variable I want to use?

A. Python is just that smart! Actually, for most programming languages, you need to specify the type of variable, and if you try to put a different type of data in that variable, you can get an error or unpredictable results. Python changes the variable type on-the-fly, so you can use the same variable as a string in the beginning of the program and then a number later. This is not the best idea, however. You should keep your variables focused on a specific type and a specific job.

Workshop

The quiz questions are provided for your further understanding.

Quiz

1. What is a function?

2. How would you write a print() statement that prints the sum of 10 and 20?

3. Declare a variable named movie and assign to it the last movie you saw in theaters.

4. What character is used in print() statements to force a new line?

5. What is a variable?

6. What function is used to get information from a program’s user?

7. What is a prompt?

8. Write a simple program that asks the user for his or her birthday in three separate prompts—one for month, one for day, and one for year—and then combine the three into a Month date, year format that you print on the screen.

9. In Python, what does the /t character do?

Answers

1. A function is a collection of statements that perform a specific task.

2. print(10 + 20)

3. (Obviously, this should vary based on your most recent cinema-viewing experience.) For me:

movie = "Once Upon a Time in Hollywood"

4. The newline character is .

5. A variable is a named storage location.

6. The input() function

7. A prompt describes the information that a user is to type.

8. Here is one possible solution:

# Answer to Chapter 4, Question 8


bYear = input("What year were you born? ")
bMonth = input("What month were you born? ")
bDay = input("What day were you born? ")

print("You were born on", bMonth, bDay, ",", bYear, "!")

9. It tabs over the input.

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

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