## IT 116: Introduction to Scripting Class 6

### Today's Topics

#### New Material

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

### Homework 3

I have posted homework 3 here.

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

Let's take a look at it.

### Review

#### Performing Calculations

• Operators are special symbols that act upon one or more values ...
• and perform an action
• Usually that action is to produce a new value
• The values that the operators work on are called operands
• Python has operators for basic arithmetic

Symbol Operation Description
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```

#### Decimal and Integer Division

• 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 results in an integer
• 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```

#### Exponent Operator

• ** 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```

#### Remainder Operator

• 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
• 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

#### Operator Precedence

• When more than one type of operator is used in a calculation ...
• The Python interpreter must know which operation to perform first
• The rules that are used to make this decision are called rules of 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

#### Grouping with Parentheses

• When we write
`2 + 3 * 5`
• Python will multiply 3 time 5 ...
• 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

#### Mixed-Type Expressions and Data Type Conversion

• 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`
• 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 and 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

#### Breaking Long Statements into Multiple Lines

• Statements are the basic unit of Python programs
• 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 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.```

### New Material

• The `print` function normally prints its output ...
• and moves down a line
```\$ cat print_04.py
# Prints three lines

print("Line 1")
print("Line 2")
print("Line 3")

\$ python3 print_04.py
Line 1
Line 2
Line 3```
• There is a special character, called newline
• which does not print anything ...
• but it moves the output down one line
• The `print` function normally adds this invisible newline character ...
• to whatever values you give it as arguments
• You can tell `print` not to add this newline character ...
• at the end of the arguments ...
• or to print some other character
• To do this you have to give `print` a special kind of argument
• Normally an argument to a function is an expression ...
• like
```5
a
a * 6```
• But in certain situation you can give an argument in a different way ...
• that looks like an assignment statement
• I will explain this in more detail in a later class
• For now here is what you need to know
• If you want to change the character or characters ...
• that `print` adds to the end of its printed arguments ...
• you write something like this
`end=" "`
• This argument tells `print` to change the character ...
• automatically added at the end of the printed arguments ...
• from a newline ...
• to a space
• If we run the following script
```\$ cat print_02.py
# Prints a single line

print("Line 1", end=" ")
print("Line 2", end=" ")
print("Line 3")```
• we get
```\$ python3 print_02.py
Line 1 Line 2 Line 3```
• If you wanted `print` to print nothing automatically ...
• you would set end to the empty string ""
• The empty string is the string with no characters
```\$ cat print_03.py
# Prints a single line

print("Line 1", end="")
print("Line 2", end="")
print("Line 3")

\$ python3 print_03.py
Line 1Line 2Line 3```
• You can use more than one character as the value of end
```\$ cat print_04.py
# Prints a single line

print("Line 1", end="---")
print("Line 2", end="---")
print("Line 3")

\$ python3 print_04.py
Line 1---Line 2---Line 3```
• If you give `print` more that one argument to print ...
• it will automatically add a space ...
• between each argument ...
• in the printed output
```>>> print(1, 2, 3, 4, 5)
1 2 3 4 5```
• You can change the string automatically added ...
• between each printed argument ...
• using a technique similar to the one above
• Here the argument name is sep
• So we can change the space between values ...
• to a comma ...
• like this
```>>> print(1, 2, 3, 4, 5, sep=",")
1,2,3,4,5```
• We can also use more than one character as a separator
```>>> print(1, 2, 3, sep=", ")
1, 2, 3```
• You can also use both sep and end ...
• in the same `print` statement
```\$ cat print_05.py
# Prints a single line

print(1, 2, sep=", ", end="---")
print(3, 4, sep=", ", end="---")
print(5)

\$ python3 print_05.py
1, 2---3, 4---5```

#### Escape Characters

• A string is just a sequence of characters ...
• and `print` will print any string we give it
• What if we wanted to to print three lines ...
• with a single call to `print`?
• Tp do this we can add newline characters to the string ...
• given to `print` as an argument
• The way we write the newline character in Python ...
• and most computer languages is
`\n`
• Like this
```print("Line 1\nLine 2\nLine 3")
Line 1
Line 2
Line 3```
• This is an example of an escape character
• An escape character is a single character ...
• which is represented by a backslash, \ ...
• followed by a letter
• Escape characters are used to represent single characters ...
• that cannot be written any other way
• The most commonly used escape characters in Python are

Escape
Character

Effect
\n Causes output to be advanced to the next line
\t Causes output to skip over to the next horizontal tab position
\' Causes a single quote mark to be printed
\" Causes a double quote mark to be printed
\\ Causes a backslash character to be printed
• To print a Windows pathname ...
• which uses the backslash character \ ...
• instead of the slash, / that Unix uses ...
• we need to use \\
```print('The path is C:\\temp\\data.')
The path is C:\temp\data.```
• We can use the Tab escape character \t ...
• to space out text on the screen
```>>> print("Monday\tTuesday\tWednesday\tThursday\tFriday")
Monday  Tuesday Wednesday   Thursday    Friday```
• You can also use it
• to align the values of different variables ...
• printed on different lines
```\$ cat print_06.py
# uses tabs to align values

