You are on page 1of 36

CHAPTER 2

INPUT,
PROCESSING,
AND OUTPUT
Part 3

Variables
• Variable: name that represents a value in the computer’s memory
o Used to access and manipulate data stored in memory
o A variable references the value it represents

• Assignment statement: used to create a variable and make it reference


data
• General format : variable = expression
29
• Example : age = 29
age
• Assignment operator: the equal sign (=)

1
Variables (cont’)
• In assignment statement, variable receiving value must be on left side
• A variable can be passed as an argument to a function

• Variable name should not be enclosed in quote marks


• You can only use a variable if a value is assigned to it
• E.g.:
width = 10
print(width)
print("width")
3

Variable Naming Rules


• Rules for naming variables in Python:
1. Variable name cannot be a Python keyword (next slide)
print
2. Variable name cannot contain spaces
prod ID prodID
3. First character must be a letter or an underscore(_)
1player _prod
4. After first character may use letters, digits, or underscores
team1 team_1 the1stTeam
5. Variable names are case sensitive
studName ≠ studname 4

2
Variable Naming Rules
Keywords
and with print global try
del assert class except for
from else exec is lambda
not if in or elif
while pass raise import break
as yield continue return finally
def
5

Variable Naming Rules


• Variable name should reflect its use, short and meaningful
• E.g.s: y12, sum, tax_rate, taxRate, TAX , IF

3
Exercise:
Variable Name legal or illegal?
a. Units_per_day
b. DayOfWeek
c. 3dGraph
d. June1997
e. “X”
f. Error flag
g. Mixture#3

Variable Reassignment
• Variables can reference different values while program is running
• Garbage collection: removal of values that are no longer referenced by
variables
o Carried out automatically by Python interpreter

4
Variable Reassignment
• A variable can refer to item of any type
o Variable that has been assigned to one type can be reassigned to
another type
• E.g.1 :
dollars = 2.75
print("I have", dollars, "in my account.")
#Reassign dollars so it references a different value.
dollars = 99.95
print("But now I have", dollars, "in my account!")
9

Swapping variable values


x = 1
y = 2
temp = x # Save x in a temp variable
x = y # Assign the value in y to x
y = temp # Assign the value in temp to y

• Equivalent to:
x, y = y, x # Swap x with y

10

5
Multiple Assignments

• If a value is assigned to multiple variables, you can use a syntax like


this:
a = b = c = 1
• which is equivalent to:
c = 1
b = c
a = b

11

Numeric Data Types, Literals, and the str Data Type


• Data types: categorize value in memory
o e.g., int for integer, float for real number, str used for storing
strings in memory
• Numeric literal: number written in a program
o No decimal point considered int, otherwise, considered float

• Some operations behave differently depending on data type


• You cannot write currency symbols, spaces, or commas in numeric
literals
value = $4,567.99 ✕

12

6
Data Types
Data types
Sequence
Numeric Dictionary Boolean Set
Type
True, False
Integer 1, 567 Strings “Hello”

Complex
List
Number

Float 1.23, 9000.00


Tuple
13

Reassigning a Variable to a Different Type


• A variable in Python can refer to items of any type

x = 99
print(x)

x = "Take me to your leader"


print (x)

14

7
Exercise
1. What will the following code display? Correction?
val = 99
print("The value is", "val")

2. After these statements execute, what is the Python data type of


the values referenced by each variable?
value1 = 99
value2 = 45.9
value3 = "abc"
15

Exercise
3. What will be displayed by the following program?
my_value = 99
my_value = 0
print(my_value)

16

8
Named Constants
• The value of a named constant or simply constant represents permanent
data that never changes.
• Use all UPPERCASE letters to name a constant.
# Assign a radius
radius = 20 # radius is now 20
PI = 3.141592 # PI is a constant
area = radius * radius * PI # Compute area
cir = 2 * radius * PI # Compute circumference
# Display results
print("The area is", area)
print("The circumference is", cir)
17

Named Constants
• There are three benefits of using constants:
1. You don’t have to repeatedly type the same value if it is used
multiple times.

radius = 20
PI = 3.141592
area = radius * radius * PI
3.141592
cir = 2 * radius * 3.141592
PI
print("The area is", area)
print("The circumference is", cir)

18

9
Named Constants
• There are three benefits of using constants:
2. If you have to change the constant’s value (e.g., from 3.14 to
3.14159 for PI), you need to change it only in a single location in the
source code.

radius = 20
PI = 3.14
3.141592
area = radius * radius * PI
cir = 2 * radius * PI
print("The area is", area)
print("The circumference is", cir)
19

