Class 5

- Comments
- Variable Naming Rules
- Choosing Good Variable Names
- Printing Multiple Values
- Numeric Data Types and Literals
- Reading Input from the Keyboard
- Reading Numbers with the
`input`

Function

- Performing Calculations
- Decimal and Integer Division
- Exponent Operator
- Remainder Operator
- Operator Precedence
- Grouping with Parentheses
- Mixed-Type Expressions and Data Type Conversion
- Breaking Long Statements into Multiple Lines
- Converting Algebra Into Python
- Turning a Formula into a Python Program

You should read Chapter 3, *Decision Structures and Boolean Logic*, from our
textbook, Starting Out with Python,
before next weeks's class.

I have posted homework 3 here.

It is due this coming Sunday at 11:59 PM.

You will lose 2 points for every day that your assignment is late.

Every Unix file has a time stamp that changes every time the file is modified

I look at this time stamp to determine whether a submission is late.

If your assignment is not working by the due date, you can continue to work on it but you will lose a few points.

If your assignment is working, do not go back and change it, because that will change the time stamp and result in a late penalty.

If you get an email from me saying an assignment is missing
**do not email me about this**.

I get far too many emails.

Instead of emailing me fix the problem.

I collect homework assignments and and check Class Exercises several times during the week.

I will check or collect your assignment later in the week.

Scripts for each Class Exercise must have the correct name and be in the correction location or my scripts will not see them.

If my scripts do not see them, your score with be zero.

If you receive no email from me about your Class Exercise script, that means your script will get full credit, less any late penalty that applies.

- Technical courses require that you master a great deal of detail
- Unless you are an exceptional student ...
- you will need to spend some time on this course ...
- several times during the week
- Working once a week is usually not enough
- The key to success in a technical course ...
- is steady, consistant, work ...
- spread out over several days
- Some important concepts do not sink in immediately
- It may take several days for something new to sink in
- Since material in this course often depends on what came before ...
- it is critical that you not fall behind
- in your work for this course
- If you fall behind, it can be
**VERY**hard to catch up

- The instructions in the homework assignments and Class Exercises are sometimes complex ...
- and involve multiple steps
- When this happens, you may need to read the assignment more than once ...
- to make sense of what I want you to do
- Take the time to read these documents slowly ...
- so you understand all the details
- If you don't you will make mistakes ...
- and lose points
- Technical work is detailed work ...
- so you must learn to read documents with a lot of detail
- If you do not understand what I want in an assignment ...
- post a question in the class discussion area
**NEVER GUESS**at the meaning of something I have written

- The script should be readable
- Anyone who knows Python should be able to read the script ...
- and learn what it does ...
- without running the script
- When you write a program you understand its different parts
- But what if someone else needs to read the program ...
- in order to understand what it does or make changes
- What if you need to read the program a year from now?
- There are many ways to make a program readable ...
- but one of the most important is to use comments
- A comment is text written inside a script ...
- that is
**not**read by the interpreter - Comments describe how the program works ...
- to people reading the code
- In Python, any text on a line after a hash mark, # ...
- is ignored by the interpreter
>>> print("Hello") # but ignore this text Hello

- If you want to write a multiline comment ...
- each line must begin with a #

- Variable names in Python must follow certain rules
- You cannot use words that have special meaning to Python as variable names
- Variable names cannot have spaces
- The first character of a variable name must be a letter, a-z and A-Z, or an underscore, _
- After the first character you can use letters, digits or the underscore
- Uppercase and lowercase letters are distinct

- Words that have special meaning to Python are called keywords
- The help feature in the Python interpreter can give you the list
help> keywords Here is a list of the Python keywords. Enter any keyword to get more help. False def if raise None del import return True elif in try and else is while as except lambda with assert finally nonlocal yield break for not class from or continue global pass

- Python is case sensitive
- That means that uppercase letters and lowercase letters are
**completely different** - This means that value and Value ...
- are the names of different variables
- Here are some examples legal variable names
rate rate_1 Rate_1 _rate

