124
+ Data Types, Errors and Debugging, Advanced Math Operations & Formatting Output CSCI-UA.002

Data Types, Errors and Debugging, Advanced Math Operations

  • Upload
    others

  • View
    10

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Data Types, Errors and Debugging, Advanced Math Operations

+

Data Types, Errors and Debugging, Advanced Math Operations & Formatting OutputCSCI-UA.002

Page 2: Data Types, Errors and Debugging, Advanced Math Operations

+Agenda

n Reading – Gaddis CH 1 & 2n Reserved copies are available for use in Bobst Library at the

Reserves Desk—two floors down from the main lobby

n Assignment #1 – Due Thursday

n Drop-in Tutoring – 1/31 – Go to Common Syllabus for more info

n Lecture: Data & Error Types, Debugging and String Formattingn Data Types & Conversions

n Errors

n Advanced Math Operations

n Formatting with print()

n Formating: format() vs. f-strings

n Turtle (time remaining)

Week of 2/1 - Day 3

Page 3: Data Types, Errors and Debugging, Advanced Math Operations

+Data Types

Page 4: Data Types, Errors and Debugging, Advanced Math Operations

+Data Types

n Python needs to know how to set aside memory in your computer based on what kind of information you want to store

n There are three basic types of data that we will be working with during the first half of the termn Strings (character-based data)

n Numbers

n Logical Values (True / False)

Page 5: Data Types, Errors and Debugging, Advanced Math Operations

+Numeric Data Types

n Integersn Whole numbers that do not contain a decimal point

n Abbreviated as “int” in Python

n Example: 5, -5, 100, 10032

n Floating Point Numbersn Numbers that contain a decimal point

n Abbreviated as “float” in Python

n Example: 5.0, -5.0, 100.99, 0.232132234

Page 6: Data Types, Errors and Debugging, Advanced Math Operations

+Numeric Data Types

n You can store numeric data inside variables that you create. Example:

num_1 = 5 # this is an intnum_2 = 4.99 # this is a float

n Keep in mind that you do not use separators or symbols when storing numeric data. Example:

num_3 = $5,123.99 # error!

Page 7: Data Types, Errors and Debugging, Advanced Math Operations

+What’s the data type?

5

5.5

“Hello”

“5.5”

2.975

2.0

Page 8: Data Types, Errors and Debugging, Advanced Math Operations

+

Page 9: Data Types, Errors and Debugging, Advanced Math Operations

+

Page 10: Data Types, Errors and Debugging, Advanced Math Operations

+

Page 11: Data Types, Errors and Debugging, Advanced Math Operations

+

Page 12: Data Types, Errors and Debugging, Advanced Math Operations

+

Page 13: Data Types, Errors and Debugging, Advanced Math Operations

+

Page 14: Data Types, Errors and Debugging, Advanced Math Operations

+

Page 15: Data Types, Errors and Debugging, Advanced Math Operations

+Numeric Data Types

n Python is not a strictly typed language. This means that you don’t need to pre-declare what kind of data your variables will be holding.

n This is also called “dynamic typing”.

Page 16: Data Types, Errors and Debugging, Advanced Math Operations

+Data Types across languages

n Python

n PHP

n JavaScript

n Perl

n C

n C++

n Java

n ActionScript

Loosely Typed Strictly Typed

Page 17: Data Types, Errors and Debugging, Advanced Math Operations

+Strictly Typed Languages -Examples

var name:String = “Harry”;

var top_speed:Number = 50;

var gravity:Number = 9.5;

String name = “Harry”;

int top_speed = 50;

float gravity = 9.5;

ActionScript Java

Page 18: Data Types, Errors and Debugging, Advanced Math Operations

+User input and Math Expressions

n We can capture input from the user (via the input() function) and use that input in our calculations

n However, the input() function “returns” a string – this means that the data type that “comes out” of the input() function is a series of printed characters

n We need to convert the result of the input function from a string into one of the two numeric data types that Python supports (float and int)

Page 19: Data Types, Errors and Debugging, Advanced Math Operations

+Solution: The float() and int() functionsn float() and int() are data type conversion functions. They each take one

argument and convert that argument into the specified data type

n Example:

# ask the user for their monthly salary

monthly_salary = input(‘how much do you make in a month?’)

# convert the salary into a float

monthly_salary_float = float(monthly_salary)

