IT 116: Introduction to Scripting
Class 14
Today's Topics
Review
Homework 7
I have posted homework 7 here.
It is not due this coming Sunday.
Instead is due on the Sunday of the following week, October 27th.
This is to allow you time this weekend to study for the mid-term.
Mid-term
Review
Strings and String Literals
Characters
- Everything in a computer's memory is a binary number
- Binary number are written in powers of 2 and use a string of 1s and 0s
- To represent a character we need a table of numbers and the character they represent
- Nowadays we use a character table called Unicode
- Unicode represents all the characters in most world languages
Variables
- A variable is a place in memory with a name that stores a value
- A variable in Python can hold a value of any type
Creating Variables with Assignment Statements
Expressions
- An expression is anything that can be turned into a value
- There are four different kinds of expressions
- Literal
- Variables
- Calculations
- Function calls
- Expressions are used on the right hand side of an assignment statement
- And as arguments in a function call
Variable Naming Rules
- 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 or 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
- Python is case sensitive
- That means that uppercase letters and lowercase letters are completely different
Numeric Data Types and Literals
- A Python variable can hold many different types of values
- Strings
- Integers
- Floats
- Booleans
- Values of each type ares stored in the computer's memory in a different format
- The technical term for each of these different representations is a
data type
- Operators
are special characters that act upon one or more values and perform some action
- Usually the action is to creates a new value
- The values that the operators work on are called
operands
- Python has operators for basic arithmetic
Character | 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 |
Decimal and Integer Division
Exponent Operator
Remainder Operator
- When we perform long division 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
- and we can get the remainder with %
>>> 17 % 5
2
Operator Precedence
- Sometimes the order in which you use operators affects the result
- Python needs rule to decide which operators to use first
- The order in which operators are evaluated are called the rules of
operator precedence
- The operator with the highest precedence is used first
- The precedence for Python's arithmetic operators is
** |
Exponentiation |
*
/
//
%
|
Multiplication, division and remainder |
+
-
|
Addition and subtraction |
Grouping with Parentheses
Escape Characters
- The non printing characters
- Space
- Tab
- Newline (Return or Enter)
- are called whitespacecharacters
- You can add a space to a string just by hitting the space bar
- But how do you add a Tab?
- To include such characters in a string you need a special way to represent them
- You do this using two characters, where the first is a \
- Such combinations are called escape characters
- 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 |
Concatenation Operator
Boolean Expression
- A value that can only be true or false is a data type called a boolean
- Python refers to this data type as
bool
- A boolean expression is an expression whose only possible values are true and false
- There are two boolean literals
- Notice the capitalization
Relational Operators
- Boolean expressions are often created using
relational operators
- Relational operators compare two values and return true or false depending on their relationship
- Here are the relational operators
Operator | Meaning |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
== |
Equal to |
!= |
Not equal to |
- Notice that we test for equality using == not =
Precedence of Relational Operators
- All the relational operators have lower precedence than the arithmetic operators
- So + will be evaluated before >
- The order of precedence is
** |
Exponentiation |
*
/
//
%
|
Multiplication, division and remainder |
+
-
|
Addition and subtraction |
>
<
>=
<=
==
!=
|
Relational Operators |
Control Structures
- Control structures
are features of a language that allow the interpreter to take different paths through the code
if
Statements
if
-else
Statements
Indentation in the if
-else
Statement
Nested if
Statements
if
-elif
-else
Statements
Logical Operators
Precedence of Logical Operators
- The logical operators, and, or and not
have lower precedence than arthmetic operators
- They are also lower than the relational operators
** |
Exponentiation |
*
/
//
%
|
Multiplication, division and remainder |
+
-
|
Addition and subtraction |
>
<
>=
<=
==
!=
|
Relational Operators |
and
or
not
|
Logical per Operators |
Loops
- A loop repeats a number of statements
- There are two types of loops
- Loops controlled by counting
- Loops controlled by some con dition
- In loops that are controlled by counting, the loop repeat a certain number of times
- In loops controlled by a condition the code will keep looping as long as some condition is true
While Loops
Infinite Loops
- If the boolean expression in a
while
loop does not become false ..
- the loop will go on forever
- This is called an
infinite loop
- On Unix, you stop an infinite loop by hitting Control C
for
Loops
The range
Function
- The
range
function is used to create a list of integers in a for
loop
- It can take 1, two or three arguments
- With 1 argument the list goes from 0 to one lessthan the argument
>>> for number in range(5):
... print(number)
...
0
1
2
3
4
- With two arguments, the 1st gives the starting value
- And the 2nd argument is one more than the last number
>>> for number in range(1, 5):
... print(number)
...
1
2
3
4
- The 3rd argument is the step value
- It is what is added to each number to get the next
>>> for number in range(2, 11, 2):
... print(number)
...
2
4
6
8
10
Running Totals
- A total that is updated as new numbers are encountered
is called a running total
- A good example of a running total in everyday life is a bank balance
- Your bank balance is the running total of all deposits and withdrawals from your account
- In programming, running totals are calculated using a variable called an
accumulator
- This is followed by a loop in which new numbers are added to the accumulator
- Before you enter the loop, the accumulator must be set to 0
- Running totals are used when you calculate averages
$ cat average.py
# this program asks the user how many numbers
# they have to enter, then performs a running
# total and computes the average
entries = int(input("How many entries? "))
total = 0
for entry_no in range(entries):
number = int(input("number: "))
total += number
average = total / entries
print("Average", average)
$ python3 average.py
How many entries? 10
number: 10
number: 9
number: 8
number: 7
number: 6
number: 5
number: 4
number: 3
number: 2
number: 1
Average 5.5
Augmented Assignment Operators
- we often have to change the value of a variable by some amount
- If we wanted to add 5 to the variable num we could write
number = number + 5
- Statements like this happen all the time, so most computer languages have a special operator for this
- Instead of writing the statement above we could write
number += 5
- This operator works as follows
- Get the current value of the variable on the left
- Get the current value of the expression on the right
- Add the two values
- Assign this new value to the variable
- An operator like this is called an
augmented assignment operator
- Python has an augmented assignment operator for every arithmetic operator
Operator | Example | Equivalent To |
+= |
numb += 5 |
numb = num + 5 |
-= |
num -= 5 |
num = num - 5 |
*= |
x *= 5 |
x = x * 5 |
/= |
x /= 5 |
x = x / 5 |
//= |
x //= 5 |
x = x // 5 |
%= |
x %= 5 |
x = x % 5 |
**= |
x **= 5 |
x = x ** 5 |
Nested Loops
- You can nest any type of loop inside another loop
- But nested
for
loops are the most common
- Here is a nested
for
loop that creates a times table
$ cat times_table.py
# This script creates a times table using nested for loops
for row in range(1, 11):
for column in range(1, 11):
entry = row * column
print(entry, end="\t")
print()
$ python3 times_table.py
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
- With each pass through the outer loop, the loop variable row gets a new value
- It keeps that value while the inner loop variable column changes from 1 to 10
Functions
- A function
is a group of statements that has a name and performs a specific task
- Some functions are written inside the Python interpreter
- They are called
built-in functions
- But you can define your own Python functions
- You can also create files called modules
that contain a number of functions
- You can then use an
import
statement to bring these functions into any Python script
Two Types of Functions
- There are two types of functions
- Functions that return a value
- Functions that do not return a value
- The textbook calls the second type of function a
void function
- The conversion functions like
str
, int
and float
return a value
print
does not return a value
Defining a Function
Calling a Function
- To run a function you make a function call function call
- A function call has two parts
- The function name
- A list of arguments enclosed in parentheses
- You must follow the function name with parentheses even if the function takes no arguments
Local Variables
- Any time you create a variable inside a function you are creating a
local variable
- A local variable created inside a function can only be used inside that function
- The variable only exists while the function runs
- This means the variable is invisible outside the function
- Outside the function, the local variable does not exist
- Local variables defined in one function are invisible to other functions
- This means we can use the same variable name in more than one function
- Another way of saying this is that the
scope
of a local variable is the function in which it is defined
Parameters
- Parameters are a special kind of local variable
- They are defined in the function header inside the parentheses
- Parameters get their value from the corresponding argument in the function call
- Like other local variables, they disappear after the function ends