0% found this document useful (0 votes)
3 views

Mod02 Getting Inputs

The document discusses reading input from the keyboard in Python, explaining how to use the built-in input function to capture user input and store it in variables. It also covers data type conversion for numeric input, demonstrating how to convert strings to integers and floats using the int() and float() functions. Additionally, the document outlines basic mathematical operations and provides examples of using variables in calculations.

Uploaded by

jubahib.jane23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Mod02 Getting Inputs

The document discusses reading input from the keyboard in Python, explaining how to use the built-in input function to capture user input and store it in variables. It also covers data type conversion for numeric input, demonstrating how to convert strings to integers and floats using the int() and float() functions. Additionally, the document outlines basic mathematical operations and provides examples of using variables in calculations.

Uploaded by

jubahib.jane23
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

2.

6 Reading Input from the Keyboard 71

Checkpoint
2.10 What is a variable?
2.11 Which of the following are illegal variable names in Python, and why?
x
99bottles
july2009
theSalesFigureForFiscalYear
r&d
grade_report
2.12 Is the variable name Sales the same as sales? Why or why not?
2.13 Is the following assignment statement valid or invalid? If it is invalid, why?
72 = amount
2.14 What will the following code display?
val = 99
print('The value is', 'val')
2.15 Look at the following assignment statements:
value1 = 99
value2 = 45.9
value3 = 7.0
value4 = 7
value5 = 'abc'

After these statements execute, what is the Python data type of the values
referenced by each variable?
2.16 What will be displayed by the following program?
my_value = 99
my_value = 0
print(my_value)

2.6 Reading Input from the Keyboard


CONCEPT: Programs commonly need to read input typed by the user on the key-
board. We will use the Python functions to do this.

Most of the programs that you will write will need to read input and then perform an
operation on that input. In this section, we will discuss a basic input operation: reading
VideoNote
Reading Input
data that has been typed on the keyboard. When a program reads data from the keyboard,
from the usually it stores that data in a variable so it can be used later by the program.
Keyboard
In this book, we use Python’s built-in input function to read input from the keyboard. The
input function reads a piece of data that has been entered at the keyboard and returns that
piece of data, as a string, back to the program. You normally use the input function in an
assignment statement that follows this general format:
variable = input(prompt)
72 Chapter 2   Input, Processing, and Output

In the general format, prompt is a string that is displayed on the screen. The string’s pur-
pose is to instruct the user to enter a value; variable is the name of a variable that ref-
erences the data that was entered on the keyboard. Here is an example of a statement that
uses the input function to read data from the keyboard:
name = input('What is your name? ')

When this statement executes, the following things happen:


• The string 'What is your name? ' is displayed on the screen.
• The program pauses and waits for the user to type something on the keyboard and
then to press the Enter key.
• When the Enter key is pressed, the data that was typed is returned as a string and
assigned to the name variable.
To demonstrate, look at the following interactive session:
>>> name = input('What is your name? ') Enter
What is your name? Holly Enter
>>> print(name) Enter
Holly
>>>

When the first statement was entered, the interpreter displayed the prompt 'What is your
name? ' and waited for the user to enter some data. The user entered Holly and pressed
the Enter key. As a result, the string 'Holly' was assigned to the name variable. When the
second statement was entered, the interpreter displayed the value referenced by the name
variable.
Program 2-12 shows a complete program that uses the input function to read two strings
as input from the keyboard.

Program 2-12 (string_input.py)

1 # Get the user's first name.


2 first_name = input('Enter your first name: ')
3
4 # Get the user's last name.
5 last_name = input('Enter your last name: ')
6
7 # Print a greeting to the user.
8 print('Hello', first_name, last_name)

Program Output (with input shown in bold)


Enter your first name: Vinny Enter
Enter your last name: Brown Enter
Hello Vinny Brown

Take a closer look in line 2 at the string we used as a prompt:


'Enter your first name: '
2.6 Reading Input from the Keyboard 73

Notice the last character in the string, inside the quote marks, is a space. The same is true
for the following string, used as prompt in line 5:
'Enter your last name: '

We put a space character at the end of each string because the input function does not
automatically display a space after the prompt. When the user begins typing characters,
they appear on the screen immediately after the prompt. Making the last character in the
prompt a space visually separates the prompt from the user’s input on the screen.

Reading Numbers with the input Function


The input function always returns the user’s input as a string, even if the user enters
numeric data. For example, suppose you call the input function, type the number 72, and
press the Enter key. The value that is returned from the input function is the string '72'.
This can be a problem if you want to use the value in a math operation. Math operations
can be performed only on numeric values, not strings.
Fortunately, Python has built-in functions that you can use to convert a string to a numeric
type. Table 2-2 summarizes two of these functions.

Table 2-2 Data conversion functions


Function Description
int(item) You pass an argument to the int() function and it returns the argument’s
value converted to an int.
float(item) You pass an argument to the float() function and it returns the argument’s
value converted to a float.

For example, suppose you are writing a payroll program and you want to get the number
of hours that the user has worked. Look at the following code:
string_value = input('How many hours did you work? ')
hours = int(string_value)

The first statement gets the number of hours from the user and assigns that value as a string
to the string_value variable. The second statement calls the int() function, passing
string_value as an argument. The value referenced by string_value is converted to an
int and assigned to the hours variable.

