Professional Documents
Culture Documents
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
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
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
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
• Equivalent to:
x, y = y, x # Swap x with y
10
5
Multiple Assignments
11
12
6
Data Types
Data types
Sequence
Numeric Dictionary Boolean Set
Type
True, False
Integer 1, 567 Strings “Hello”
Complex
List
Number
x = 99
print(x)
14
7
Exercise
1. What will the following code display? Correction?
val = 99
print("The value is", "val")
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
11
START
END
23
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
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: ")
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
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.
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
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 :”))
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
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
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
• 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
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
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
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
62
31
Practical : Justification output
spaces
63
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
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