# calculate the yearly salary

yearly_salary = monthly_salary_float * 12

# print the result

print(‘that means you make’, yearly_salary, ‘in a year’)

Page 20: Data Types, Errors and Debugging, Advanced Math Operations

+Nesting data type conversions

n In the previous example we performed our data type conversion in two lines

n We could have done that in a single line using a technique called “nesting”

n Example:

mynum = float( input(‘give me a number!’) )

Page 21: Data Types, Errors and Debugging, Advanced Math Operations

+Nesting data type conversions

Page 22: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge

n Ask the user for two numbers. You can assume they will be floating point numbers.

n Compute the following and print it out to the user:

n The sum of the numbers

n The product of the numbers

n The difference between the numbers

n The first number divided by the second number

Page 23: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge - Coins

n Write a program that asks the user for a number of pennies, nickels, dimes and quarters

n Calculate the total amount of money that the user has and print it out

Page 24: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge – Subway Ride Calculator

n Write a program that asks the user for the value of their current Metro card

n Compute how many rides they have left on their card. Only provide whole number results (i.e. you cannot have 3.5 rides left on a card)

Page 25: Data Types, Errors and Debugging, Advanced Math Operations

+Errors, Bugs and Debugging

Page 26: Data Types, Errors and Debugging, Advanced Math Operations

+The Software Error

“...an analyzing process must equally have been performed in order to furnish the Analytical Engine with the necessary operative data; and that herein may also lie a possible source of error. Granted that the actual mechanism is unerring in its processes, the cards may give it wrong orders.”

- Lady Augusta Ada King, Countess of Lovelace (1843)

Page 27: Data Types, Errors and Debugging, Advanced Math Operations

+Mechanical Malfunctions

“It has been just so in all of my inventions. The first step is an intuition, and comes with a burst, then difficulties arise—this thing gives out and [it is] then that 'Bugs' — as such little faults and difficulties are called—show themselves and months of intense watching, study and labor are requisite before commercial success or failure is certainly reached.”

- Thomas Edison, 1878

Page 28: Data Types, Errors and Debugging, Advanced Math Operations

+“Debugging”1947, Harvard Mark II Computer

Page 29: Data Types, Errors and Debugging, Advanced Math Operations

+“Debugging”

De-bugging a program is the process of finding and resolving errors.

Page 30: Data Types, Errors and Debugging, Advanced Math Operations

+Types of Errors

n Syntax errors: The code does not follow the rules of the language; for example, a single quote is used where a double quote is needed; a colon is missing; a keyword is used as a variable name.

n Runtime errors: In this case, your code is fine but the program does not run as expected (it “crashes”). For example, if your program is meant to divide two numbers, but does not test for a zero divisor, a run-time error would occur when the program attempts to divide by zero.

n Logic errors: These can be the hardest to find. In this case, the program is correct from a syntax perspective; and it runs; but the result is unanticipated or outright wrong. For example, if your program prints “2+2 = 5” the answer is clearly wrong J

Page 31: Data Types, Errors and Debugging, Advanced Math Operations

+Example Errors

print(“hello, world!’)

Page 32: Data Types, Errors and Debugging, Advanced Math Operations

+Example Errors

print(“hello, world!’) SyntaxError: EOL while scanning string literal

Page 33: Data Types, Errors and Debugging, Advanced Math Operations

+Example Errors

