Arithmetic in Python

KhaledMaarof
Chapter2sept182018.pdf

An Introduction to Computer Science with Java, Python and C++ Community College of Philadelphia edition Copyright 2017 by C.W. Herbert, all rights reserved.

Last edited August 28, 2017 by C. W. Herbert

This document is a draft of a chapter from An Introduction to Computer Science with Java, Python and C++, written by Charles

Herbert. It is available free of charge for students in Computer Science courses at Community College of Philadelphia during the

Fall 2017 semester. It may not be reproduced or distributed for any other purposes without proper prior permission.

Please report any typos, other errors, or suggestions for improving the text to cherbert@ccp.edu

Chapter 2 – Reading, Writing, and Arithmetic in Python

Contents

Chapter 2 Learning Outcomes ....................................................................... Error! Bookmark not defined.

Data Types and Variables .................................................................................................. 2

Math in Python ............................................................................................................... 14

Assignment Statements and Expressions ............................................................................................... 14

Polymorphism ......................................................................................................................................... 14

Arithmetic Operations ............................................................................................................................ 15

Quotients and Remainders ..................................................................................................................... 16

Built-In Functions and Math Module Functions in Python ..................................................................... 16

Type Conversion and Type Casting ......................................................................................................... 17

Math Module Functions .......................................................................................................................... 18

Order of Operations ................................................................................................................................ 20

Commutative and Associative Behavior ................................................................................................. 21

Data Streams and System Console I/O in Python ........................................................... 23

Data Streams ........................................................................................................................................... 23

Console Output in Python ....................................................................................................................... 24

Console Input in Python .......................................................................................................................... 25

Documentation First Programming ................................................................................ 27

In class exercise Lab 2A – Console I/O: Age in Days ............................................................................... 31

Intro to CSCI with Java, Python, and C++ Chapter 2 page 2

Chapter 2 – Reading, Writing, and Arithmetic in Python

This chapter introduces basic elements of Python programming needed to create simple I-P-O software,

along with related topics from Computer Science.

I-P-O refers to Input, Processing and Output. Raw data is put into the computer, the computer then

processes the data, and puts out the result. In a broad way, all computer software is I-P-O software, but

we will focus on simple software that gets data from a user, does something with the data, then gives us

the result right away. We will learn about Python instructions to read data from the user, perform

arithmetic, and display the result. We will also learn a bit about how computers format data for storage

and processing.

Lessons 1 discusses data types and variables in Python, including math and simple assignment

statements.

Lessons 2 looks at math and simple assignment statement in Python.

Lesson 3 introduces simple console I/O, which is text input and output based on data streams. We won’t

learn how to read and write data files in this chapter – that comes later, but it is based on what we learn

in this chapter.

Lessons 4 describes a simple design technique for beginning programmers – documentation-first

programming.

The lab exercise in the chapter will provide you with some practice using most of the material covered in

the chapter.

Note: This chapter refers to the Python 3 programming language and assumes that you have the

Python 3 language ready to use on your computer. Appendix A describes downloading and

installing Python.

Data Types and Variables

In this lesson we will look at how computers commonly format data for storage and processing and how

variables are used in Python to refer to data being processed.

Data Types

A data type is a format used to store data in the memory of a computer. Formats for data depend on

what the data means and how the data will be used. Numbers, for example, are stored in formats that

allow the computer to quickly perform arithmetic with the data. Character or text data can be stored in

simpler formats mapped to images for displaying and printing the data. Using specialized data types

allows computers to process data more efficiently – using less memory to store data and less time to

process data.

Most programming languages have built-in data types that each fall into one of four different

categories:

Intro to CSCI with Java, Python, and C++ Chapter 2 page 3

• Boolean data is used to keep track of true and false values.

• text data is composed of characters – the symbols we use in human languages, such as the Latin

alphabet used for the English language. The term string is often used to refer to a sequence of

text characters used as a unit of data.

• integer data is numeric data without fractions.

• floating-point data is numeric data with fractions, most often stored as decimal numbers with a

decimal point and decimal fractions. Computer often store this data in a format similar to

scientific notation.

Some languages have sequence datatypes, which store a sequence of data items of a simpler datatype,

such a set of numbers or a set of characters. The data type list in python is an example of a sequence

datatype. The str datatype in Python and the String datatype in Java are sequence datatypes, which

each store a set of text characters as a character String.

Specialized data types exist in different languages, such as data types for date and time. Pictures, sound

and video all have their own data types, such as JPEG, WAV and MP4 files.

Datatypes can also be defined by the programmer as object classes in object-oriented languages. We

will look at objects in more detail later in the semester when we begin to work with Java.

The next few paragraphs discuss how languages refer to data stored in a computer's memory. Specific

data types in Python are described after that.

Variables, Constants, and Literals

Data may be represented in computer programs as variables, constants, or literals.

A variable is a memory location holding a specific value, similar to a variable in algebra. A variable has a

symbolic name, which is used in a program to refer to the value stored in the variable. The stored value

can be changed, hence the name variable.

A constant refers to a value stored in memory which, once initialized, cannot be changed, hence the

name constant. Constants are similar to variables – symbolic names representing stored values –

however, once a value has been assigned to a constant, it cannot be changed. Python has no built-in

constants, although the Boolean values True and False can be used like constants.

A literal is a source code representation of a specific data value. The string “Hello World!” from Lab 1 in

Chapter 1 is an example of a string literal. A literal value in a computer program is said to be hardcoded

into the program. For example, in print (“Hello, World.”), The string “Hello, world.” is

hardcoded into the print instruction. The actual value is part of the program, not a variable holding the

value.

The use of variables and constants is preferred over hardcoding data, especially numeric data, because

hardcoding numeric data can lead to errors and inefficiency. Imagine that you will use the value

3.14159 many places in a program. Instead of typing 3.14159 each time you wish to use it, or copying

and pasting it many times, you could create a variable or constant pi, which equals 3.141589 and just

use that each time.

Intro to CSCI with Java, Python, and C++ Chapter 2 page 4

Hardcoding can also decrease a program's flexibility. Imagine a program that performs an economic

analysis of an airplane that can hold 153 passengers. If the number 153 is hardcoded into the program,

then the program could not be used to perform a similar analysis on a plane with 217 passengers

without modifying the code. Instead, If the number of passengers is a variable, then the software could

work with any size plane without re-writing the program.

Assignment statements set the value of a variable. Assignment statements use an equals sign in most

high-level languages, with the name of the variable on the left of the equals sign, and the literal value, or

an expression that derives the value, on the right. Here are some examples of assignment statements

from the Python language:

x = 3

root1 = (-b - math.sqrt(b**2 - 4*a*c) )/(2*a)

