# Table of Contents

# Intro to CS 116

May 03, 2016

### Course Info

Section: 003

Instructor: Lori Case

E-mail: lori.case@uwaterloo.ca

Office: DC 3103

Office Hours: See Office Hours or by appointment.

## CS 116

Python only now (We are testing to see if CS 116 works as just Python)

**Small note:** They altered the CS 115 to accomodate for this change in CS 116. At the time of writing this in Spring 2016, I took CS 115 almost two years ago in Fall of 2014. There is some information that is familiar to people who took CS 115 last term (Winter 2016) but not to people like me due to the changes in CS 115.

###Some Python Basics:

- Written using regular mathematical notation 3+ 4 5 * (3 + 4) – 1
- Two numeric types (integers and floating point numbers) instead of one
- Strings, Booleans, lists
- No character or symbol type used in CS116.

###A very simple Python program:

x = 2 * (4 + 12) y = x +8

z = y * y

w = “hi”

u = w + w

Scheme | Python | |||
---|---|---|---|---|

Value: | Representation: | Type: | Representation: | Type: |

natural | exact | Nat | exact | Nat |

integer | exact | Int | exact | Int |

rational | exact | Num | inexact | Float |

irrational | inexact | Num | inexact | Float |

##Basic Mathematical Operations

- Addition (+), Subtraction (-), Multiplication (*):
- If combining two Int values, the result is an Int
- If combining two Float values, or a Float and an Int, the result is a Float

**Division:**

x / y

- The result is a Float for any numerical values x and y (even if both are Int)

**Integer division:**

x // y

- The result is the integer part of the division
- If x and y are both Int, the result is an Int
- If either x or y is a Float, the result is an Float, with the decimal part being .0
- Usually used with x and y as Int

**Remainder**

x % y

- x and y should both be Int
- produces the Int remainder when x divided by y

**Exponents**

x ** y

- (anyof Int Float) (anyof Int Float) -> (anyof Int Float) – produces x raised to the power of y

###Last Tips:

- Python precedence operations are standard math precedence rules (BEDMAS)
- Use ## or # for comments (from beginning or middle of line)
- Do not use dash in variable names – Use underscore instead

###Functions in Python:

fn_name (arg1, arg2, …, argN)

- must have correct number of arguments
- separate arguments by single comma

abs(-3.8) => 3.8

type(5) => <type ‘int’>

max(3,5,9) => 9

###The Math Module

To use functions from math

- Import the math module into your program
- Use math.fn or math.const to reference the function or constant you want

# Math Module, Functions, Design Recipe

May 05, 2016

```
import math
```

```
math.sqrt(25)
```

```
math.log(32,2)
```

```
math.log(32.0, 10)
```

```
math.floor(math.log(32.0, math.e))
```

```
math.factorial(10)
```

```
math.cos(math.pi)
```

### Creating new functions in Python

```
def fname (p1, p2, ..., pN):
```

```
statement1
```

```
statement2
```

- Indent each statement the same amount For function to return a value, include return answer
- where answer is the value the function produces
- If no return statement, the function produces None

## Design Recipe

### Purpose statement:

- Explicitly indicate what the function does, including how the parameters are used

### Contract

- Types of consumed and produced values
- Include any needed requirements on consumed
- Most type names are the same as in Racket, except for Num; Use Nat, Int, Float as appropriate

## Testing in Python

Download the file: check.py from the CS116 web pages.

Put a copy in the same folder as your assignment .py files for each assignment.

Add the following line to each assignment file:

import check

You do NOT need to submit check.py when you submit your assignment files.

### check.expect

## Question 1, Test 1: description check.expect( “Q1T1”, expr, value_expected)

- This function performs the test:
Does
**expr**exactly equal value_expected? - Use for checking exact values (
**integer or strings**).

### check.within

## Question 2, Test 2: description check.within(
“Q2T2”,
expr, value_expected, tolerance)
• This function performs the test:
abs(expr – value_expected) <= tolerance
• Use for checking inexact values (**floating point numbers only**).

**Example of check.expect and check.within:**

## Test 1: middle is first value

```
check.expect("Q1T1",middle(3,10,1),3)
```

Note: You should now include your examples with your tests.

## Q2, Test 2: positive radius (1.0)

```
check.within("Q2T2", area_circle(1.0), 3.14159, 0.00001)
```

## More Casting and Conversion Functions

**float: Int -> Float**

float(1) => 1.0

float(10) => 10.0

**float: Str -> Float**

float(“34.1”) => 34.1

float(“2.7.2”) => Error

float(“23”) => 23.0

**int: (anyof Float Str Int)-> Int**

int(4.7) => 4

int(3.0/4) => 0

int(-12.4) => -12

**This is a truncation operation (not rounding)**

int(“23”) => 23

int(“2.3”) => Error

**str: (anyof Int Float Str) -> Str**

str(3) => “3”

str(42.9) => “42.9”

# Mutation

May 10, 2016

## Mutation:

Python allows us to change the values of variables

The following Python program is valid:

x = “a”

x = 100

x = 2 * x - 1

## Local vs Global variables

Variables defined inside a function are called
local variables

– Local variables only can be mutated inside the
function they are defined in

Variables defined outside a function are called
global variables

– Global variables cannot be mutated inside any
functions in CS116.

###Correct Usage of Global Variables:
tax_rate = 0.13

def total_owed(amount):

return amount * (1+tax_rate)

### This Causes an Error:

grade = 87

def increase_grade(inc):

grade = grade + inc
increase_grade(5)

### Mutating Parameters

Consider the program:

def add1(n):

n = n + 1

return n

starter = 0

y = add1(starter)

The value of n is changed locally, but the value of starter is not changed.The mutation of n is a local mutation only.

Even if starter was called n, the same behaviour would be observed.

**Tip:**
Python expects each line of code to be an entire statement

Can be a problem e.g. due to indentation

If a statement is not done, use a \ (backslash) character to show it continues on next line

## Built-in type Bool:

- True, False
- Equality testing: ==
- Use for all atomic values (except for floats)
- Inequality testing:<,<=,>,>=
- != is shorthand for not equal

## Very similar to Scheme

**v1 and v2**

True only if both v1, v2 are True

**v1 or v2**

False only if both v1, v2 are False

**not v**

True if v is False , otherwise False

Like Scheme, Python uses **Short-Circuit evaluation**

Stop evaluating as soon as answer is known

**or: stop when one argument evaluates to True**

**and: stop when one argument evaluates to False**

## Example of an If Statement

if test: true_action_1 … true_action_K

**def double_positive(x):**

result = x

if x > 0:

result = 2*x

return result

# If Statements

May 12, 2016

## “Chained” Conditional Statement

if test1:

action1_block

elif test2:

action2_block

elif test3:

action3_block

else:

else_action_block

def ticket_cost(age):

if age < 3:

cost = 0.0

elif age < 18:

cost = 5.50

elif age < 65:
cost = 9.25

else:

cost = 8.00

return cost

## Factorial Function

## factorial(x) produces the product ## of all the integers from 1 to n ## factorial: Nat -> Nat

## example:

## factorial(5) => 120 ## factorial(0) => 1
def factorial (x):

if x == 0:

return 1

else:

return x * factorial( x - 1)

### Limitations

factorial(1000) -> RuntimeError: maximum recursion depth exceeded

- There is a limit to how much recursion Python “can remember”

## Important

**If a function does not include a return
statement, then the produced value (and type) is None**

- The purpose statement does not need to include “Produces None” as this will be included in the contract.

# If Statements

May 19, 2016