- Here are some examples of
**illegal**variable namesguns&roses # can't use symbols in variable names guns and roses # can't use spaces in variable names 1st_try # can't start a variable name with a digit

- Just because a variable name is legal ...
- doesn't mean it's a good variable name
- You should use variable names that make it clear ...
- what values the hold
- So instead of using the variable name d to hold how far you have traveled ...
- use the variable name distance
- The name of a variable should always tell you what information it contains
- Sometimes you need more than one word ...
- to describe the value contained in a variable
- When this happens, you should use the underscore character, _ ...
- to separate words ...
- like this
course_id student_name first_name

- The
`print`

function can accept more than one argument>>> room_1 = 92 >>> print("My room number is", room_1) My room number is 92

- Notice that we used both a string literal and a variable ...
- separated by a comma
- Also notice that Python automatically put a space ...
- between the string and the value of the variable
- There is no limit to the number of arguments
`print`

will accept>>> room_2 = 93 >>> print("My room number is", room_1, "and my friend is staying in", room_2) My room number is 92 and my friend is staying in 93

- A Python variable can hold many different types of values
- Strings
- Integers
- Decimals

- Each of these types of values is stored in the computer's memory ...
- in a different format
- The technical term for each of these different representations is a data type
- Any Python variable can hold any kind of value ...
- and changing the data type of a value assigned to a variable ...
- causes no problems in Python
- When a string is stored in memory, it's data type is
`str`

- When an integer is stored in memory, it has the data type
`int`

- When a decimal is stored, it has data type
`float`

- Float is short for floating point
- Whenever we write a value directly into a Python statement ...
- that value is called a literal
- Whenever you write a value in a Python statement ...
- Python can detect what kind of data type it should have
- You can see this using the Python function
`type`

>>> type("Glenn") <class 'str'> >>> type(5) <class 'int'> >>> type(5.0) <class 'float'>

- The
`type`

function also works on variables>>> score = 85 >>> type(score) <class 'int'> >>> score = 85.0 >>> type(score) <class 'float'> >>> score = "85" >>> type(score) <class 'str'>

- Python can get a value from the user ...
- by using the
`input`

function `input`

has one argument ...- the text that will prompt the user for input
`input`

is used in as assignment statement like this`VARIABLE_NAME = input(PROMPT)`

- When the Python gets to an assignment statement using
`input`

it- Prints the prompt
- Waits for the user to enter text and hit Enter
- Assigns the variable the text entered by the user

- Here is an example
>>> team = input("Please enter a team name: ") Please enter a team name: Red Sox >>> print("Go", team) Go Red Sox

- Notice that there is a space at the end of the prompt string
- You want there to be a gap between the prompt printed by the interpreter ...
- and the value entered by the user

`input`

Function- The value produced by the
`input`

function is always a string ... - regardless of the value entered by the user
>>> number = input("Please enter a number: ") Please enter a number: 55 >>> type(number) <class 'str'>

- The value that the
`input`

function returns from the user ... - is always a string
- If we want the value to be some other data type ...
- we have to use a conversion function
- To convert the variable number to an integer ...
- we can use the
`int`

function>>> number = int(number) >>> type(number) <class 'int'>

- To convert it to a decimal, we can use
`float`

>>> number = float(number) >>> type(number) <class 'float'>

- If you run a conversion function on a string ...
- that cannot be converted into a number you will get an error
>>> number = input("Please enter a number: ") Please enter a number: fifty-five >>> number = int(number) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'fifty-five'

- In the code above we used two assignment statements ...
- one to get input from the user using
`input`

... - and another to convert the value into the right data type
- We can combine both operations into a single assignment statement
>>> number = int(input("Please enter an integer: ")) Please enter an integer: 67 >>> type(number) <class 'int'>

- In Python's interactive mode, we can perform calculations
>>> 4 + 5 9