name = “Joe Smith”

citizen = True

Be careful – assignment statements might look like algebra expressions, but they are not. In most

programming languages, including Python, Java, and C++, the only thing that goes on the left of the

equals sign is the name of the variable being assigned a value.

The term name binding or just binding refers to establishing the connection between a name in a

computer program and a specific memory location holding data of a certain datatype.

The term data typing refers to establishing the data type of a variable (or other stored data) in a

computer program. Data typing and binding often happen together, but they are two separate things.

Binding matches the variable name used in a program to a memory location and typing matches the

formats the location with a datatype.

The languages Java and C++ use static binding and static data typing. In this case, static means that the

name and datatype are established before the program runs. A specific memory location and a specific

data type are associated with each variable before the instructions in a program are executed. The

variable's name and data type must be declared in the source code and they become fixed – they cannot

change as the program runs. The value of a variable can change, but not it's data type.

Python uses dynamic binding and dynamic data typing, in which a memory location and data type are

established for each variable as the program runs. In Python, the data type is determined from the way

in which the variable is used, and the datatype can change as the program runs. Datatype do not need

to be declared as in Java and C++. The two examples below show this.

Static binding is sometimes referred to as early binding, and dynamic binding is sometimes referred to

as late binding.

Intro to CSCI with Java, Python, and C++ Chapter 2 page 5

Java – static binding and static data typing

double qualityPoints, creditHours;

double gpa;

qualityPoints = 52.5;

creditHours = 15.0;

gpa = qualityPoints / creditHours;

system.out.println("the GPA is ", gpa);

gpa = "Hello, world!";

System.out.print("the GPA is ", gpa);

Python dynamic binding and dynamic data typing

qp = 52.5

cr = 15

gpa = qp/cr

print("the GPA is ", gpa, "\n")

gpa = "Hello, world!"

print("the GPA is ", gpa)

In the Java code above, the two instructions that start with double define the variables as double

precision floating-point data. Variable declarations are processed when the code is compiled – an

example of static binding and static data typing. A memory location is associated with the name of each

variable, along with its data type at compile time, before the program runs.

In the Python code above, no data declarations are required. The memory locations for variables and

their data types are defined by the values assigned to them in the assignment statements when the

program runs – an example of dynamic binding and dynamic data typing. The datatype of the value to

the right of the equal sign in a Python assignment statement will determine the data type of the variable

in which the value is stored.

In Python a variable's datatype can change as a program runs, but It cannot change in statically typed

languages such as Java and C++, where only a variable's value can change, but not its data type.

Defining a data type by the way in which a variable is used instead of by using a declaration is known as

duck typing (if it walks like a duck, etc.). Python uses duck typing. Java uses type declarations. qp

becomes a floating-point variable in the python code above because its assigned value, 52.5, is a

decimal fraction. cr becomes an integer because 15 is an integer. gpa becomes a floating-point value

because the result of the math expression qp/cr, is a decimal fraction.

Duck typing does not require explicit data type declarations. It is used in many languages that use

dynamic data typing.

The Python segment above will run

correctly as a program in Python. The

output is shown on the right. The first gpa

assignment statement assigns a floating-

point value to gpa. The output shows us

this is 3.5. The second gpa assignment

statement assigns the string value "Hello,

world!" to gpa. The same variable is used,

but the datatype changes from numeric to

character data as the program runs.

Intro to CSCI with Java, Python, and C++ Chapter 2 page 6

The instructions in the Java segment above will not work within a program. The program will generate a

data type mismatch exception when we try to assign a string value to a floating-point variable. Once the

data type of a statically typed variable has been established, it cannot change.

So, in summary, the Python language deals with variables and their data types by:

• using dynamic binding

• using dynamic data typing

• using context-based duck typing to determine a variable's data type

• allowing a variable's data type to be changed as the program runs.

Syntax and Variable Names

The syntax of a computer programming language is the set of rules that define the symbols used in the

language and the structure of the language. A computer processes a program written in a specific

language by first examining the code according to the syntax of that language.

In Python, for example, each instruction is one logical line of code, terminated by a newline character –

the character generated when you press the enter key. That rule is part of the syntax of the language.

No other special character is needed to mark the end of a Python instruction. This rule is part of the

syntax of the Python language.

The syntax of the language defines tokens for the language – individual pieces of code, usually a single

word – that mean something to the compiler or interpreter. The instructions in Python, such as print(),

are tokens that the interpreter understands as instructions. Some tokens are single characters, such as

the plus sign, which triggers an addition operation on numeric data in most languages.

Each token means something to the language, as defined by the syntax of the language. Compilers and

interpreters translate source code tokens into CPU instructions and their data based on the syntax of

the language.

Python's syntax, like the syntax for any language, has rules to define which tokens are variables and how

variables can be used. The syntax of a language also defines how variables can be named.

Intro to CSCI with Java, Python, and C++ Chapter 2 page 7

Here are the rules for variable names in Python:

• Variables names must start with a letter or an underscore character. They cannot start with a

number or a special character.

• letters, numbers and underscore characters may be used in variable names, but no other special

