IT 116: Introduction to Scripting
Class 6
Tips and Examples
Review
New Material
Studying
Microphone
Quiz 1
I have posted the answers to Quiz 1
here.
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.
Resources
The Resources page has links that
you might find useful.
There is a link to it on the class web page.
Questions
Are there any questions before I begin?
Tips and Examples
Converting Decimal to Integer
Review
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 the result is always a decimal
- Even when the result is a whole number
- // 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 down
to the next lower integer
>>> -4 // 2
-2
>>> -5 // 2
-3
Exponent Operator
Remainder Operator
- When we perform long division and divide one number by another we get two
results
- 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
- 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 interpreter
must decide which to use 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
Mixed-Type Expressions and Data Type Conversion
- If you multiply two integers, you get an integer
>>> 3 * 5
15
- In calculations where the values are all integers ...
- the result will always be an integer ...
- except when division is used
>>> 6 / 2
3.0
- If you multiply two decimals, you get a decimal
>>> 3.0 * 5.0
15.0
- In calculations where all values are decimals ...
- the result will always be a decimal
- But what if you multiply an integer by a decimal?
- In Python, you will get a decimal
>>> 3 * 5.0
15.0
- This is is always true with calculations using both integers and decimala
- An expression that uses operands of different data types is called a
mixed-type expression
Breaking Long Statements into Multiple Lines
- Statements are the basic unit of Python programs
- A statement can be as long as you like
- But if a statement is longer than the width of your window ...
- you won't be able to read it all without moving things around
- This makes it hard to see what is going on ...
- and can make fixing your code hard
- It's best to have all you statements fit inside your window
- You can break a long Python statement into two or more lines ...
- by hitting backslash, \, then Enter or
Return ...
- and continuing the statement on a new line
print("You will need to invest", present_value, "dollars at", \
rate, "interest for", years, "years")
Attendance
New Material
More Expressions inside Expressions
- In the last class I talked about using a
function call ...
- as an argument to another function call
number = int(input("Please enter an integer: "))
- The argument to
int
(in red)
is itself a function call
- But using an
expression
inside another expression happens in other places too
- It happens with calculations using operators
- Look at the following expression
rate * balance
- * is an operator
- But what about rate and
balance?
- They are variables
- But variables are expressions themselves
- The general format for a calculation with operators is
EXPRESSSION OPERATOR EXPRESSION
- Whenever we use a calculation, each of the operands are themselves expressions
- This means we can write something like this
5 + round(value)
- Or this
value_1 + round(value_2)
- Or even this
round(value_1) + round(value_2)
- Expression appear everywhere in Python statements
Whitespace Characters
- Not all characters appear as marks on a page
- The Python statement
print("Hello")
prints 5 characters
- But the statement
print("Hello world")
prints 11 characters, one of them a Space
- Space is a perfectly good character
- Even though it does not put a mark on the page
- Spaces are very important
- Canyoureadthisline?
- Not easily
- Spaces mark the end of one word and the beginning of the next
- Spaces are a relatively recent invention
- They first appeared in the Middle Ages
- The Space is a member of a special group of characters
whitespace
- These characters do not put a mark on the page
- But make the printed characters easier to read
- The other two whitespace characters are Tab and
newline
- The newline character moves the printed output down one line
- You type a newline by hitting Enter (PC) or Return (Mac)
Escape Sequences
- How do you add whitespace characters to a string
string literal
?
- With Space, you just hit the space bar on the keyboard
- There is a Tab key on your keyboard
- But when you use it inside a text editor ...
- different number of spaces are added ...
- depending on where you are in the line ...
- when you hit tab
- Here is what happens in
emacs
the text editor I use
x |
xx |
xxx |
xxxx |
- Hitting Tab adds spaces ....
- to bring you to a tab stop ...
- which has a certain position on each line
- That is not the same thing as entering a Tab character ...
- which is a legitimate Unicode character
- And how are we to go down to the next line in a string literal?
- Just hitting the Enter or Return key does not work
>>> print("Line 1
File "<stdin>", line 1
print("Line 1
^
SyntaxError: EOL while scanning string literal)
- In Python and most computer language
- we need a special way to write these characters inside a string literal
- The way we write the newline character is \n
- Like this
print("Line 1\nLine 2\nLine 3")
Line 1
Line 2
Line 3
- This is an example of an
escape sequence
- An escape sequence is two characters you type
- To get one special character in your Python string literal
- Escape sequences are used to represent characters ...
- that cannot be written any other way
- Escape sequences consist of the \ (backslash)
- Followed by one of these characters
Escape Sequence |
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 |
- A Windows
pathname
uses the backslash character \
after the name of each directory
- Why do we need the escape sequence \\?
- Unix uses a slash, /, to separate
directories ...
- In a pathname like /home/ghoffman/it116
- Windows uses \ for this purpose
- So a Windows pathname would be \home\ghoffman\it116
- To print a Windows pathname 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
- So that values in a table align properly
$ cat table.py
# prints a small table
print("Max\tMin")
print("-----------")
print("5\t1")
print("12\t2")
print("100\t0")
$ python3 table.py
Max Min
-----------
5 1
12 2
100 0
- The escape sequences for single and double quotes,
\' and \" ...
- are useful when writing a string literal with many quotes
>>> print("He said \"It\'s me!\")
He said "It's me!"
Concatenation Operator
Concatenating Strings with Numbers
- When you give the
print
function a number ...
- it has to convert the number into a string in order to print it
>>> value = 5
>>> print("The value is", value)
The value is 5
- So printing a string and a number is no problem ...
- when they are separate arguments
- But you cannot concatenate a string and a number
- The values on both sides of the + must be
strings
- If they are not, 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 convert it into a string
- You do this with the
str
conversion function
print("The balance is " + str(balance))
The balance is 1000
Using print
without Going to a New Line
- The
print
function normally prints its output on one line and
moves down to the next
$ 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
- The
print
function normally adds the newline character ...
- to the string you give it as an argument
- But you can tell
print
not to add this newline character at the end
- Or you can tell it to print some other character instead of newline
- To do this you have to give
print
a special kind of argument
- Normally an argument to a function is an expression like
>>> print(5)
5
>>> a = 6
>>> print(a)
6
>>> print(a * 5)
30
- But in certain situations you can give an argument in a different way
- This different form 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
- To have
print
add a space instead of newline
- You add the following argument inside the parenetheses
end=" "
- 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
- You can also tell
print
to add nothing at the end
- You do this by setting 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
- The empty string is a perfectly good string
- It just contains no characters
- It's like 0 for strings
- 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
print
Item Separator
- If you give
print
more that one argument to print ...
- it will add a Space between each value
>>> print(1,2,3,4,5)
1 2 3 4 5
- You can change the character automatically added between each printed argument
- This is done using a technique similar to what we did 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
- I am showing you these features of
print
because they can be
useful
- But I will never ask you a question about the end
or sep arguments on an exam
F-strings
- Often we want to print a string that contains the value of
variables
- For example, a script might want to print a greeting ...
- with the name of a person and their username ...
- using the variables name and
username
>>> name = "John Smith"
>>> username = "jsmith"
- What if I wanted to print the following string
Hello, John Smith! Your username is jsmith
- I could try
>>> print("Hello ", name, "! Your username is ", username)
Hello John Smith ! Your username is jsmith
- But the ! should not have a space before
it
- I could use concatenation
>>> print("Hello, " + name + "! Your username is", username)
Hello, John Smith! Your username is jsmith
- But that is a lot of work and is ugly
- However, since Python 3.6 I have another option
- I can use F-strings, formated strings
- An F-string begins with an f ...
- followed by a quoted string ...
- with the variables inside { } ...
- like this
>>> print(f"Hello, {name}! Your username is {username}")
Hello, John Smith! Your username is jsmith
- This is much easier to type ...
- and much less ugly
- But the real power of F-strings lies in what they can do with numbers
Printing Numbers
- Printing numbers properly is often a challenge
- If we print 1 divided by 3 we get a repeating decimal
>>> print(1/3)
0.3333333333333333
- This decimal goes on forever ...
- but the Python interpreter does not have a unlimited memory
- So there is a limit to the number of digits after the decimal point ...
- a
float
value can hold
- When we print a money value, we only want two decimal places
- But Python will always give us as many decimal points as it can
>>> bill = 54.35
>>> 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 13800000000 years")
The age of the Universe is 13800000000 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 power of ten
- So we could represent the age of the Universe as 13.8 x 109 years
- And the size of an electron as 2.82 x 10-15 meter
- Languages like C, and Java use a special function,
printf
,
in these situations
- The name
printf
stands for "print formated"
- But Python takes another approach
- The { } inside F-strings can hold more than
the name of a variable
- They can hold a string called a format specifier ...
- that tells Python how to display the value of the variable
- The format is
{VARIABLE_NAME:FORMAT_SPECIFIER}
- The format specifier is a string that tells Python how the number is
to be formated
- It 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 format specifiers are used with a
float
- The type specifier for a
float
is
f
- You can also use the format specifier to determine the number of digits ...
- after the decimal point
- To do this, the format specifier uses a dot, . ...
- followed by an integer ...
- followed by f
- 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
>>> value = 12345.6789
>>> print(f"The value is {value}")
The value is 12345.6789
>>> print(f"The value is {value:.2f}")
The value is 12345.68
- To get three digits after the decimal point we would use
.3f
>>> print(f"The value is {value:.3f}")
The value is 12345.679
- Notice that the
format
function automatically rounds the
last digit ...
- so we do not have to use the
round
function
- You can use the format specifier to print a number in scientific
notation
- All you have to do is use e instead of
f in the format specifier
>>> universe_age = 13800000000
>>> print(f"The age of the universe is {universe_age:e} years")
The age of the universe is 1.380000e+10 years
>>>
>>> print(f"The size of an electron is {electron_size:e} meters")
The size of an electron is 2.820000e-14 meters
- We can specify the precision the same way we did before
>>> print(f"The age of the universe is {universe_age:.2e} years")
The age of the universe is 1.38e+10 years
>>> print(f"The size of an electron is {electron_size:.2e} meters")
The size of an electron is 2.82e-14 meters
- Normally, when we write big numbers we use commas
- They separate thousand from millions, from billions and so on
- 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 (.)
- We can use format specifiers to add commas to numbers
- To do this add a comma before the period in the format specifier
- Like this
>>> value = 12345.67890
>>> print(f"The value is {value:,.2f}")
The value is 12,345.68
- We never need the precision part when writing the format specifier
for an integer
- But we have to specify the data type with d
>>> universe_age = 13800000000
>>> print(f"The age of the Universe is {universe_age:,d} years")
The age of the Universe is 13,800,000,000 years
Specifying Minimum Length for a Number
- When you print a table of numbers ...
- you want the right-hand sides of the numbers 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")
$ 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 in front of the .
in the format specifier
$ cat print_09.py
# # prints a table of values using f-strings
print(f"{24:10d} {234523.4589:10.2f} {31:10d} {86:10d}")
print(f"{2324:10d} {79:10d} {74:10d} {22343.453:10.2f} {79:10d}"
$ python3 print_09.py
13452.12 24 234523.46 31 86
2324 79 74 22343.45 79
- By writing "10" before the .
- We are telling Python to make sure each number is 10 characters wide
- Notice that I did not use variable names inside { }
- I used number literals instead
- I also mixed decimals and integers
- I left off the column labels in the previous script because I did not want to
complicate things
- But we can use format specifiers to set the minimum width of
strings as well as numbers
- When we work with strings we use the type specifier
s
$ cat print_10.py
# prints a table of values using format specifiers
print(f"{'Mon':10s} {'Tue':10s} {'Wed':10s} {'Thr':10s} {'Fri':10s}")
print(f"{13452.12:10.2f} {24:10d} {234523.4589:10.2f} {31:10d} {86:10d}")
print(f"{2324:10d} {79:10d} {74:10d} {22343.453:10.2f} {79:10d}")
$ python3 print_10.py
Mon Tue Wed Thr Fri
13452.12 24 234523.46 31 86
2324 79 74 22343.45 79
- The output does not look good because the numbers are right aligned
- But 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 specifiers
print(f"{'Mon':>10s} {'Tue':>10s} {'Wed':>10s} {'Thr':>10s} {'Fri':>10s}")
print(f"{13452.12:10.2f} {24:10d} {234523.4589:10.2f} {31:10d} {86:10d}")
print(f"{2324:10d} {79:10d} {74:10d} {22343.453:10.2f} {79:10d}"
$ python3 print_11.py
Mon Tue Wed Thr Fri
13452.12 24 234523.46 31 86
2324 79 74 22343.45 79
Order of F-string Designators
Don't Worry about F-strings
I will not ask you to use them on a quiz or exam.
I do not expect you to memorize all the different components of a format
specifier.
These are the sorts of things you look up when you need them.
Studying
Class Exercise
Class Quiz