print("percent\t", 10)
print("rate\t", 5)

\$ python3 print_06.py
percent  10
rate     5```
• The escape characters for single and double quotes, \' and \" ...
• let you use whatever quotes you want ...
• without having to worry about what quotes you used ...
• to enclose the entire string
```>>> print("He said \"It\'s me!\"")
He said "It's me!"```

#### Concatenation Operator

• In the last class we introduced the arithmetic operators
• These operators work on vales that are integers ...
• or decimal numbers
• Different operators work on different data types
• That's because an operation that makes sense in one data type ...
• may not make sense in another
• Dividing two numbers make sense ...
• but not dividing two strings
• The basic operation performed on strings ...
• is to take two strings and join them
• This is called concatenation
• and the concatenation operator in Python is +
```>>> team = "Red Sox"
>>> print("Let's go", team)
Let's go Red Sox
>>> cheer = "Let's go " + team
>>> print(cheer)
Let's go Red Sox```
• The arguments ofr the first `print` statement ...
• are a string literal ...
• and a variable
• The second `print` statement has one argument ...
• which is the expression formed by the concatenation ...
• of a string literal ...
• and a variable

#### Concatenating Strings with Numbers

• When you give the `print` function a number ...
• it has to convert it into a string ...
• in order to print it
```>>> value = 5
>>> print("The value is", value)
The value is 5```
• But when you use the concatenation operator + ...
• as an argument to `print` ...
• you must be careful that all the values the the operator works on ...
• are strings
• If you don't you will get an error
```print("The value is" + value)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly```
• The concatenation operator only works with strings
• so this works
```>>> balance = "1000"
>>> print("The balance is " + balance)
The balance is 1000```
• because balance is a string
• But this does not
```>>> balance = 1000
>>> print("The balance is " + balance)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly```
• In order to use a number in concatenation ...
• you have to use the `str` conversion function ...
• to turn it into a string
```print("The balance is " + str(balance))
The balance is 1000```

#### Printing Numbers

• Printing numbers properly often poses a challenge
• If we print 1 divided by 3 ...
• we get a repeating decimal
```>>> print(1/3)
0.3333333333333333```
• Of course the decimal goes on forever ...
• but the Python interpreter does not have a unlimited memory ...
• so there is a limit to the number of decimal points ...
• a `float` value can have
• When we perform a calculation involving money ...
• we want to display only two decimal points
• But Python will always give us as many decimal points ...
• as it has to offer
```>>> print(bill, "split three ways is", bill/3)
54.35 split three ways is 18.116666666666667```
• Of course we can always use the `round` function
```>>> print(bill, "split three ways is", round(bill/3, 2))
54.35 split three ways is 18.12```
• A similar problem occurs when we want to print really big ...
• or really small numbers
```>>> print("The age of the Universe is 13700000 years")
The age of the Universe is 13700000 years
>>> print("The size of an electron is .0000000000000282 meters")
The size of an electron is .0000000000000282 meters```
• This is why scientists use scientific notation
• This notation represents a value with two numbers
• The first number is a value ...
• and the second number is a multiple of ten
• So we could represent the age of the Universe as 13.7 x 109 years ...
• and the size of an electron as 2.82 x 10-15 meter
• Languages like C, and Java deal with the problem of printing numbers ...
• by providing a special print function called `printf` ...
• But Python takes another approach

#### The `format` Function

• The name `printf` stands for "print formated"
• Instead of providing a new print function
• Python provides the `format` function ...
• which creates a string ...
• and allows you to a lot of flexibility ...
• when printing numbers
• The `format` function takes two arguments
• A value
• A format specifier
• The format specifier is a string ...
• that specifies how the number is to be formated
• The format specifier can have many different parts ...
• most of which are optional
• The part that isn't optional ...
• is the part that specifies the data type ...
• of the value
• Most of the time when we use the `format` function ...
• we are using it with a `float` value ...
• and the type specifier is f
• The most common way to use the `format` function ...
• on a `float` value ...
• is to specify the number of decimal points
• To do this, the format specifier has the following format
`.NUMBER_OF_DIGITS_AFTER_DECIMAL_POINTf`
• The number of digits after the decimal point is called the precision
• The format string asking for 2 digits of precision when printing a `float` is .2f
```>>> format(12345.67890, ".2f")
'12345.68'```
• To get three digits after the decimal point we would use .3f
```>>> format(12345.67890, ".3f")
'12345.679'```
• Notice that the `format` function automatically rounds the last digit ...
• so we do not have to use the `round` function

#### Using `format` with Scientific Notation

• You can use the `format` function ...
• to display a number in scientific notation
• All you have to do is use e ...
• instead of f in the format specifier
```>>> print("The age of the universe is" , format(13700000, "e"), "years")
The age of the universe is 1.370000e+07 years
>>> print("The size of an electron is", format(.0000000000000282, "e"), "meters")
The size of an electron is 2.820000e-14 meters```
• We can specify the precision ...
• the same way we did before
```>>> print("The age of the universe is" , format(13700000, ".2e"), "years")
The age of the universe is 1.37e+07 years
>>> print("The size of an electron is", format(.0000000000000282, ".2e"), "meters")
The size of an electron is 2.82e-14 meters```