Named Constants
• There are three benefits of using constants:
3. Descriptive names make the program easy to read.

PI = 3.141592
cir = 2 * radius * PI

SERVICETAX = 0.06
taxAmount = total * SERVICETAX

20

10
Exercise
1. Given that the speed of light is 299792458 m/s, write a statement to create
a defined constant for the value.

2. Write program statements that uses defined constants for the vowels in the
alphabet.

21

Expression
• An expression represents a computation involving values, variables,
and operators that, taken together, evaluate to a value.
• E.g.s.:
x = 1 # Assign 1 to variable x
y = 3 # Assign 3 to variable y
radius = 1.0 # Assign 1.0 to variable radius

# Assign the value of the expression to x


x = 5 * (3 / 2) + 3 * 2 #13.5

x = y + 1 # Assign the addition of y and 1 to x


area = radius * radius * 3.14159 # Compute area
22

11
START

Reading Input from the Keyboard Read


no1

• Most programs need to read input from the user Read


• Built-in input function reads input from keyboard no2

• Format: variable = input(prompt) sum =


no1 + no2
• Does not automatically display a space after the prompt
Display
sum

END

23

Reading Input from the Keyboard


• E.g.: name = input("Enter your name: ")
o The string Enter your name: " is displayed on the screen.
o The program pauses and waits for the user to type something on the
keyboard and then to press the Enter key.
o When the Enter key is pressed, the data that was typed is returned as
a string and assigned to the name variable.

24

12
Reading Numbers with the input Function
• Built-in functions convert between data types
o int(item) converts item to an int
o float(item) converts item to a float
o Type conversion only works if item is valid numeric value, otherwise,
throws exception
o int and float functions execute faster than eval function.

25

Reading Numbers with the input Function


• Nested function call: general format:

function1(function2(argument))
o value returned by function2 is passed to function1
• E.g.:
hours = int(input("How many hours did you work? "))

26

13
Reading Input from the Console
1. Use the input function
• name = input("What is your name: ")

2. Use the eval function


• value = eval(input(stringVariable))
• eval("51 + (54 * (3 + 2))") #returns 321

27

e.g.: 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. Program Output (with input shown in bold)
6. # Display the data. What is your name? Chris
7. print("Here is the data you entered:") What is your age? 25
What is your income? 75000.0
8. print("Name:", name) Here is the data you entered:
9. print("Age:", age) Name: Chris
10. print("Income:", income) Age: 25
Income: 75000.0
28

14
LISTING 2.3: ComputeAverage.py
• Key in the following program and run it:
# Prompt the user to enter three numbers
number1 = eval(input("Enter the first number: "))
number2 = eval(input("Enter the second number: "))
number3 = eval(input("Enter the third number: "))

# Compute average
avg = (number1 + number2 + number3) / 3

# Display result
print("The average of", number1, number2, number3,"is", avg) 29

Simultaneous Assignment
• Syntax:
var1, var2, ..., varn = exp1, exp2, ..., expn
• It tells Python to evaluate all the expressions on the right and assign them
to the corresponding variable on the left simultaneously.
• E.g.:
num1, num2 = eval(input("Enter two numbers separated by commas: "))

• Is equivalent to:
num1 = eval(input("Enter the first number: "))
num2 = eval(input("Enter the second number: "))

30

15
LISTING 2.4 ComputeAverageWithSimultaneousAssignment.py

1. # Prompt the user to enter two numbers


2. num1, num2= eval(input("Enter two numbers separated by commas: "))
3. # line 2 obtains multiple input in one statement
4.
5. # Compute average
6. average = (num1 + num2) / 2
7.
8. #Display result
9. print ("The average of", num1,num2, "is ", average)

Enter two numbers separated by commas: 5, 9


The average of 5 9 is 7.0

31

Exercise
Write a python program that reads score for 3 subjects
through a single statement.
Then, the program should calculate and display the sum (add
up all the scores) .
Sample output:
Enter score for 3 subjects: 20,80,55
Total is 155

16
Library Modules
• A library module is a file with extension .py
o Contains functions and variables
o Can be used (imported) by any program
o can be created in IDLE or any text editor
o Looks like an ordinary Python program
• To gain access to the functions and variables:
o place a statement of the form import moduleName at the
beginning of the program

Built-in Functions
>>> max(2, 3, 4) # Returns a maximum number
4
>>> min(2, 3, 4) # Returns a minimum number
2
>>> round(3.51) # Rounds to its nearest integer
4
>>> round(3.4) # Rounds to its nearest integer
3
>>> abs(-3) # Returns the absolute value i.e. |-3|
3
>>> pow(2, 3) # Same as 2 ** 3 (23)
8
34