- + is an example of an operator
- Operators are special symbols that act upon one or more values ...
- and perform an action
- Usually that action produces a new value
- The values that the operators work on are called operands
- Python has operators for basic arithmetic

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 decimal 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 - All these operators can be used with variables ...
- as well as numbers
>>> a = 2 >>> b = 4 >>> a + b 6 >>> a - b -2 >>> a * b 8 >>> a / b 0.5

- Python has two division operators
- /
- //

- The first works like ordinary division
>>> 4 / 2 2.0 >>> 4 / 5 0.8

- Notice that even when the operands are integers ...
- and the result of the division is a whole number ...
- Python shows the result as a decimal number
- This is decimal or floating-point division
- // division always gives a whole number
- When the result of the division is positive ...
- any fraction is thrown away
>>> 4 // 2 2 >>> 5 // 2 2

- When the result of the division is negative ...
- the result is rounded
**up**to the next integer>>> -4 // 2 -2 >>> -5 // 2 -3

- ** is the exponent operator
- The number before this operator is raised to the power ...
- of the second operator
>>> 3 ** 2 9 >>> 3 ** 3 27 >>> 3 ** 4 81

- When we perform long division and divide one number by another ...
- we get two results
- A quotient
- A remainder

- If we divide 17 by 5 we get a quotient of 3 ...
- and a remainder of 2
- The integer division, //, gives us the quotient
>>> 17 // 5 3

- and we can get the remainder with %
>>> 17 % 5 2

- The remainder operator is sometimes called the modulus operator
- You can use the remainder operator to determine whether a number is odd or even
- If the remainder is 0, the number is even
- If the remainder is 1, the number is odd

- We can use more than one operator in a calculation
>>> 2 + 3 + 5 10

- When the operators are all the same ...
- the order in which we do the addition does not matter
- We could start at the left and work to the right ...
- or start at the right and add numbers in the other direction
- Order doesn't matter if we do addition and subtraction together
>>> 2 + 3 - 5 0

- We get the same result if we first add 2 and 3 ...
- and then subtract 5 ...
- or subtract 5 from 3 and then add 2
- But with other combinations of operators the order does matter
- What if the calculation was
2 + 3 * 5

- Which operation do we do first?
- Running this calculation in Python gives
>>> 2 + 3 * 5 17

- Humans can tolerate ambiguity, but computers cannot
- Computer languages deal with situations like this by using rules ...
- that specify which operator should act first
- These rules are called operator precedence
- The operator with the higher precedence is used first
- The precedence for Python's arithmetic operators is

** Exponentiation * / // % Multiplication, division and remainder + - Addition and subtraction

- When we write
2 + 3 * 5

- Python will multiply 3 time 5 ...
- before it adds 2
- But what if we wanted a different order?
- What if we wanted 2 to be added to 3 ...
- and then the result added multiplied by 5
- We can do this if we put the addition inside parentheses
>>> 2 + 3 * 5 17 >>> (2 + 3) * 5 25

- Whenever you are in doubt about the order of precedence ...
- you can use parentheses to make your intention clear

- If you multiply two integers, you get an integer
>>> 3 * 5 15

- If you multiply two decimals, you get a decimal
>>> 3.0 * 5.0 15.0

- But what if you multiply an integer by a decimal?
- In Python, you will get a decimal
>>> 3 * 5.0 15.0

- Here are the rules
- When an operation is performed on two
`int`

values, the result will be an`int`

- When an operation is performed on two
`float`

values, the result will be a`float`

- When an operation is performed on an
`int`

and a`float`

, the`int`

value will be temporarily converted to a`float`

and the result of the operation will be a`float`

- When an operation is performed on two
- An expression that uses operands of different data types is called a mixed-type expression
- The conversion of an
`int`

to a`float`

happens automatically - If you need to convert a value into an integer ...
- you can use the
`int()`

conversion function - If you need to convert a value into a decimal ...
- you can use the
`float()`

conversion function