num = input('give me a number: ’)

num_float = float(num)

new_num = 10 + num_float

print (new_num)

give me a number: apple

Traceback (most recent call last):

File "<pyshell#1>", line 2, in <module>

num_float = float(num)

ValueError: could not convert string to float: 'apple'

Source Execution

Page 34: Data Types, Errors and Debugging, Advanced Math Operations

+

Page 35: Data Types, Errors and Debugging, Advanced Math Operations

+

Page 36: Data Types, Errors and Debugging, Advanced Math Operations

+

Page 37: Data Types, Errors and Debugging, Advanced Math Operations

+Example Errors

num_1 = float(input (‘give me a num: ’))

num_2 = float(input (‘give me another num: ’))

print(‘the sum is: ‘, num_1 – num_2)

give me a num: 5

give me another num: 2

the sum is: 3.0

Source Execution

Page 38: Data Types, Errors and Debugging, Advanced Math Operations

+

Page 39: Data Types, Errors and Debugging, Advanced Math Operations

+Debugging Techniques

Page 40: Data Types, Errors and Debugging, Advanced Math Operations

+Basic Debugging Techniques

n Set small, incremental goals for your program. Don’t try and write large programs all at once.

n Stop and test your work often as you go. Celebrate small successes J

n Use comments to have Python ignore certain lines that are giving you trouble

n Use the print() function to display values of variables

Page 41: Data Types, Errors and Debugging, Advanced Math Operations

+Code for IDLE Debugging

# epdb1.py -- experiment with the Python debugging in IDLE

a = 3

b = 2

c = 4

final = a + b + c

print(final)

Page 42: Data Types, Errors and Debugging, Advanced Math Operations

+Debugging in IDLE

n Go to the Shell Window

n Click Debug > Debugger – Toggles debugger ON

n Go to Script Window and Run Module

n When finished, Click Debug—in the shell window—and select Debugger

Page 43: Data Types, Errors and Debugging, Advanced Math Operations

+ Stepping with the Debugger

Page 44: Data Types, Errors and Debugging, Advanced Math Operations

+Advanced Math Operations

Page 45: Data Types, Errors and Debugging, Advanced Math Operations

+Division Operations

n Python contains two different division operators

n The “/” operator is used to calculate the floating-point result of a division operation

n The “//” operator is used to calculate the integer result of a division operation (essentially throwing away the remainder). This operation will always round down.

n Most times you will use the floating point division operator (“/”)

Page 46: Data Types, Errors and Debugging, Advanced Math Operations

+Division Operations

print(5/2)

print(5//2)

print(-5/2)

print(-5//2)

# 2.5

# 2

# -2.5

# -3

Page 47: Data Types, Errors and Debugging, Advanced Math Operations

+Order of Operations

n Python supports the standard order of operations (PEMDAS)

n You can use parenthetical notation inside your math expressions to group operations

n Ex:

((5+10+20)/60) * 100

Page 48: Data Types, Errors and Debugging, Advanced Math Operations

+

Page 49: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge

n Write a program that asks the user for three price values.

n Calculate the average price in a single variable and output it to the user

Page 50: Data Types, Errors and Debugging, Advanced Math Operations

+Calculating an average in a single step

average_score = (100 + 50 + 88) / 3

Page 51: Data Types, Errors and Debugging, Advanced Math Operations

+Exponents

n You can raise any number to a power by using the “**” operator

n Example: 24

2 ** 4

Page 52: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge: Calculating the area of a square

Page 53: Data Types, Errors and Debugging, Advanced Math Operations

+Remainder Operator (modulo)

n The modulo operator (“%”) returns the remainder portion of a division operation

n Example:

5/2 # 2.55%2 # 1

Page 54: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge: Time Calculations

Ask the user to input a number of seconds as a whole number. Then express the time value inputted as a combination of minutes and seconds.

Enter seconds: 110

That’s 1 minute and 50 seconds

Page 55: Data Types, Errors and Debugging, Advanced Math Operations

+Converting Math Formulas into Programming Statements

n Most math formulas need to be converted into a format that Python can understand before they can be evaluated

Page 56: Data Types, Errors and Debugging, Advanced Math Operations

+Converting Math Formulas into Programming Statements

10b

(3)(12)

4xy

10 * b

3 * 12

4 * x * y

y = (3 * x) / 2

y = 3 x2

Page 57: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge: Investment Planning

n In this exercise you will ask the user to input the following valuesn How much money they want to generate

n An interest rate value

n How long they’d like to invest their money

n Calculate how much they will need as an initial investment Example:n You will need ______ dollars to generate ______ dollars at ______

% over _____ years.

Page 58: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge: Investment Planning

n P = Present Value

n F = Future Value

n R = Rate or Return

n N = Number of Years

P =F

(1+ r)n

Page 59: Data Types, Errors and Debugging, Advanced Math Operations

+Mixed Type Expressions

n Python allows you to mix ints and floats when performing calculations.

n The result of a mixed-type expression will evaluate based on the operands used in the expression

Page 60: Data Types, Errors and Debugging, Advanced Math Operations

+Mixed Type Expressions

Operand 1 Operand 2 Result

int int int

float float float

float int float

Page 61: Data Types, Errors and Debugging, Advanced Math Operations

+

Page 62: Data Types, Errors and Debugging, Advanced Math Operations

+Line Continuation

n Sometimes expressions can get to be very long

n You can use the “\” symbol to indicate to Python that you’d like to continue the expression onto another line

n Example:

x = 5 + 2 / 7 \+ 8 – 12

n This also works for print() function calls as well

Page 63: Data Types, Errors and Debugging, Advanced Math Operations

+Formatting Output with the print() function

Page 64: Data Types, Errors and Debugging, Advanced Math Operations

+Line endings

n When using the print() function you probably have noticed that Python automatically places a newline character at the end of each line

n You can override this behavior and have Python use a character of your choice by using the optional ‘end’ argument when using the print() function

n Example:

print(‘one’, end=‘’)print(‘two’, end=‘’)

Page 65: Data Types, Errors and Debugging, Advanced Math Operations

+Separating print() function arguments

n By default, Python will place a space between arguments that you use in print() function calls

n You can override this behavior by using the optional ‘sep’ argument

n Example:

print(‘one’, ‘two’, sep=‘*’)

# output: one*two

Page 66: Data Types, Errors and Debugging, Advanced Math Operations

+Combing both line endings and separators

n You can use both the ‘sep’ and the ‘end’ arguments at the same time in the same print() function call.

n Example:

print(‘a’, ‘b’, ‘c’, sep=‘*’, end=‘’)

Page 67: Data Types, Errors and Debugging, Advanced Math Operations

+Escape Characters

n Most programming languages support an “escape character” that allows you to perform special actions inside the confines of a delimiter.

n In Python the escape character is the “\” character

n It causes Python to treat the next character as a “special” character – in most cases this means that you will ignore the next character and prevent it from interfering with your delimiter

n Example:

print('Hi, I\'m Harry Potter, your professor')

Page 68: Data Types, Errors and Debugging, Advanced Math Operations

+Escape Characters

n There are a number of special characters you can use in conjunction with the escape character to perform special string operations.

n Example – “\n” – forces a line break.

print(‘line 1\nline 2\nline 3\n’)

# line 1# line 2# line 3

Page 69: Data Types, Errors and Debugging, Advanced Math Operations

+Escape Characters

n Example – “\t” – forces a tab:

x = 5y = 4

print('X', '\t', 'Y', '\t', 'X*Y’)print(x, '\t', y, '\t', x*y)

X Y X*Y5 4 20

Page 70: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge

n Write a program that asks the user to enter in 3 products and 3 prices.

n Format your output to look like the following:

Product Priceproduct1 price1product2 price2product3 price3

Page 71: Data Types, Errors and Debugging, Advanced Math Operations

+String Concatenation

n You can’t “add” strings together, but you can “concatenate” them into a single compound string

n Example:

a = input(‘first name’)b = input(‘last name’)

c = b + ‘,’ + a

print(c)

Page 72: Data Types, Errors and Debugging, Advanced Math Operations

+String Repetition

n You can also “multiply” a string by an integer value to produce a larger string

n Example:

lyrics = 'Fa ' + 'La ' * 8print(lyrics)

# Fa La La La La La La La La

Page 73: Data Types, Errors and Debugging, Advanced Math Operations

+The format() function

Page 74: Data Types, Errors and Debugging, Advanced Math Operations

+Formatting Strings

n The format() function can be used to format a string before you decide to print it out to the user

n format() takes two arguments – a string and a formatting pattern (expressed as a string)

n format() returns a string which can be treated like any other string (i.e. you can print it out immediately, store its value in a variable, etc)

Page 75: Data Types, Errors and Debugging, Advanced Math Operations

+The Format function

n The first argument passed to the format function is the item that you wish to format

n The second argument passed to the function is the formatting “pattern” you wish to apply to this item

n This pattern varies based on what you would like to do to the item in question

n Once the pattern is applied to the item the format function will return a string version of your item with the formatting pattern applied

Page 76: Data Types, Errors and Debugging, Advanced Math Operations

+String Formatting

n One common use of string formatting is to generate a string that contains a known # of characters

n For example, say you have the strings “Harry” and “Computer Science”. You might want to generate output that looks like the following given these items:

Name DepartmentHarry Computer Science

n In this case we need to ensure that the strings “Name” and “Harry” are the same width so that the strings that come after them (“Department” and “Computer Science”) line up correctly.

Page 77: Data Types, Errors and Debugging, Advanced Math Operations

+String Formatting

n You can use the format() function to “pad” a string with extra spaces at the beginning or the end of the string.

n For example:

x = format(‘Harry’, ‘<20s’)

n This will generate a new string (x) that contains the string ‘Harry’ plus 15 spaces at the end of the string. The total length of the string in this case will be 20 characters.

n The ‘<‘ character in the formatting pattern tells Python to left justify the string and place the extra spaces at the end of the new string

Page 78: Data Types, Errors and Debugging, Advanced Math Operations

+String Formatting

n You can also have Python right justify the string and place the spaces at the beginning of the new string by doing the following:

b = format(‘Harry’, ‘>20s’)

Page 79: Data Types, Errors and Debugging, Advanced Math Operations

+String Formatting

x = “Hello, World!”

y = format(x, ‘>20s’)

print(x)

>> Hello, World!

print(y)

>> Hello, World!

Page 80: Data Types, Errors and Debugging, Advanced Math Operations

+Formatting Numbers

n The format() function can also be used to generate a printable string version of a float or integer number

n format() takes two arguments – a number and a formatting pattern (expressed as a string)

n format() returns a string which can be treated like any other string (i.e. you can print it out immediately, store its value in a variable, etc)

Page 81: Data Types, Errors and Debugging, Advanced Math Operations

+Limiting decimal precision

a = 1/6

print (a)

b = format (a, '.2f')

print (b)

0.16666666666666666

0.17

Page 82: Data Types, Errors and Debugging, Advanced Math Operations

+Formatting patterns

a = 10000/6

b = format(a, ‘.2f’)

c = format(a, ‘.5f’)

d = format(a, ‘,.5f’)

e = format(a, ‘>20,.2f’)

# format a as a 2 digit float

# format a as a 5 digit float

# 5 digit float + comma separators

# 2 digit float, commas + 20 character minimum field width,justified to the right

Page 83: Data Types, Errors and Debugging, Advanced Math Operations

+Formatting Percentages

a = 0.52

print(format(a, '%'))

print(format(a, '.2%'))

print(format(a, ‘.0%’))

52.000000%

52.00%

52%

Page 84: Data Types, Errors and Debugging, Advanced Math Operations

+Formatting Integers

a = 20000

print(format(a, ',d'))

print(format(a, ’>20,d'))

20,000

20,000

Page 85: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge

n Write a program that generates the 2 times table, like this:

Number 1 Number 2 N1 * N22 1 22 2 42 3 62 4 8

Page 86: Data Types, Errors and Debugging, Advanced Math Operations

+New FormattingF-strings

Page 87: Data Types, Errors and Debugging, Advanced Math Operations

+Formatted String Literal – f-string

n Works for Python 3.6 and up—keep using format() for any Python version lower

n Behavior is very similar to the format function

n Fewer arguments to write

n Expressions(s) enclosed using curly bracesn Expressions evaluated and converted to string representation

n Results interpolated into original string

n Slightly faster than format()

Page 88: Data Types, Errors and Debugging, Advanced Math Operations

+format() versus f-strings

>>> s = 'bar'>>> print(format('foo', 's'), s, format('baz', '3s'), sep='.') foo.bar.baz

>>> s = 'bar'>>> print(f'foo.{s}.baz') foo.bar.baz

format() f-string

Page 89: Data Types, Errors and Debugging, Advanced Math Operations

+Evaluating Complex Expressions

>>> quantity = 6>>> item = 'bananas'>>> price = 1.74>>> print(f'Price per item is ${price/quantity}')Price per item is $0.29

>>> name = ”Dr. Tyson”>>> profession = ”Assc Director - Senior Data Scientist">>> affiliation = ”Moody’s Analytics">>> message = f"Hi {name}. " \

f"You are a {profession}. " \f"You are at {affiliation}."

>>> messageHi Dr. Tyson. You are a Assc Director - Senior Data Scientist. You are at Moody’s Analytics.

Arithmetic Expressions & Multiline f-strings

Page 90: Data Types, Errors and Debugging, Advanced Math Operations

+Formatting Numbers

n General Pattern

f’{<expr>:<format_specifier>}’

n Example

>>> val = 12.5>>> print(f'{val:.2f}’) # outputs? >>> print(f'{val:.5f}')

Page 91: Data Types, Errors and Debugging, Advanced Math Operations

+

Page 92: Data Types, Errors and Debugging, Advanced Math Operations

+f-String Expression Limitations

n f-string expression cannot be empty >>> f'foo{}bar’ File "<stdin>", line 1 SyntaxError: f-string: empty expression not allowed

n f-string expressions cannot have backslashes in them >>> print(f'foo{\n}bar’) File "<stdin>", line 1 SyntaxError: f-string expression part cannot include a backslash

n Triple-quoted f-strings cannot have comments in them

Page 93: Data Types, Errors and Debugging, Advanced Math Operations

+

Introduction to Turtle GraphicsDrawing Graphics in Python

Page 94: Data Types, Errors and Debugging, Advanced Math Operations

+Getting to Know the turtle Library

n Pre-installed Python Library for creating pictures and shapes using a virtual canvas

n Accommodates interactive drawing

n Opening a turtle screen…

>>> import turtle>>> s = turtle.getscreen()

n Little black triangular shape is the

Page 95: Data Types, Errors and Debugging, Advanced Math Operations

+Setting up your graphics

import turtle# try a higher value like 100turtle.setup(10,10)

Python Code Cartesian Coordinate Plane

Page 96: Data Types, Errors and Debugging, Advanced Math Operations

+Setting up your graphics

import turtle# try a higher value like 100turtle.setup(10,10)

Python Code Cartesian Coordinate Plane

Page 97: Data Types, Errors and Debugging, Advanced Math Operations

+Drawing Geometric Figures

Page 98: Data Types, Errors and Debugging, Advanced Math Operations

+Drawing a Square: Code

from turtle import *

forward(100)left(90)forward(100)left(90)forward(100)left(90)forward(100)

Code Output

Page 99: Data Types, Errors and Debugging, Advanced Math Operations

+Drawing a Square: Code (Alternate)

import turtle

t = turtle.Turtle()t.fd(100)t.lt(90)t.fd(100)t.lt(90)t.fd(100)t.lt(90)t.fd(100)

Code Output

Page 100: Data Types, Errors and Debugging, Advanced Math Operations

+Drawing a Square - Steps

1. Move forward 100 steps. (In the beginning, the turtle is facing to the right.)

2. Turn 90 degrees to the right.

3. Move forward 100 steps.

4. Turn 90 degrees to the right.

5. Move forward 100 steps.

6. Turn 90 degrees to the right.

7. Move forward 100 steps. The turtle has ended up where it started.

Page 101: Data Types, Errors and Debugging, Advanced Math Operations

+Drawing a Square – Using Module Onlyimport turtle

# set up our graphical canvas# width = 500, height = 500; starting point = 0, 0turtle.setup(500,500,0,0)

# move the turtle forward by 100 pixels# note that the turtle initially faces to the rightturtle.forward(100)

# now turn to the right by 90 degreesturtle.left(90)

# now the turtle is facing down. move another 100 pixelsturtle.forward(100)

# turn to the right by 90 more degrees# this will point the turtle to the leftturtle.left(90)

# and move forward by another 100 pixelsturtle.forward(100)

# repeat the process one more time!turtle.left(90)turtle.forward(100)

Page 102: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge: Drawing Polygons

n Write a series of Python programs that draw the following shapes to the screen: n A triangle (3 sided figure)

n A pentagon (5 sided figure)

n An octagon (8 sided figure)

Page 103: Data Types, Errors and Debugging, Advanced Math Operations

+Other Turtle Functions

Page 104: Data Types, Errors and Debugging, Advanced Math Operations

+Going Home…

>>> import turtle

>>> t = turtle.Turtle()

>>> t.goto(100,100)

>>> t.home()

>>> t.clear() # clears the screen; variables do NOT change

>>> t.reset() # screen clears; all turtle’s settings restored to default

Page 105: Data Types, Errors and Debugging, Advanced Math Operations

+Drawing Preset Figures

>>> t.circle(60) # argument is size of radius>>> t.dot(20)>>> t.reset()

Page 106: Data Types, Errors and Debugging, Advanced Math Operations

+Changing Screen Color and Title

turtle.bgcolor(“blue”) # what does this do?turtle.title(“My Turtle Program”)

Page 107: Data Types, Errors and Debugging, Advanced Math Operations

+Change Pen Speed & Color

>>> t.speed(1)

>>> t.forward(100)

>>> t.speed(10)

>>> t.forward(100)

>>> t.pencolor("purple")

>>> t.fillcolor("orange")

>>> t.pensize(10)

>>> t.speed(9)

>>> t.begin_fill()

>>> t.circle(90)

>>> t.end_fill()

Pen Speed Pen Color

Page 108: Data Types, Errors and Debugging, Advanced Math Operations

+Picking the Pen Up and Down>>> t.fd(100)

>>> t.rt(90)

>>> t.penup()

>>> t.fd(100)

>>> t.rt(90)

>>> t.pendown()

>>> t.fd(100)

>>> t.rt(90)

>>> t.penup()

>>> t.fd(100)

>>> t.pendown()

Page 109: Data Types, Errors and Debugging, Advanced Math Operations

+Bringing it All Togetherimport turtlefrom turtle import *

turtle.title('Using the turtle Python module')# Define Screen sizeturtle.setup(500, 500, 0, 0)

anObject = turtle.Turtle()anObject.color('green')

# Draw a SquareanObject.penup()

anObject.goto(130, 130)anObject.setheading(0)anObject.pendown()

anObject.forward(100)

anObject.right(90)anObject.forward(100)anObject.right(90)

anObject.forward(100)anObject.right(90)

anObject.forward(100)anObject.right(90)anObject.right(90)

anObject.penup()

anObject.goto(-100, -100)

# Draw some textanObject.write('Hello Linux Format!’, font = ('Times New Roman', 26, 'bold'))turtle.done()

Example - Linux Format Magazine (August 2016)

Page 110: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenges

Page 111: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge

You’re working on a simple inventory management system for a small store. You’d like to store the name and price of two different products and print them out in the following format.

Item: Bread, Price: $2.99Item: Eggs, Price: $1.99

Page 112: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge - Mad Libs

n Write a program that asks the user to type in 4 different words using the following prompts:

enter a nounenter a verbenter an adjectiveenter an adverb

n Use the input to output a “Mad Libs” paragraph using the following text:

The [adjective] [noun] was very hungry, so it decided to [adverb] [verb] to the nearest restaurant.

Page 113: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge

n Ask the user for two numbers. You can assume they will be floating point numbers.

n Compute the following and print it out to the user:

n The sum of the numbers

n The product of the numbers

n The difference between the numbers

n The first number divided by the second number

Page 114: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge - Coins

n Write a program that asks the user for a number of pennies, nickels, dimes and quarters

n Calculate the total amount of money that the user has and print it out

Page 115: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge – Subway Ride Calculator

n Write a program that asks the user for the value of their current Metro card

n Compute how many rides they have left on their card. Only provide whole number results (i.e. you cannot have 3.5 rides left on a card)

Page 116: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge

n Write a program that asks the user for three price values.

n Calculate the average price in a single variable and output it to the user

Page 117: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge: Calculating the area of a square

Page 118: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge: Time Calculations

Ask the user to input a number of seconds as a whole number. Then express the time value inputted as a combination of minutes and seconds.

Enter seconds: 110

That’s 1 minute and 50 seconds

Page 119: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge: Units of Time

Develop a program that begins by reading a number of seconds from the user. Then your program should display the equivalent amount of time in the form D:HH:MM:SS.

The hours, minutes and secondsshould all be formatted so that they occupy exactly two digits.

Page 120: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge: Investment Planning

n In this exercise you will ask the user to input the following valuesn How much money they want to generate

n An interest rate value

n How long they’d like to invest their money

n Calculate how much they will need as an initial investment Example:n You will need ______ dollars to generate ______ dollars at ______

% over _____ years.

Page 121: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge: Investment Planning

n P = Present Value

n F = Future Value

n R = Rate or Return

n N = Number of Years

P =F

(1+ r)n

Page 122: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge

n Write a program that asks the user to enter in 3 products and 3 prices.

n Format your output to look like the following:

Product Priceproduct1 price1product2 price2product3 price3

Page 123: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge

n Write a program that generates the 2 times table, like this:

Number 1 Number 2 N1 * N22 1 22 2 42 3 62 4 8

Page 124: Data Types, Errors and Debugging, Advanced Math Operations

+Programming Challenge: Drawing Polygons

n Write a series of Python programs that draw the following shapes to the screen: n A triangle (3 sided figure)

n A pentagon (5 sided figure)