Number Input String Input - Kent

[Pages:6]Chapter 2 ? Part 2 Sections 2.6 -2.8

Bonita Sharif

1

Reading Keyboard Input

? A program can receive input from the keyboard ? Python inbuilt functions are used to read input

typed by the user

? A function is prewritten code to perform a certain operation and returns a value back to the program.

? The functions we will use for input are

? input() : used to read numeric data ? raw_input() : used to read strings

? Input is stored in a variable

2

Number Input

? We use the input function in an assignment statement to read input using the following template

variable = input(prompt)

? Example 1

hoursWorked = input(`How many hours did you work?')

3

String Input

? We use the raw_input function in an assignment statement to read input using the following template

variable = raw_input(prompt)

? Example 1

name = raw_input(`What is your name?') print `Hello', name

4

Combining Number and String Input

# This program asks you enter your name and age # It then displays a greeting and tells you how old you

are

firstName = raw_input(`What is your first name?')

lastName = raw_input(`What is your last name?')

age = input(`Enter your age: ');

print `Hello', firstName, lastName

print `You are',age,'years old.'

Notice the space

5

Checkpoint 2.17

? You need the user of a program to enter the amount of sales for the week. Write a program statement that prompts the user to enter this data and assign the input to a variable

6

1

Operators

? Math operators are used for calculations

+

Addition

-

Subtraction

*

Multiplication

/

Division (output the quotient)

%

Remainder (output the remainder)

**

Exponent (raise a number to a power)

2**3 is equivalent to 23

7

Math Expressions

? A math expression performs a calculation and gives a value

? Examples

2**6 # outputs 64, 2 and 6 are operands 4%2 # outputs 0

What is the output for the following statements?

print 21%6 print 1/3 #integer division,truncation may occur print 1.0/3 #floating point division

8

Calculating Percentages

? In order to calculate a percentage, convert the percentage to a decimal number

? E.g., 50% is equal to 0.50

? Example

? Calculate the sale price of an item after discount. The store offers a 10% discount on all items.

? Write the algorithm in pseudocode

? What are the Input, process, output elements?

9

Calculate sale price of an item

# This program gets an item's original price and # calculates its sale price, with a 10% discount.

# Get the item's original price. original_price = input("Enter the item's original

price: ")

# Calculate the amount of the discount. discount = original_price * 0.10

# Calculate the sale price. sale_price = original_price - discount

# Display the sale price. print 'The sale price is', sale_price

10

Operator Precedence

? Defines the order in which different operators in a compound expression are grouped.

? Precedence from high to low

** * / % (execute from left to right) + - (execute from left to right)

11

Parentheses

? Used to force execution of certain parts of an expression together

? Example

(12 + 6) / 3 * (4 / 2)

12

2

Converting expressions

? You should be able to convert algebraic expressions into a python statement

? Example

? Convert the following expression into a python statement P=F/(1+r)n

13

Data Type Conversions

? The result of an operation of two int values will result in an int.

? In case of a mixed type expression (where the operands are of different types

? int value will be converted to float (temporarily ? An implicit conversion occurs)

? Result will be a float

? Explicit conversions are sometimes required. See next example

14

Explicit type conversion example

# Get the number of books the user plans to read. books = input('How many books do you want to read? ') # Get the number of months it will take to read them. months = input('How many months will it take? ') # Calculate the number of books per month. per_month = float(books) / months # Display the result. print 'You will read', per_month, 'books per month.'

15

More on Conversions

? When a float is converted to an int

? Fractional part is discarded

? When an int is converted to a float

? A decimal point is added

16

Formatting long lines of code

? If a statement is too long, the backslash `\' can be used to tell the python interpreter that the statement is continued on the next line

? Example

print `Your name is' first_name, \ last_name, `and you are' \ age, `years old'

17

Formatting Output

? An escape character is a special character that is preceded with a \ and appears in a string literal

? \n : new line ? \t : tab ? \" : double quote ? \' : single quote ? \\ : backslash ? \a : system beep

? The newline character(\n) is a special character that causes the output to advance to the next line.

18

3

Suppressing print's newline

? Example

print `first line', print `second line', print `third line'

Comma suppresses the newline inherent in the print statement

19

Using the \n character

This statement

print `first line\nsecond line\nthird line'

is equivalent to the following three statements

print `first line' print `second line' print `third line'

20

Escape Character Examples

? Tab escape character

print "1\t2\t3\t4\t5"

? Quote escape characters

print `I like reading \`Goodnight Moon\' ' print "I like reading \"Goodnight Moon\" "

(remember the usage of double quotes in a single quoted string and vice versa we learnt earlier.)

? Backslash characters

print "The path is C:\\Data"

21

The + Operator

? + behaves differently when given different operand types such as numbers and strings

? When the operands are numbers, addition is performed

? When the operands are strings, concatenation occurs

? Useful for breaking up a print statement that spans many lines.

print `This is one '+`string.'

22

Exercise

Do the following two groups of statements give the same output?

print `Enter the amount of ' + \ `sales for each day and ' + \ `press Enter'

print `Enter the amount of ' , print `sales for each day and' , print `press Enter'

23

Formatting Numbers

? Usually numbers of the data type float are printed out with 12 significant digits

? How do you reduce the number if not needed?

? Using the string format operator (%)

? General format

print string % number

? string contains text and/or a formatting specifier which is a set of characters that specify how a value is formatted

? number is a variable or expression that gives a numeric value

? The value of number will be formatted according to the formatting specifier in the string

24

4

Example

String format

pi_value = 3.14159

operator

print `The value of pi is %.2f' % pi_value

Format specifier

Number

The output of the above statement is

The value of pi is 3.14

25

Format specifiers

? The f in a format specifier indicates that the number is a floating-point number.

? The number after the . indicates that the number should be rounded to two decimal places

? Notice that the format specifier itself starts with a %

? Examples of format specifiers

? %.2f ? %.4f

26

Formatting Multiple Values

? print string % (number, number,....) ? string will contain all the formatting specifiers you

need ? (number, number,...) is a list of variables or

expressions ? The formatting specifiers in the string are applied

to the list of numbers in order from left to right ? Example

print `The values are %.1f and %.4f" % (5.434, 6.5553)

27

Formatting Field Width

? A formatting specifier can also include minimum field width i.e., the number of spaces used to display a value.

? The number before the . in a formatting specifier specifies the number of spaces reserved on screen for the value

? Field width is useful to print things neatly in columns. ? Example

myValue= 3.32546 print `The value is:%7.3' % myValue

Output will be

The value is: 3.325

There are two spaces here 28

Formatting Integers

? Use the %d format specifier for integers ? Field width is specified before the d in the

specifier ? Example

? age = 30 ? print `I am %d years old' % age

? Output is

? I am 30 years old

29

Formatting Strings

? Use the %s format specifier for strings ? For width of string specify the number

before the s in the format specifier

30

5

# This program displays a set of salesperson # names and units sold in two columns.

# Assign the names to variables. salesperson1 = 'Graves' salesperson2 = 'Harrison' salesperson3 = 'Hoyle' salesperson4 = 'Kramer' salesperson5 = 'Smith'

# Assign the units sold to variables. units1 = 1456.78 units2 = 2890.55 units3 = 946.77 units4 = 2678.91 units5 = 1287.87

# Display the data. print '%15s %15s' % ('Salesperson', 'Units Sold') print '%15s %15d' % (salesperson1, units1) print '%15s %15d' % (salesperson2, units2) print '%15s %15d' % (salesperson3, units3) print '%15s %15d' % (salesperson4, units4) print '%15s %15d' % (salesperson5, units5)

Calculating Average

# Get three test scores and assign them to the # test1, test2, and test3 variables. test1 = input('Enter the first test score: ') test2 = input('Enter the second test score: ') test3 = input('Enter the third test score: ')

# Calculate the average of the three scores # and assign the result to the average variable. average = (test1 + test2 + test3) / 3.0

# Display the average. print 'The average score is: %10.2f' % average

31

32

What is the problem with this code?

# This program is about assignment to variables. # Author: Bonita Sharif # Date: 9/2/08

# Create three variables of the numeric type number1 = 3 number2 = 4 number3 = 2 print number1, number4

33

6

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download