character (such as !, #, $, or %) may be used.

• Variable names in Python are case sensitive. Num1 and num1 are two different variables.

valid variable names

num1 sum Sum SUM _count hourly_rate

Invalid variables names

name reason 3x starts with a number Trump# special character hourly rate blank space

Python variables are "declared" by giving them a value in an assignment statement. A variable cannot

be used in Python until it has been given a value. In fact, a variable does not exist in Python until it has

been given a value in an assignment statement.

Reserved Words, also known as keywords are tokens that have special meaning. They cannot be used

as the names of variables or constants in a specific programming language. The following is a list of

keywords in Python:

and del from not while

as elif global or with

assert else if pass yield

break except import print

class exec in raise

continue finally is return

def for lambda try

Python has one of the shortest list of reserved words in any programming language. Java has 50

reserved words, C++ has 86, C# has 79, Swift has 71, and the original COBOL language had over 400.

Programming conventions are guidelines for the use of a programing language that most programmers

follow. Their use is not required, but highly recommended so that a programmer's work is compatible

with the work of other programmers and to make software source code easier to read and understand –

especially for people grading your programming assignments. Some programming languages have their

own programming conventions, particularly for the names of variables, methods, and object classes.

The Style Guide for Python Code (PEP 8, www.Python.org/dev/peps/pep-0008 )describes many of

conventions for Python programming, originated by Guido van Rossum. For example, the Style Guide

suggests that programmers should:

"never use the characters 'l' ( lowercase el ), 'O' ( uppercase letter oh )

or 'I' ( uppercase letter I ). … In some fonts these characters are

indistinguishable from the numerals one and zero." – Python PEP 8

three different variables

(case sensitive)

Intro to CSCI with Java, Python, and C++ Chapter 2 page 8

Many corporations have their own programing conventions, in addition to common programing

conventions for a language. Your instructor may suggest programming conventions for use in this

course.

Datatypes in Python

Python 3 has a variety of built-in datatypes. They fall into several categories: Boolean, numeric,

sequences, mappings, classes, instances, and exceptions. In this chapter we will only look at the most

commonly used datatypes in Python. We will see some of the others in later chapters.

Note: The datatypes in Python were originally based on those in the C programming language.

This does not mean much to new programmers, but it tells more experienced programmers

something about the formats Python software uses to store data..

Python interpreters often use the native data formats of the system on which a program is running.

Boolean Data

The answer to any true or false question, or the equivalent, such as yes corresponding to true and no

corresponding to false, can be stored as boolean data.

A checkbox on a job application keeping track of whether or not the applicant has a driver’s license, for

example, can be coded in Python as boolean data.

Figure 2 shows two questions from the Pennsylvania Voter Registration Form that each are Boolean

questions – they have yes or no answers that can correspond to the boolean values true or false.

A Boolean value data can be stored a single bit of data, but often computers use an entire byte to store

each Boolean value. Most computer memory is Byte addressable, which means each byte of memory

has its own memory address. Each bit then has a sub-address within the byte. To address a single bit, a

byte would need to be addressed, then the bit within the byte. It is faster for the computer to address

an entire byte than it is to address a bit within a byte. Using a byte to store a Boolean value wastes some

space, but speeds up a running program. This is a classic example of a tradeoff in modern computing –

wasting space, which is cheap, to speed up a running program.

Python has two Boolean literal constants, True and False. Notice that they are capitalized.

Remember, Python is case sensitive.

Figure 2 –

Boolean questions

Intro to CSCI with Java, Python, and C++ Chapter 2 page 9

Boolean assignment statements can have, on the right of the equals sign, the values True or False or

any valid logical expression that uses the Boolean operators and, or and not. Here are some examples:

citizen = True

onions = False

willing = True

able = True

ready = willing and able

running = power_on and not(broken)

switch = True

Here is an interesting quirk of the Python language: True is a Boolean literal, but true, with a lowercase

't', can be used as the name of a variable. So true can be False. Try the following Python code:

overtime = False

true = overtime

print(true)

The Boolean operators and, or, and not are used to manipulate true and false values in conditional

statements for branching and looping in Python. We will discuss their specific meaning and use in the

next chapter.

Text Data

Text data is made up of characters. A character is a single symbol from the alphabet of a language. In

English, the name “John”, for example, is made up of four characters – J, o, h, and n.

Python uses the sequence datatype str to store text data as a string of characters. It does not have a

special data type for a single character as many languages do. In Python, a single character is just a string

with only one character in the sequence. (Note in this text the Python str datatype will often be

referred to as a string, but the official Python name for the type is str.)

A string literal is a string of characters enclosed by quotation marks. “Hello World!” is an example.

Python string literals are indicated by enclosing them in either double quotes – "name", or single quotes

– 'name'. Python also uses triple quotes, either three single quotes or three double quotes together –

'''hello''', """goodbye""". The type of quotation marks used at the end of a sting must match the type

used at the beginning. A different type of quote can be used as a character within the string.

The term alphabetic character refers to upper and lowercase letters, usually in reference to the Latin

alphabet used for English. The term numeric character refers to decimal numeric digits 0 through 9. The

term alphanumeric character refers to the two together – alphabetic characters and numeric characters

– but it does not include special characters, such as $, !, ? or #. All characters that are not decimal

numeric digits 0 through 9 are called non-numeric characters.

Strings are used for information that is not normally used to perform arithmetic. This includes ID

numbers used as labels identifying people or things, such as Social Security numbers, student numbers,

zip codes, and product serial numbers. Even though we call them numbers, they are really used as text

data and can often include non-numeric characters. We also don’t want them to be rounded off or

truncated, as numbers sometimes are.

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 10

Numeric Data

There are three numeric data in Python 3: integers, floating-point numbers, and complex numbers. In

this course, we will only use integer and floating-point data, not complex numbers. Those who are

prepared to work with complex numbers might be interested in the following resources:

Introduction to complex numbers in Python:

http://www.geeksforgeeks.org/complex-numbers-in-python-set-1-introduction

The Python 3 cmath library of complex number functions:

https://docs.python.org/3/library/cmath.html

All of the instructors for CSCI 111 and 112 at CCP have sufficient math background to help you if you

need to work with complex numbers or decide to use them in an assignment. They are not included in

the primary course material because not all students are prepared to work with complex numbers at the

time they take CSCI 111.

In Python, as in many programming languages, an integer is a number without a fractional component,

while a floating point number is a number with a decimal fractional component.

Integers in Python can be positive or negative and are stored in a variable length format whose size is

only limited by the amount of memory available.

Floating point values are stored in a binary format but displayed by default in a decimal format. Python

uses the default storage format of the underlying system to store floating-point numbers, based on the

standards for the C programing language. So, the exact format used for storing floating-point numbers

in Python depends on the computer and operating system you are using.

Most widely used operating systems store floating point numbers using IEEE’s Standard for Binary

Floating-Point Arithmetic (IEEE 754-2008). This means floating point values are stored using a

significand-exponent format similar to scientific notation with a significand, an exponent, and two signs,

one for the significand and one for the exponent. For example, the value 437.65, which would be 4.3765

x 102 in base-ten scientific notation, which would be stored as +4.3765E+02 as a Python floating point

number. The value before the E is the number’s significand and the value after the E is its exponent.

In scientific notation, the first part of the number is called its mantissa. It has become customary in

Computer Science to refer to the mantissa as the significand in a floating point number to distinguish it

from the mantissa in a logarithm. Floating point numbers are not stored in logarithmic formats, they are

stored in a log-linear format, so the significand in a a floating point format is not exactly the same thing

as a mantissa in a logarithmic format.

An IEEE floating point number has:

• a sign indicating if the value is positive or negative.

• a significand containing the significant digits of the number. The significand is more formally

known as the mantissa of a floating point number, but is often called a significand to distinguish

it from the mantissa in a logarithm. Floating point numbers are in a log-linear format, not a

logarithmic format.

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 11

• an exponent. IEEE 754 uses an offset for the exponent which accounts for the sign, so the sign of

the exponent is not stored separately.

• The base, which is always 10, is not stored.

Floating-point numbers may be typed in Python as decimal numbers, such as 1234.56, or in their

significand-exponent format: +1.23456E+04. The significand is normalized, which means there is only

one significant digit before the decimal point. 45.654E+02 would be normalized to 4.5654E+03.

Floating-point numbers all have decimal points. A number entered with a decimal point will be a

floating-point number in Python, while a number without a decimal point will be an integer. 0.0 is a

floating-point value. 0 is an integer value.

Python allows data of different types to be used in math expressions and will convert the result of such

operations to the widest type. Quoting from the Python documentation:

Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of

different numeric types, the operand with the “narrower” type is widened to that of the other,

where integer is narrower than floating point, which is narrower than complex. Comparisons

between numbers of mixed type use the same rule.

The description above uses the term " binary arithmetic operator" This is not directly related to

computers, but from the world of mathematical functions, in which a function with two arguments is

said to be a binary function, while a function with one argument is said to be a unary function. An

operator is a symbol or token that indicates which function should be performed on the data. It is much

simpler than it sounds: in sum = x+3, the plus sign is an operator indicating the binary function

addition should be performed on x and 3. X and 3 are added together. X = -b is an example of a

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 12

unary function, it only takes one operand. In this case, the negation operation is performed on b to get

the value for x. x is set to negative b.

In the next section we will look more closely at numeric operations in Python. For more information on

data types in Python, see: https://docs.python.org/3/library/stdtypes.html .

CheckPoint 2.1

1. What is the difference between static binding and dynamic binding? Which does Python use?

2. How is the datatype of a variable determined in Python? When can it be changed?

3. Describe why the statement true = False can be valid in Python.

4. How is text data stored in Python?

5. What are the three numeric datatypes in Python? How do they compare to one another in

terms of their "width", and what happens if different data types are used in the same arithmetic

expression?

6. None of the following are valid assignment statements in Python. Describe why not for each

one of them.

a. 3x = 17

b. Name$ = "Joe Smith"

c. name1 = 'Joe Smith"

d. k+3 = 24

e. decayRate = 1 / lambda

f. y = m * x + b

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 13

Numbers from the Real (and Imaginary) World We’ve briefly looked at integer and floating point numbers in Python, but what about other kinds of

numbers, such as whole numbers, real numbers, and so on? In fact, what's the difference between a

whole number and an integer? It turns that some names or types of numbers are are well-defined

and some are subject to interpretation.

An integer is numbers without a fraction {…, -3, -2, -1, 0, 1, 2, 3, …}.

The terms whole numbers, natural numbers and counting numbers are without universally agreed

upon definitions. Some mathematicians say the terms whole number and integer mean the same

thing, while others say whole numbers start at zero. Some say natural numbers start at zero and

include only the positive integers. Others say natural numbers start at one. The same is true for

counting numbers – some say they start at zero, some say at one.

Mathematicians and computer scientists who wish to be precise use the terms positive integers and

non-negative integers to define two subsets of integers: the positive integers start at one {1,2,3,…},

while the non-negative integers start at zero {0,1,2,…} The non-negative intergers are also called

unsigned integers.

A rational number is any number that can be represented by a ratio of integers; basically a fraction

whose numerator (top) and denominator (bottom) are both integers. (The denominator cannot be

zero.) Integers are a subset of the rational numbers.

A real number is any number that can be represented on a number line. Basically, if we can draw a

line of a certain length, even if the length cannot be expressed exactly as a rational number, it is a

real number. The hypotenuse of a right triangle with two sides each 1 unit long is exactly √2 units

long. √2 is a real number, but it cannot be represented exactly by any rational number. Such

numbers are known as irrational numbers. An irrational number is any real number that cannot be

represented exactly by a ratio of integers, such as π or √2.

We cannot represent all real numbers in Python, but we can represent a decimal approximation of a

real number using floating point numbers with a high degree of accuracy. For example, the irrational

number π rounded off to 15 digits is 3.14159265358979, which we could represent in Python as the

value +3.14159265358979E+00. Even though it is not exactly π, it is accurate enough to calculate the

radius of a sphere the size of the Earth to within one-millionth of an inch.

Numbers that involve negative square roots are imaginary numbers, since negative values have no

square root. Complex numbers combine real and imaginary numbers. They are important in fields

such as electronics. Basically, if you need to use them you know what they are, and if not, then don’t

worry about it for now. As mentioned in the text, Python's cmath module has facilities for working

with complex numbers. See: https://docs.python.org/3/library/cmath.html .

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 14

Math in Python

Assignment Statements and Expressions

An assignment statement assigns a new value to an existing variable. It has two parts, separated by an

equal sign:

variable = expression

The name of a variable is only thing allowed on the left of the equal sign. An expression describing the

value to be assigned is to the right of the equal sign. It may be an actual value (a literal value), another

variable which has a value, or an expression that derives a value, to which be assigned to the variable.

Here are some examples:

angle = 45 # numeric assignment, hardcoded literal value

city = “Philadelphia” # string assignment

cooks_rate = chefs_rate # value of chefs_Rate is assigned to cooks_Rate

gross_pay = hours * rate # math expression; the calculated value is assigned to gross_pay

Expressions describe how to determine or calculate a value. Numeric expressions look like algebra

expressions, and most of the evaluation rules are the same as in elementary algebra. The computer will

try resolve the expression to end up with a single value, then assign that value to the variable.

An expression should yield a value of the same data type as the variable to which it is assigned. If not,

type casting may occur. Type casting is discussed in more detail later in this section.

Expressions have operands, which are the values used in an expression, and operators, which are

symbols or functions indicating the operations to be performed in an expression. In the assignment

statement sum = a + b, the terms sum, a, and b are the operands in the expression, while the plus sign is

the operator indicating the addition operation is to be performed.

The operations to be performed on data in an assignment statement can be specified by operators, such

as the plus sign, or by functions. Functions are methods that return a value, such as a math function to

return the square root of a number or a string function to convert a string to all uppercase characters.

x = math.sqrt(10.0) results in x being set to 3.1622776601683795.

Polymorphism

Sometimes a symbol for an operation or the name of a function in a function call can trigger one

operation for one data type and another operation for a different data type. In computer

programming, this is a form of polymorphism, which means the same name or symbol can stand for

different operations on different data types. The meaning of the plus sign + depends on the data types

of its operands. The plus sign is polymorphic because it performs different operations on different

types of data:

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 15

• The Python instruction print(12 + 16) prints the number 28. The operands 12 and 16 are

int values, so the computer will perform the operation associated with the plus sign for integers

— simple integer addition.

• The Python instruction print(“Joe” + “Smith”) prints the string “JoeSmith”. “Joe” and

“Smith” are strings, so the computer will perform the operation associated with string data —

concatenation, sticking the two strings together to form a new longer string.

The plus sign signifies addition for numeric values but concatenation for strings. It has more than one

meaning, with its meaning bound to the data types of its operands. This is an example of what is known

as ad hoc polymorphism, in which the meaning of symbol depends on the data type of its operands. Ad

hoc polymorphism is also called operator overloading and function overloading.

Polymorphism will be studied in more detail later in the semester when we begin looking at methods in

Java. For now, it is enough to have a general idea of what polymorphism is – the same symbol (or

function name) can trigger different operations for different data types.

Arithmetic Operations

Here are some of the operations that may be used with all numeric data in Python:

Operand Name Description

x + y addition sum of x and y

x – y subtraction difference between x and y

x * y multiplication product of x and y

x / y Division quotient of x and y

x // y integer division integer quotient of x and y (x/y truncated)

x % y Modulo operation

integer remainder of x / y

-x Negation negative of x

x ** y Exponentiation x to y power ( xy )

Addition, subtraction, multiplication, and division are similar to the same operations in elementary

algebra. Each of these operations takes two operands.

sum = addend1 + addend2

difference = minuend – subtrahend

product = multiplier * multiplicand

quotient = dividend / divisor

For more about Python numeric data and operations, see section 4.4 of the Python Standard Library

documentation at: https://docs.python.org/3/library/stdtypes.html The Python Language Reference

(https://docs.python.org/3/reference/index.html ) describes the technical syntax and semantics of the

Python language. the Python Standard Library documentation describes how to use the feature included

Python does not understand implied multiplication.

z = 3x + y must be written as:

z = 3*x + y

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 16

in the standard Python language download, which is more helpful for most programmers. The Python

Tutorial can also be helpful: https://docs.python.org/3/tutorial/index.html

Quotients and Remainders

A quotient from integer division will be an integer, the remainder is lost. (The integer quotient is also

called "the floored quotient". ) For example, 20 divided by 3 is 6 remainder 2. The integer quotient is 6.

The remainder of 2 is lost.

The modulus operation, also called the remainder operation, returns the remainder, not the quotient.

The remainder is called the modulo of a number (17 modulo 5 = 2). The operator is the percent sign

instead of the slash:

Remainder = dividend % divisor

This is read as “Remainder equals dividend modulo divisor” or

“Remainder equals dividend mod divisor”

Here is an example of how the modulus can be useful. Let’s assume that a church choir with 40 people

is making a trip in vans which can each carry 12 passengers. We want to know how many vans we can

fill, and how many people are left over beyond the last full van. 40 divided by 12 is 3, with a remainder

of 4. Division tells us how many full vans: 3 . Modulus tells us how many people will be left over after

the three vans are full: 2. In general, we can use two instructions like the ones below to capture both

the integer quotient and remainder:

vans = choir_size // 12 # quotient = dividend // divisor

Built-In Functions and Math Module Functions in Python Two different types of functions are commonly used in Python software – built-in functions and

functions from a Python module.

Built-In functions

Built-in functions are part of the Python language and perform a variety of operations. The print()

function is one such function built into Python 3. Built-in functions may be used in Python without the

need to download or activate them.

There are a few built-in functions that can be helpful for math in Python, such as:

Function value returned

abs(x) absolute value the absolute value (magnitude) of x

float(x) Float floating point number with the value of x

int(x) Integer an integer from a numeric or string value. It truncates the value.

round(x) Round an integer from a numeric or string value. It rounds the off value to the nearest integer.

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 17

Type Conversion and Type Casting Sometimes it is necessary to explicitly tell the computer to use a specified datatype for a certain value.

In many programming languages this is known as type conversion or type casting. Type casting is the

conversion of data from one type to another, according to rules embedded in a compiler or interpreter.

There are only three numeric data types in Python 3 – integer, floating-point, and complex. We will stick

with integer and floating-point values, which can be converted from one to the other using functions

from the Python math module. float() converts an integer to a floating point number, while int() and

round() convert a floating-point number to an integer.

Python allows arithmetic operations, such as addition, on data of different types, but if either operand is

a floating-point number, the other is converted to floating point. The datatype of the result depends on

the function. Programmers can use the functions above to force (or cast) the datatype of values in

Python.

The Python shell dialog below shows the use of some built-in math functions. For more about these and

other functions built into the Python language, see: https://docs.python.org/3/library/functions.html

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 18

Math Module Functions Additional functions for use in Python software are available in Python modules. A Python module is a

file containing Python code defining functions objects, and variables. There are many modules for

different purposes, such as the math module, the calendar module, and the email module. Some are

available from the Python Foundation, others are available form third parties, such as Google, Amazon

or Microsoft. As a Python programmer, you will be able to create and store modules of your own.

For a list of some useful Python modules, see: https://wiki.python.org/moin/UsefulModules

The features of a module are only available if the module has been downloaded and activated. A module

that has been downloaded can be activated by either including all of its source code in a Python

program, s or by using an import statement.

The Python Math Module is included with the standard Python 3 download, so you don’t need to

download – it's already available, but you need an import statement near the top of your Python code.

The Python Math Module has set of math functions, such as functions for trigonometry, exponentiation,

working with logarithms, and so on. It does not need to be downloaded because it is already included in

the standard Python download, but it must be activated before it can be used. The program on the

next page shows how to do this using the import statement at the top of the code.

Here are some of the more commonly used math functions from the standard Python math module:

Function value returned

ceil(x) ceiling function the smallest integer greater than or equal to x

cos(x) Cosine cosine of x radians

degrees(x) radians to degrees converts angle x from radians to degrees

exp(x) base e exponentiation ex

fabs(x) absolute value absolute value or magnitude of x abs(x)

factorial(x) x factorial factorial of x x!

float(x) convert to float make x a floating-point number

floor(x) floor function largest integer less than or equal to x

hypot(x, y) Hypotenuse Euclidean norm, sqrt(x*x + y*y) √𝑥 + 𝑦2

int(x) x truncated to an integer (truncated)

log(x) natural logarithm natural log of x

log(x,b) Logarithm logarithm of x in base b

log10(x) base 10 logarithm logarithm of x in base 10

log2(x) base 2 logarithm logarithm of x in base 2

pow(x, y) Exponentiation x to y power xy

radians(x) degrees to radians converts angle x from degrees to radians

sin(x) Sine sine of x radians

sqrt(x) square root square root of x √𝑥

tan(x) Tangent tangent of x radians

Notice that the trigonometric functions use radians, not degrees. The function radians(x)

converts x degrees into radians. Calculating the sine of x degrees would be:

y = math.sin( math.radians (x) )

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 19

The functions from the Python math module must be used with the name math.function() where

function is the name of function to be used, such as math.sin() and math.radians() in the example above.

In general, functions that are part of the Python language can be usec without a module name.

Functions that are a part of a separate Python module must be used with the module's name.

The sample Python script on the next page shows how to use the import statement and function name

to use the hypotenuse function. Given the length of the two short sides of a right triangle, the

hypotenuse function will calculate the length of the third side, the hypotenuse.

# hypotenuse.py

# short sample program to illustrate the hypotenuse function

# last edited by C. Herbert, Jan. 7, 2017

import math # import math module to enable math functions

a = 3.0 # first side of a right triangle

b = 4.0 # second side of a right triangle

# calculate hypotenuse

c = math.hypot(a,b)

# display output

print("The three sides of the right triangle are:")

print(a)

print(b)

print(c)

The output looks like this:

Python's math module also includes several mathematical constants, such as:

E constant e mathematical constant, Euler's number (2.71828...)

Pi constant π mathematical constant pi (3.14159...)

Here is an example of the use of the pi function:

area = math.pi * radius**2 # the area of a circle is πr2

Python also has a cmath module, with math functions for use with complex numbers. For more

information about the cmath module, see https://docs.python.org/2/library/cmath.html

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 20

Order of Operations The mathematical order of operations in a programming language is affected by three things:

• order of evaluation

• operator precedence

• grouping symbols

The order of evaluation for a language is basically the direction of the language – left to right for

Python, just as it is for English. (Hebrew and Arabic are examples of languages that are read from right

to left, while some Asian languages are read from top to bottom.)

Order of evaluation is superseded by operator precedence. Operator precedence is the precedence

given to one operator over another by a compiler or interpreter as it evaluates expressions.

Here is part of the table of operator precedence for the Python language:

Operator Precedence

Multiplicative * / // %

Additive + -

Python evaluates multiplication and division before addition and subtraction, but that multiplication and

division operations have the same precedence, and addition and subtraction have the same precedence.

Does MDAS sound familiar? It is the same order of operations for elementary math in elementary

algebra.

Here is an example:

x = 20 + 4 / 2

What does x equal? We perform operations in order from left to right, but division has precedence over

addition, so we should do the division first. The correct answer, is x = 22, not x= 12.

We can explicitly change the order of operations by using parentheses, as in this example:

X = (20 + 4) / 2

In this case, X = 12, not 22. The parentheses tell the computer to evaluate the addition before the

division.

Parenthesis are a grouping symbol in math. We can always use parentheses to explicitly tell the

computer to evaluate one operation before another.

Parentheses are also very important when translating fractions into a programming language. In

elementary algebra, the fraction bar is a grouping symbol just as parentheses are grouping symbols.

Consider the following example:

𝑥 = 3 + 9

3−1

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 21

What does x equal? 3 + 9 = 12, 3 - 1 = 2, and 12

2 is 6. The fraction bar tells us to evaluate the

terms in the numerator and denominator before dividing.

But what happens if we translate this into Python? Many people would simply enter:

X = 3 + 9 / 3 – 1

However this is not correct, because division has precedence over addition and subtraction, yielding:

3 + 9

3 - 1, which is 3 + 3 - 1, which is 5.

The correct form of 𝑥 = 3 + 9

3 − 1 translated into Python would be:

x = (3 + 9) / (3 -1)

This example shows us that parentheses should be placed around the numerator and the denominator

of a fraction with operations in them when we are translating the fractions into expressions in Python. In

general, if you are not sure what the computer will do first, you can tell the computer what you want it

to do first by using parentheses.

Note that functions with expressions in the argument of the function will resolve the argument to a

single value before invoking the function. For example, in

X = math.sqrt(4 + 20)

The computer will evaluate 4 + 20 to a single value before it uses the square root function.

Commutative and Associative Behavior Most Python arithmetic operations are commutative and associative in the same manner as their

counterparts in elementary algebra. Commutative means two operands can exchange positions and the

result of the operation is the same; in other words, the order of the operands does not affect the result.

(A+B = B+A)

Addition and multiplication are commutative, subtraction and division are not. The order of the

operands in subtraction and division (including the modulus operation) affects the results.

Even when the operation is commutative, computer programmers should still try to be consistent in the

order in which they use operands. This is related to Crewton Ramone’s corpulent midget rule. 1

Carpenters always specify length, then width, then height when listing dimensions. Even though W x L

is the same as L x W, if a carpenter gets the numbers in the wrong order on a job site, we could end up

with a door for corpulent midgets ( 3 feet high and 7 feet wide instead of 7 feet high and 3 feet wide).

The order of two values might make a difference in how a person interprets the data, even when it

doesn’t make a difference in the result of a commutative operation.

Associative means that if the same operation is used several times in a row, such as A+B+C, then it does

not matter which operation is performed first: (A+B)+C = A+(B+C). Pythion is left associative, meaning

1 Crewton Ramone is a math educator in Hawaii. See Crewton Ramone’s House of Math, online at: http://www.crewtonramoneshouseofmath.com/

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 22

without parenthesis it will perform A+B then add the result to C, but if B+C were added to A, the result

would be the same.

Addition and multiplication are associative, but subtraction and division are not.

CheckPoint 2.2

1. What is on each side of the equal sign in a Python assignment statement?

2. What three things affect the mathematical order of operations in a programming language?

3. What does the % operator indicate in a Python math expression?

4. What operations do the operators indicate should be performed in each of the following Python

math expressions:

a. quotient = x/y b. quotient = x//y

5. convert each of the following to Python assignment statements:

a. 𝑠𝑢𝑚 = 𝑎 𝑑+𝑏 𝑐

𝑏 𝑑

b. 𝑐 = √𝑎2 + 𝑏2 (without using the hypotenuse function)

c. 𝑎 = 𝜋𝑟2

d. 𝑦 = 𝑣0 𝑡 𝑠𝑖𝑛(𝑡ℎ𝑒𝑡𝑎) − 1

2 g 𝑡2

e. 𝑎𝑚𝑜𝑢𝑛𝑡 = 𝑝𝑟𝑖𝑛𝑐𝑖𝑝𝑎𝑙 (1 + 𝑟𝑎𝑡𝑒

𝑛 )

𝑛 𝑡

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 23

Data Streams and System Console I/O in Python

The system console is a computer system's primary interface with a user, consisting of the system's

primary input device and primary output device – usually just a keyboard and a screen. The term I/O

refers to input and output together, so the system console is a computer system's primary I/O device.

The console's input device is usually just the keyboard itself, with no mouse or other pointing device. It

usually operates in a text-only, command-driven mode.

The console's output device is usually just a simple display screen, often operating in a simple text-only

mode.

Most modern computer systems have a more sophisticated graphical user interface. A graphical user

interface (GUI) is a system for communication between a user and a computer that uses both a

keyboard and a pointing device, such as a mouse, and a screen that can display graphics as well as text.

From a programmer's point of view, the term system console usually only includes the text-based screen

and keyboard, even when it is part of a GUI. Some professionals, such as computer hardware engineers,

tend to think of the console as the entire GUI.

Data Streams System I/O uses data streams, also called I/O streams. A data stream is just a sequence of data flowing

from a sender to a receiver. Input data streams bring data in from external sources; output data

streams send data out to external destinations.

A raw data stream contains unformatted binary data. A tokenized data stream contains tokens and

delimiters. A token is a piece of data. A delimiter is a marker that separates one token from another in

a data stream. In most modern computers, a delimiter is a Unicode character or a string of Unicode

characters. When a person types a list, for example, commas often are used as delimiters.

I/O data streams use whitespaces as delimiters. A whitespace is:

• a blank space, such as you get by pressing the spacebar (Unicode 0008)

• a set of consecutive blank spaces

• a tab character (Unicode 0009)

• a newline (line feed) character (Unicode 000a)

• a formfeed (page feed) character (Unicode 000c)

• or any of several other technical characters related to file I/O, which we’ll see later.

Figure 5

I/O data streams

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 24

Console Output in Python We have already seen console output in Python, using the simple print() statement. Here are a few

examples:

print("Hello, world!")

print(sum)

print(hello)

print("The sum of", 10, "and", 7, "is", 17)

The print statement in Python 3 is a function, which takes an argument in parenthesis. The argument of

the print() statement will be converted to a string of text, and sent to the system console's output

stream. The console output stream is displayed on the console output, usually just a screen, as text.

The argument of the print() function can be a single item, or multiple items separated by commas. The

text that is displayed depends on what each item is:

• An Item enclosed in quotation marks will be handled as a string of text.

• If an item not enclosed in quotation marks is a number, or any expression that results in a

numeric value, the numeric value will be converted and displayed as a string of text.

• Other items not enclosed in quotation marks, except for keywords, will be interpreted as

variables. If a variable already exists, then its value will be displayed. If a variable in a print()

statement has not already been defined, the statement will generate an error message.

• If an item not enclosed in quotation marks is a Python keyword or a python function, the value

to be printed will depend on the meaning of the keyword or function. If not used properly, a

print() statement with a Python keyword or a Python function will result in an error message.

Here is the set of four print() functions from above used in a Python program, along with the output

from the program:

# testPrint.py

# short sample program to illustrate print() function arguments

# last edited by C. Herbert, Sept. 17, 2018

sum = 20+34

print("Hello, world!")

print("The sum of", 10, "and", 7, "is", 17)

print(sum)

print(hello)

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 25

The first line in the program assigns the value of 20+34 sum to the variable sum.

The first print statement prints the familiar string Hello, world!

The next print statement has multiple items, separated by commas. Some of the items are strings inside

quotes, while others are numbers. Python combines these to form and print the string The sum of 10

and 7 is 17.

The third print statement prints the value of the variable sum, which was previously set to 54 by the

expression 20+34. Python send 54 as a string to the console output to be displayed.

The fourth print statement doesn’t work. There is nothing wrong with the print statement itself, but it

attempts to print the value of the variable hello, which does not exist yet as a variable. If hello were to

be enclosed by quotation marks, the string hello would be displayed, but it is not in quotes, so the

Python interpreter generates the complex-looking error message we see. The message basically tells us

that when the program terminated, the interpreter could not understand the meaning of the name hello

in line 5 of the file it was trying to run as a Python program. Technically, this is a Python NameError,

which will occur whenever Python encounters aword or phrase it cannot interpret in Python code.

Console Input in Python Python has a simple input() function that will read input from the console input stream and capture the

result as the value of a string variable. Here is an example:

firstName = input("Please enter your name:")

In this example, the string Please enter your name: will be displayed on the console, then the system will

wait for the user to enter something. The value entered by the user will be returned by the input()

function as a string. That string will then be saved using the variable firstName. The Python input()

function always returns a string, and is most often used as shown above.

The string which the input function takes as an argument is called the prompt. An input prompt is an

important part of the run-time documentation of the program helping the user to understand how to

use the software.

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 26

The string the user enters will be displayed on the screen as text immediately following the prompt

string. There is no space between the prompt and the user's response unless the programmer

purposely puts one there. The following example has four sets of similar input statements, each a little

different as follows:

• There is no space between the prompt and the user input.

• A blank space is at the end of the prompt string (between the colon and the quotation mark).

• A tab character is at the end of the prompt string.

• A newline character is at the end of the prompt string.

testInput.py

# short sample program to illustrate print() function arguments

# last edited by C. Herbert, Sept. 17, 2018

# with no space at end of prompt string

name = input("Please enter your first name:")

print("Hello" + name)

print()

# with a space at end of prompt string

name = input("Please enter your first name: ")

print("Hello" + name)

print()

# with a tab at end of prompt string

name = input("Please enter your first name:\t")

print("Hello" + name)

print()

# with a newline at end of prompt string

name = input("Please enter your first name:\n")

print("Hello" + name)

print()

The output from this program is shown on the next page. Notice how the use of the space, the tab

character, and the newline character each affect the spacing between the prompt and the user's input.

The program is included with the files for this module in Canvas. You can try the [program to see how

this difference affects the user.

There is no one right or wring way to terminate the prompt string, but we want our software to be easy

to use, easy to understand and to look good on the screen. Using a blank, space, a tab or a newline at

the end of a prompt string can help with this.

Also notice how a blank print() function can be used to affect line spacing in output and make our

program's output easier to read.

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 27

What about the statement print("Hello" + name) ? As it is, the string hello and the string with the user's

name run together. How can this print statement be modified to improve the look of the output?

If you look back at testPrint.py program, you will see that we did not need to put a blank space before or

after numbers to be printed. Python prints strings exactly as they are, but puts blank spaces before and

after numbers when it turns those numbers into strings to be printed. It is up to us to put spacing where

we want it when several strings are printed together.

Documentation First Programming

An important aspect of engineering, including software engineering, is captured in the phrase:

“Design it before you try to build it.”

Documentation first programming is a simple design-first approach to software development in which

we begin by writing comments to describe what the software should do, then create code to do what

the comments say to do.

We start documentation first programming by developing an outline of what the software should do

from the specifications for the software, then we turn the outline into a set of comments. We then use

those comments in a Java development project as the basis for the code needed to implement the

software. If necessary, we refine the comments as we go along.

This section contains a simple example of documentation first programming. In this example, we wish to

create software for a simple road trip calculator that will tell us the average speed and gas mileage for

an automobile journey. The specifications call for a program to:

1. get the distance in miles, driving time in hours, and fuel used in gallons during a long car trip.

The data will be input by the user.

2. calculate the average speed (miles per hour), and mileage (miles per gallon) for the trip.

3. display the distance, time, average speed, and mileage for the trip.

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 28

This is an example of an I-P-O program – Input, Processing, Output – get some input, process the data,

output the results. Many short programs fit the I-P-O pattern. It is a simple example of what’s known in

software engineering as a design pattern.

To create the road trip software using a documentation first approach, we start with an outline:

1. declare variables

2. set up program to read from keyboard

3. get user input

a. distance in miles

b. driving time in hours

c. fuel used in gallons

4. calculate

a. average speed (MPH)

b. fuel mileage (MPG)

5. output results

a. distance and time

b. MPH

c. MPG

Next, we create a set of Java comments matching the outline, or copy and paste the outline into an IDE,

refining it into comments as we go along. The result should look something like this:

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 29

# Road Trip Calculator

# by C. Herbert for CSCI 111

# declare variables

# distance traveled in miles

# total driving time in hours

# total fuel used in gallons

# mileage - average miles per gallon MPG

# average speed – miles per hour MPH

# get distance in miles

# get driving time in hours

# get fuel used in gallons

# calculate Fuel mileage (MPG)

# calculate Average speed (MPH)

# print results – distance and time, MPH and MPG

Our next step is to create the Python code to do what each of the comments says to do. Our promgram

might then look something like the code on the next page. Introductory comments that were not

included in the outline have been added to the code.

This approach – starting with the documentation – saves work, makes programming easier to

understand, and reduces errors. Comments first help us to design the program, then serve to document

what we did after we are finished This approach separates the process of designing from building; it is a

simple way to design something before you try to build it. It is much better than “cowboy coding”, in

which we try to design the software as we code and then add comments later.

Many new programming students are tempted to engage in cowboy coding because the first few

programs they write are simple and the design is easy, but it is better to develop good programming

habits from the beginning. Remember, we’re not here to learn how to write short simple programs,

we’re here to learn habits that will serve us well in the long run. Documentation first programming is

one step in that direction.

The RoadTrip.py program and its output are shown on the next page.

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 30

# roadTrip.py

# program to calculate average speed and mileage for a road trip

# last edited Sept. 17, 2018 by C. Herbert for CSCI 111

#declare variables

distance = 0.0 # distance traveled in miles

time = 0.0 # total driving time in

fuel = 0.0 # total fuel used in gallons

mileage = 0.0 # mileage - average miles per gallon MPG

speed = 0.0 # average speed – miles per hour MPH

# get distance in miles from the keyboard

distance = float(input("Please enter the distance (miles): "))

# get driving time in hours

time = float(input("Please enter the total driving time (hours): "))

# get fuel used in gallons

fuel = float(input("Please enter the total fuel used (gallons): "))

# calculate fuel mileage (MPG)

mileage = distance/fuel

# calculate average speed (MPH)

speed = distance / time

# print results - distance and time, MPG and MPH

print() # blank print to separate input from output

print("You traveled ", distance, " miles in ", time, " hours.")

print("Your average speed was ", speed, " MPH.")

print("Your mileage was ", mileage , " MPG.")

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 31

Lab 2A – Console I/O: Age in Days (in class exercise)

Working with at least one other student, complete the following as a lab exercise in class.

Chapter 2 - Homework Assignment: I-P-O Software

A common simple design pattern in programming is input-processing-output (I-P-O). Software asks the

user for some input, processes the data, then delivers some output. I-P-O software ranges from simple

software that converts units of measure, such as converting mile to kilometers, to complex software,

such as system that gather numerous inputs from an airplane and its pilot and outputs data that

controls the flight of the plane.

The following four problems require an interactive I-P-O software solution that asks the user for some

input, processes the data, then outputs the result.

Your assignment is to complete any one of the four problems.

You should use variable names that would be meaningful to someone reading your code. Use can use

constants where appropriate, but otherwise all data should be input, not hardcoded into your software.

Make your output look attractive, useful to the user, and easy to understand. Keep your code readable,

easy to understand, and well-organized.

Remember to start with documentation, using a documentation-first approach to designing your

software.

Design create, test and debug a program with console I/O to ask for the

user’s name and age in years, then return the user’s name and age in

days. We will use 365.25 days per year as a constant value in the code.

This is an exercise in documentation-first programming; simple arithmetic,

assignment statements, and console I/0.

The program should:

• get the user’s name

• say hello to the user by name and ask for the user’s age in years

• calculate the user’s age in days

• print the results – the user’s age in days.

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 32

1. World City Temperature Celsius to Fahrenheit Converter

Input:

• ask for a city name

• ask for the current temperature in the city temperature in degrees Celsius, using the name

of the city

Processing:

• convert to degrees Fahrenheit using the formula:

F = ( 9

5 C) + 32

Output:

• a statement of the form:

The current temperature in London is 20 ⁰C, which is 68 ⁰F

Note: the degree symbol is Unicode \u00b0.

This problem is harder than it looks. You need to be concerned about the use of integer and

floating point numbers in arithmetic.

2. Monthly Loan Payment Calculator

Input:

• the address of the property

• the amount of the loan

• annual interest rate, (Entered as a decimal. For example, 4.5% is .045)

• number of monthly payments

Processing:

• calculate the effective monthly interest rate by dividing the annual rate by 12.0

• calculate the monthly payment using the correct formula

Output:

• the amount of the loan

• the annual interest rate

• the number of monthly payments

• the amount of each monthly payment

[Note: test data – $100,000 at 5% for 30 years is a payment of $536.82]

JLK Chapter 2 – Introduction DRAFT January 2015 Edition pg. 33

3. Change for a dollar.

Input:

• using short integers, ask the user for a number of cents less than 1 dollar

Processing:

• calculate the number of quarters, dimes, nickels and pennies in the amount.

We do this using the division and remainder operations. Think about how you would do it,

then design a program to do the same. How many quarters? How much is left over? How

many dimes in that amount, and so on?

Output:

• a neatly organized statement of the form:

87 cents is: 3 quarters

1 dime

0 nickels

2 pennies

4. Area, Volume, and Surface Area

Input:

• ask the user to input a distance in inches

Processing:

• calculate the area of:

o a circle with that radius area = πr2

o a square with that side area = s2

• calculate the volume of:

o a sphere with that radius volume = 4

3 πr3

o a cube with that side volume = s3

• calculate the surface area of

o a sphere with that radius surface area = 4 πr2

o a cube with that side surface area = 6 s2

Output:

• an attractive and neatly organized display of the results.