#### Using `format` to Put Commas in Big Numbers

• Normally, when we write big numbers ...
• we put a comma to separate hundreds ...
• from thousands ...
• from millions ...
• and so forth
• At least this is how we do it in English
• Many other languages ...
• such as German and French ...
• use spaces
• Spanish and Italian use periods (.)
• To get `format` to group numbers with commas ...
• we add a comma before the period ...
• in the format specifier
• like this
```format(12345.67890, ",.2f")
'12,345.68'```
• We can even leave out the precision part of the specifier
```>>> format(12345.67890, ",f")
'12,345.678900```
• We never need a precision part ...
• when writing the format specifier ...
• for an integer ...
• but we have to specify the data type with d
```print("The age of the Universe is", format(13700000000, ""), "years")
The age of the Universe is 13,700,000,000 years```

#### Specifying Minimum Length for a Number

• When you print a table of numbers from a script ...
• you want the left hand sides of the number to line up
• Sometimes you can do this with tabs
```\$ cat print_07.py
# uses tabs to print a table

print("Mon\tTue\tWed\tThr\tFri")
print("15\t24\t89\t31\t86")
print("21\t79\t74\t23\t79")
[528] glenn - ~/workspace-neon/it116/resources_it116/code_it116/examples_it116/2_chapter_examples
\$ python3 print_07.py
Mon Tue Wed Thr Fri
15  24  89  31  86
21  79  74  23  79```
• But this often does not work
```\$ cat print_08.py
# uses tabs to print a table

print("Mon\tTue\tWed\tThr\tFri")
print("13452.12\t24\t234523.4589\t31\t86")
print("2324.1\t79\t74\t22343.453\t79")

\$ python3 print_08.py
Mon Tue Wed Thr Fri
13452.12    24  234523.4589 31  86
2324.1  79  74  22343.453   79```
• What we really want is some way to specify ...
• the minimum width of a value
• We can do this by putting a number ...
• signifying the minimum width of a field ...
• in front of the . ...
• in the format specifier
```\$ cat print_09.py
# prints a table of values using format

print(format(13452.12, "10.2f") + format(24, "10.2f") + format(234523.4589, "10.2f")  \
+ format(31, "10.2f") + format(86, "10.2f"))
print(format(2324.1, "10.2f") + format(79, "10.2f") + format(74, "10.2f") \
+ format(22343.453, "10.2f") + format(79, "10.2f"))

\$ python3 print_09.py
13452.12     24.00 234523.46     31.00     86.00
2324.10     79.00     74.00  22343.45     79.00```

#### Alignment with the `format` Function

• I left off the column labels in the previous script ...
• because I did not want to complicate things
• But we can use the `format` function ...
• to set the minimum width of strings ...
• as well as numbers
• When we use `format` with strings ...
• we use the type specifier s
```\$ cat print_10.py
# prints a table of values using format

print(format("Mon", "10s") + format("Tue", "10s") + format("Wed", "10s") \
+ format("Thr", "10s") + format("Fri", "10s"))
print(format(13452.12, "10.2f") + format(24, "10.2f") + format(234523.4589, "10.2f")  \
+ format(31, "10.2f") + format(86, "10.2f"))
print(format(2324.1, "10.2f") + format(79, "10.2f") + format(74, "10.2f") \
+ format(22343.453, "10.2f") + format(79, "10.2f"))

\$ python3 print_10.py
Mon       Tue       Wed       Thr       Fri
13452.12     24.00 234523.46     31.00     86.00
2324.10     79.00     74.00  22343.45     79.00```
• The output does not look good ...
• because the numbers are right aligned ...
• while the strings are left aligned
• We can force all the strings to be right aligned ...
• if we place a > ...
• at the beginning of the format specifier
```\$ cat print_11.py
# prints a table of values using format

print(format("Mon", ">10s") + format("Tue", ">10s") + format("Wed", ">10s") \
+ format("Thr", ">10s") + format("Fri", ">10s"))
print(format(13452.12, "10.2f") + format(24, "10.2f") + format(234523.4589, "10.2f")  \
+ format(31, "10.2f") + format(86, "10.2f"))
print(format(2324.1, "10.2f") + format(79, "10.2f") + format(74, "10.2f") \
+ format(22343.453, "10.2f") + format(79, "10.2f"))

\$ python3 print_11.py
Mon       Tue       Wed       Thr       Fri
13452.12     24.00 234523.46     31.00     86.00
2324.10     79.00     74.00  22343.45     79.00```

#### Formating Percentages

• The `format` function can turn decimals ...
• into percentage
• All you have to do is change the type specifier ...
• from f ...
• to %
```>>> print("3 out of 10 is", format(3/10, ".0%"))
3 out of 10 is 30%```

### Don't Worry about the `format` Function

I will not ask you to use `format` on a quiz or exam.

I do not expect you to memorize all the different components of a format string.

These are the sorts of things you look up when you need them.