- Statements are the basic unit of Python programs
- In some languages, like C and Java ...
- you have to mark the end of the statement with a special character ...
- like the semicolon, ;
- This makes it easy to write long lines of code ...
- because you can continue a statement onto a many lines as you want
- A statement that spans many lines ends ...
- when you come to ;
- But most statements are short ...
- so Python does not do this
- A statement can be as long as you like ...
- but a long statement might hit the edge of your window ...
- and wrap to the next line
- It's best to have all you statements no longer than a certain width ...
- so you can read your code without changing the width of the window
- If you want to break up a long Python statement into two or more lines ...
- you need to use the backslash, \ ...
- to continue the statement to the next line
>>> print("To be or not to be. \ ... That is the question.") To be or not to be. That is the question.

- You may have noticed that when we write the Python
expression
a + b

- it looks like something you saw in algebra
- This is often the case ...
- but there are important difference between Python and algebra
- In algebra variable names are always a single letter
- But while it is legal to have a Python variable whose name is a single letter ...
- that is
**not**good practice in Python ... - because variable names should say something about the value they hold
- There are other differences
- In algebra when we write

- We mean that the value of the variable a is multiplied ...
- by the value of the variable b ...
- which in turn is multiplied by the value of the variable c
- In Python we would write this as
a * b * c

- Similarly, the algebraic expression

- would be written like this in Python
12 * 4

- The following algebraic formula

- would look like this in Python
y = 3 * x / 3

- Similarly the formula

- in Python would be
a = (x + 12) / (13 * b)

- Notice that we had to put both the numerator
x + 12

- and the denominator
13 * b

- inside parentheses
- We have to calculate the value of each of these expressions ...
- before dividing them
- This is were the rules of precedence swing into action
- The financial formula

- would become the following in Python
P = F / (1 + r) ** n

- In the formula above, P stands for present value
- It tells you how much money you would need to invest now ...
- at a given rate of interest (r) ...
- over a certain number of years (n) ...
- to get a certain amount of money in the future (F)
- You can see this more clearly ...
- if we give the variables meaningful names
present_value = future_value / (1.0 + rate) ** years

- The program is simple
- We need three input statements
- to get the value for the three variables
- future_value
- rate
- years

- Since the
`input`

function returns a string ... - we will have to convert them into numbers
- future_value and years will be integers ...
- and rate needs to be a float
- We can then calculate the present_value ...
- and print the results
- The code looks like this
`future_value = int(input("Money in the future: ")) rate = float(input("Interest rate: ")) years = int(input("Years: ")) present_value = future_value / (1.0 + rate) ** years print("You will need to invest", present_value, "dollars at", \ rate, "interest for", years, "years")`

- Notice that I had to use \ ...
- to split the print statement into two lines ...
- so it would not be too long
- When I run this script I get
python3 future_value.py Money in the future: 1000 Interest rate: .05 Years: 10 You will need to invest 613.9132535407591 dollars at 0.05 interest for 10 years

- The program works ...
- but the answer has too many decimal places
- Fortunately, Python has a useful function called
`round`

... - which takes one or two arguments
- If you give
`round`

one argument ... - it will round to the nearest integer
>>> round(613.9132535407591) 614

- You can specify how many decimal places you want in the result ...
- if you give
`round`

a second argument>>> round(613.9132535407591, 2) 613.91

- The revised code looks like this
future_value = int(input("Money in the future: ")) rate = float(input("Interest rate: ")) years = int(input("Years: ")) present_value = round(future_value / (1.0 + rate) ** years, 2) print("You will need to invest", present_value, "dollars at", \ rate, "interest for", years, "years")

- and we get this when we run it
$ python3 future_value.py Money in the future: 100 Interest rate: .05 Years: 10 You will need to invest 61.39 dollars at 0.05 interest for 10 years

- The right hand side of the assignment statement for present_value
- is very complicated
round(future_value / (1.0 + rate) ** years, 2)

- Here
`round`

takes two arguments - The first argument, in red ...
- is the formula for calculating the value needed
- Although the formula is very complicated ...
- it is a single expression ...
- so it represents a single argument
- The second argument, in blue ...
- specifies the number of decimal points ...
- to round the result of the first argument