17
Mathematical Functions
Function Description Example
fabs(x) Returns the absolute value for x as a float. fabs(-2) is 2.0
ceil(x) Rounds x up to its nearest integer and returns ceil(2.1) is 3
that integer.
floor(x) Rounds x down to its nearest integer and floor(2.1) is 2
returns that integer.
exp(x) Returns the exponential function of x (ex). exp(1) is 2.71828
log(x) Returns the natural logarithm of x. log(2.71828) is 1.0
log(x, base) Returns the logarithm of x for the log(100, 10) is
specified base. 2.0

Mathematical Functions
Function Description Example
sqrt(x) Returns the square root of x. sqrt(4.0) is 2
sin(x) Returns the sine of x. x represents an sin(3.14159 / 2) is 1
angle in radians. sin(3.14159) is 0
asin(x) Returns the angle in radians for the asin(1.0) is 1.57
inverse of sine. asin(0.5) is 0.523599
cos(x) Returns the cosine of x. x represents an cos(3.14159 / 2) is 0
angle in radians. cos(3.14159) is -1
acos(x) Returns the angle in radians for the acos(1.0) is 0
inverse of cosine. acos(0.5) is 1.0472

18
Mathematical Functions
Function Description Example
tan(x) Returns the tangent of x. x represents tan(3.14159 / 4) is 1
an angle in radians. tan(0.0) is 0
degrees(x) Converts angle x from radians to degrees(1.57) is 90
degrees.
radians(x) Converts angle x from degrees to radians(90) is 1.57
radians.

LISTING 3.1 MathFunctions.py


import math # import Math module to use the math functions
# Test algebraic functions
print("exp(1.0) =", math .exp(1))
print("log(2.718) =", math .log(math.e)) #e=2.718
print("log10(10, 10) =", math .log(10, 10))
print("sqrt(4.0) =", math .sqrt(4.0))
# Test trigonometric functions
print("sin(PI / 2) =", math .sin(math.pi / 2))
print("cos(PI / 2) =", math .cos(math .pi / 2))
print("tan(PI / 2) =", math .tan(math .pi / 2))
print("degrees(1.57) =", math .degrees(1.57))
print("radians(90) =", math .radians(90))

38

19
Exercise:
Evaluate the following functions:
a)math.sqrt(4)
b)max(2, 3, 4)
c)min(2, 2, 1)
d)math.ceil(-2.5)
e)math.ceil(2.5)
f)math.floor(-2.5)
g)math.floor(2.5)

39

Displaying Multiple Items with the print


Function
• Python allows one to display multiple items with a single call to print

• Items are separated by commas when passed as arguments


• Arguments displayed in the order they are passed to the function
• Items are automatically separated by a space when displayed on
screen
• E.g.:
room = 503
print("I am staying in room number")
print(room)
print("I am staying in room number", room) 40

20
The int, float, eval, and str Functions
• E.g.s:
Output:
print(int(“23”))
print(float(“23”))
print(eval(“23”))
print(eval(“23.5”))
x = 5
print(eval(“23 + (2 * x)”))

41

Exercise
age = int(input(“Enter your age :”))
age = float(input(“Enter your age :”))
age = eval(input(“Enter your age :”))

1. Enter 25 to each statement above, what would be displayed?


2. Enter 2.5 to each statement above, what would be displayed?

42

21
The int, float, eval, and str Functions
• E.g.s:
1. int(4.8) 4 7. str(5.6)  ”5.6”
2. int(-4.8)  -4 8. String = str(5.) + "%"
3. int(4) 4 print(String)  5.0%
4. float(4.67)  4.67 9. String = 5.0 + "%"
5. float(-4)  -4.0 print(String)  Error
6. float(0)  0.0

43

Performing Calculations
• Math expression: performs calculation and gives a value
o Math operator: tool for performing calculation
o Operands: values surrounding operator
• Variables can be used as operands
o Resulting value typically assigned to variable

Math operator

total = qty * 1.50

operand
44

22
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
an integer
% Remainder Divides one number by another and gives the remainder
** Exponent Raises a number to a power
45

Performing Calculations
• Two types of division:
• / operator performs floating point division
• // operator performs integer division

• Positive results truncated, negative rounded away from zero


• E.g.: 5 / 2 is 2.5
5 // 2  2.5  2
-5 // 2  -2.5  -3
-4 // 3  -1.33  -2

46

23
Performing Calculations
• Modulus (%):
o Divides one number by another and gives the remainder
o Typically used to convert times and distances, and to detect odd
or even numbers
• E.g.: 7%6=1
12 % 4= 0
26 % 8 = 2
2 20 %
3 13 = 7 3 1 Quotient
3 7 4 12 8 26 Divisor 13 20 Dividend
6 12 24 13
1 0 2 7 Remainder