This example illustrates how the int() function works, but it is inefficient because it cre-
ates two variables: one to hold the string that is returned from the input function, and
another to hold the integer that is returned from the int() function. The following code
shows a better approach. This one statement does all the work that the previously shown
two statements do, and it creates only one variable:
hours = int(input('How many hours did you work? '))
74 Chapter 2   Input, Processing, and Output

This one statement uses nested function calls. The value that is returned from the input
function is passed as an argument to the int() function. This is how it works:
• It calls the input function to get a value entered at the keyboard.
• The value that is returned from the input function (a string) is passed as an argument
to the int() function.
• The int value that is returned from the int() function is assigned to the hours variable.
After this statement executes, the hours variable is assigned the value entered at the key-
board, converted to an int.
Let’s look at another example. Suppose you want to get the user’s hourly pay rate. The fol-
lowing statement prompts the user to enter that value at the keyboard, converts the value
to a float, and assigns it to the pay_rate variable:
pay_rate = float(input('What is your hourly pay rate? '))

This is how it works:


• It calls the input function to get a value entered at the keyboard.
• The value that is returned from the input function (a string) is passed as an argument
to the float() function.
• The float value that is returned from the float() function is assigned to the pay_
rate variable.

After this statement executes, the pay_rate variable is assigned the value entered at the
keyboard, converted to a float.
Program 2-13 shows a complete program that uses the input function to read a string, an
int, and a float, as input from the keyboard.

Program 2-13 (input.py)

1 # Get the user's name, age, and income.


2 name = input('What is your name? ')
3 age = int(input('What is your age? '))
4 income = float(input('What is your income? '))
5
6 # Display the data.
7 print('Here is the data you entered:')
8 print('Name:', name)
9 print('Age:', age)
10 print('Income:', income)

Program Output (with input shown in bold)


What is your name? Chris Enter
What is your age? 25 Enter
What is your income? 75000.0
Here is the data you entered:
Name: Chris
Age: 25
Income: 75000.0
2.7 Performing Calculations 75

Let’s take a closer look at the code:


• Line 2 prompts the user to enter his or her name. The value that is entered is assigned,
as a string, to the name variable.
• Line 3 prompts the user to enter his or her age. The value that is entered is converted
to an int and assigned to the age variable.
• Line 4 prompts the user to enter his or her income. The value that is entered is con-
verted to a float and assigned to the income variable.
• Lines 7 through 10 display the values that the user entered.
The int() and float() functions work only if the item that is being converted contains
a valid numeric value. If the argument cannot be converted to the specified data type, an
error known as an exception occurs. An exception is an unexpected error that occurs while
a program is running, causing the program to halt if the error is not properly dealt with.
For example, look at the following interactive mode session:
>>> age = int(input('What is your age? ')) Enter
What is your age? xyz Enter
Traceback (most recent call last):
File "<pyshell#81>", line 1, in <module>
    
age = int(input('What is your age? '))
ValueError: invalid literal for int() with base 10: 'xyz'
>>>

NOTE: In this section, we mentioned the user. The user is simply any hypothetical
person that is using a program and providing input for it. The user is sometimes called
the end user.

Checkpoint
2.17 You need the user of a program to enter a customer’s last name. Write a statement
that prompts the user to enter this data and assigns the input to a variable.
2.18 You need the user of a program to enter the amount of sales for the week. Write a
statement that prompts the user to enter this data and assigns the input to a variable.

2.7 Performing Calculations


CONCEPT: Python has numerous operators that can be used to perform ­mathematical
calculations.

Most real-world algorithms require calculations to be performed. A programmer’s tools


for performing calculations are math operators. Table 2-3 lists the math operators that are
provided by the Python language.
Programmers use the operators shown in Table 2-3 to create math expressions. A math
expression performs a calculation and gives a value. The following is an example of a
simple math expression:
12 + 2
76 Chapter 2   Input, Processing, and Output

Table 2-3 Python math operators


Symbol Operation Description
+ Addition Adds two numbers
− Subtraction Subtracts one number from another
* Multiplication Multiplies one number by another
/ Division Divides one number by another and gives the result as
a floating-point number
// Integer division Divides one number by another and gives the result as
a whole number
% Remainder Divides one number by another and gives the remainder
** Exponent Raises a number to a power

The values on the right and left of the + operator are called operands. These are values that
the + operator adds together. If you type this expression in interactive mode, you will see
that it gives the value 14:
>>> 12 + 2 Enter
14
>>>

Variables may also be used in a math expression. For example, suppose we have two variables
named hours and pay_rate. The following math expression uses the * operator to multiply
the value referenced by the hours variable by the value referenced by the pay_rate variable:
hours * pay_rate

When we use a math expression to calculate a value, normally we want to save that value
in memory so we can use it again in the program. We do this with an assignment statement.
Program 2-14 shows an example.

Program 2-14 (simple_math.py)

1 # Assign a value to the salary variable.


2 salary = 2500.0
3
4 # Assign a value to the bonus variable.
5 bonus = 1200.0
6
7 # Calculate the total pay by adding salary
8 # and bonus. Assign the result to pay.
9 pay = salary + bonus
10
11 # Display the pay.
12 print(‘Your pay is’, pay)

Program Output
Your pay is 3700.0

You might also like