47

Performing Calculations
• Exponent operator (**):
o Raises a number to a power

• E.g.: x ** y = xy
4 ** 2 = 42 = 16

48

24
Operator Precedence and Grouping with
Parentheses
• Python operator precedence:
1. Operations enclosed in parentheses
• Forces operations to be performed before others
2. Exponentiation (**)
3. Multiplication (*), division (/ and //), and remainder (%)
4. Addition (+) and subtraction (-)
• Higher precedence performed first
• Same precedence operators execute from left to right
(5 + 3) * 6 / 2 + 4 ** 3
49

Expression Value

Exercise 5+2*4
10 / 2 – 3
8 + 12 * 2 – 4
6–3*2+7–1
(5 + 2) * 4
10 / (5 – 3)
8 + 12 * (6 – 2)
(6 – 3) * (2 + 7) / 3
4 ** 2
17 % 3
17 // 3

25
Problem: Displaying Time
Write a program that obtains minutes and seconds from seconds.
Sample output:
Enter an integer for seconds: 500
500 seconds is 8 minutes and 20 seconds

LISTING 2.5 DisplayTime.py


1. # Prompt the user for input
2. seconds = eval(input("Enter an integer for seconds: "))
3. # Get minutes and remaining seconds
4. minutes = seconds // 60 # Find minutes in seconds
5. remainingSeconds = seconds % 60 # Seconds remaining
6. print(seconds, "seconds is", minutes, "minutes and", remainingSeconds, "seconds")
51

Converting Math Formulas to


Programming Statements
• Operator required for any mathematical operation
• When converting mathematical expression to programming statement:
o May need to add multiplication operators
o May need to insert parentheses

• E.g.:
Algebraic Expression Python Statement Algebraic Expression Python Statement
(3)(12) 3 * 12 A = (x + 2) / (b – 1)
4xy 4*x*y
P = F / (1 + r) ** n
y=3*x/2
52

26
Augmented Assignment Operators
• Very often the current value of a variable is used, modified, and then
reassigned back to the same variable.
• The operators +, -, *, /, //, %, and ** can be combined with the
assignment operator(=) to form augmented assignment operators.
Operator Example Equivalent
+= i += 8 i = i + 8 There are no spaces in the
-= f -= 8.0 f = f - 8.0 augmented assignment
*= i *= 8 i = i * 8 operators.
/= i /= 8 i = i / 8 For example, + = should be
//= i //= 8 i = i // 8 +=.
%= i %= 8 i = i % 8
**= i **= 8 i = i ** 8 53

Exercise:
Assume that a = 2, and that each expression is independent. What are
the results of the following expressions?
1) a += 4
2) a *= 4
3) a /= 5
4) a %= 4
5) a *= 8 + 6

54

27
Mixed-Type Expressions & Data Type
Conversion
• Data type resulting from math operation depends on data types of
operands:
o Two int values: result is an int
o Two float values: result is a float
o int and float: result is a float

• Mixed-type expression
oE.g.: 5 * 2.0  10.0

• Type conversion of float to int causes truncation of fractional part


o E.g.: int(2.6) 2
int(-2.9)  -2
float(2)  2.0 55

Exercise:
Are the following statements correct? If so, show their printout.

value = 4.6
a) print(int(value))
b) print(round(value))
c) print(eval("4 * 5 + 2"))
d) print(int("04"))
e) print(int("4.5"))
f) print(eval("04"))
56

28
Breaking Long Statements into Multiple
Lines
• Long statements cannot be viewed on screen without scrolling and
cannot be printed without cutting off
• Multiline continuation character (\): Allows to break a statement into
multiple lines
• E.g.s:
print(“my first name is ” \
“John”)

Output:
my first name is John
57

More About Data Output


• print function displays line of output
o Newline character at end of printed data
o Special argument end="delimiter“
 causes print to place delimiter at end of data instead of
newline character

58

29
More About Data Output
print("One") One<newline>
One
print("Two") Two<newline>
Two
print("Three") Three<newline>
Three
print("One", end=" ")
print("Two", end=" ")
print("Three") One Two Three
print("One", end="")
print("Two", end="")
print("Three") OneTwoThree 59

More About Data Output


• print function uses space as item separator
o Special argument sep="delimiter"
causes print to use delimiter as item separator

• Examples: >>> print("One", "Two", "Three")


One Two Three
>>> print("One", "Two", "Three", sep="**")
One**Two**Three
>>> print("One", "Two", "Three",sep="~~~")
One~~~Two~~~Three
>>> print("One", "Two", "Three", sep="")
OneTwoThree 60

30
Practical : Justification methods
##Demonstrate justification of output using methods ljust(n), rjust(n),
##and center(n)
print("Rank".ljust(5), "Player".ljust(15), "HR".rjust(3))
print("1".center(5), "Barry".ljust(15), "2".rjust(3))
print("22".center(5), "Aaron Hank".ljust(15), "55".rjust(3))
print("333".center(5), "Babe Ruth".ljust(15), "722".rjust(3))
1 2 3 4 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 3
R a n k P l a y e r H R
1 B a r r y 2
2 2 A a r o n H a n K 5 5
3 3 3 B a b e R u t h 7 612 2

Practical : Justification output


##Demonstrate justification of output using format method
print("{0:^5s}{1:<15s}{2:>3s}".format("Rank", "Player", "HR"))
print("{0:^5s}{1:<15s}{2:>3n}".format("1", "Barry", 762))
print("{0:^5s}{1:<15s}{2:>3n}".format("2", "Aaron Hank", 75))
print("{0:^5s}{1:<15s}{2:>3n}".format("3", "Babe Ruth", 7)

62

31
Practical : Justification output
spaces

print("{0 :^ 5 s}{1 :< 15 s}{2 :> 3 s}".format("Rank", "Player", "HR"))

center justify right justify


left justify Data type

63

More About Data Output (cont"d.)


• Special characters appearing in string literal
• Preceded by backslash (\)
o Examples: newline (\n), horizontal tab (\t)

• Treated as commands embedded in string


• When + operator used on two strings in performs string
concatenation
• Useful for breaking up a long string literal

64

32
Escape Sequences
Description Escape Sequence Unicode
Tab \t \u0009
Linefeed (newline, EOL, line break) \n \u000A
Backslash \\ \u005C
Single Quote \" \u0027
Double Quote \" \u0022

65

Escape Sequences e.g.s.:


1. print("Mon\tTues\tWed")
Mon Tues Wed
2. print("Your assignment is to read \"Hamlet\" by tomorrow.")
print(‘I\’m ready to begin.’)
Your assignment is to read "Hamlet" by tomorrow.
I’m ready to begin.
3. print("ali\tconnie\tbaba".expandtabs(5))
ali connie baba
4. print("The path is C:\\temp\\data.")
The path is C:\temp\data. 66

33
Displaying Multiple Items with the + Operator
• When used with two strings, it performs string concatenation. This
means that it appends one string to another.
• E.g.s:
1. print("This is " + "one string.")
This is one string.
2. print("Enter the amount of " + \
"sales for each day and " + \
"press Enter.")
Enter the amount of sales for each day and press Enter.
67

Formatting Numbers
• Can format display of numbers on screen using built-in format
function
• Two arguments:
1. Numeric value to be formatted
2. Format specifier
• Returns string containing formatted number
• Format specifier typically includes precision(12 significant digits)
and data type
• The % symbol can be used in the format string of format
function to format number as percentage
68

34
Formatting Numbers : e.g.s
>>> print(format(123456789.456, ",.2f"))
123,456,789.46 #Inserting Comma Separators
>>> print(format(12345.6789, ",f"))
12,345.678900
>>> print("The number is", format(10345.6789, "12,.2f"))
The number is 10,345.68
>>> print(format(0.5, "%"))
50.000000% # multiply by 100, default 6 digits after .
>>> print(format(0.5, ".0%"))
50% # zero as precision
>>> print(format(0.51, ".2%"))
51.00% 69

Formatting Numbers
• Can be used to indicate scientific notation, comma separators, and
the minimum field width used to display the value
• The letter e indicating the exponent. (If you use uppercase E in the
format specifier, the result will contain an uppercase E indicating the
exponent.)
• E.g.s:
>>> print(format(12345.6789, "e"))
1.234568e+04
>>> print(format(12345.6789, ".2E"))
1.23E+04
70

35
Formatting Numbers (cont"d.)
• To format an integer using format function:
o Use d as the type designator
o Can’t specify precision
o Can still use format function to set field width or comma separator
o Default : right-justify

• E.g.s:
>>> print(format(12345, "8d"))
12345 # three spaces in front
>>> print(format(12345, "8,d")) # comma counted as 1 digit
12,345
71

Summary
• This chapter covered:
o The program development cycle, tools for program design, and the
design process
o Ways in which programs can receive input, particularly from the
keyboard
o Ways in which programs can present and format output
o Use of comments in programs
o Uses of variables
o Tools for performing calculations in programs

72

36

You might also like