Writing Python Programs, Numerical Data Types

Similar documents
Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science

Introduction to Computer Programming for Non-Majors

Python Programming: An Introduction to Computer Science

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

CITS 1401 Problem Solving & Programming

Python Programming: An Introduction to Computer Science

Introduction to Computer Programming for Non-Majors

CITS 4406 Problem Solving & Programming

Lecture Writing Programs. Richard E Sarkis CSC 161: The Art of Programming

Lecture Numbers. Richard E Sarkis CSC 161: The Art of Programming

Introduction to Computer Programming for Non-Majors

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

Comp 151. More on Arithmetic and intro to Objects

Last Time. integer/float/string. import math math.sqrt() math.pi. Python Programming, 2/e 2

Comp 151. More on Arithmetic and number types

Introduction to Computer Programming for Non-Majors

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science

Introduction to Computer Programming for Non-Majors

File processing and decision structures

Worlframalpha.com Facebook Report

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Chapter 2 Writing Simple Programs

Introduction to Engineering gii

Loop structures and booleans

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Methods CSC 121 Fall 2014 Howard Rosenthal

Introduction to Programming

Chapter 2. Outline. Simple C++ Programs

Computing with Numbers

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions.

Introduction to Computer Programming for Non-Majors

SI Networked Computing: Storage, Communication, and Processing, Winter 2009

Outline: Search and Recursion (Ch13)

Full file at

" # # if $ " %&% # ifelse $ " #&% # ifelif-else $ +bool ##%# # #.* $ ## # .# *#%$ % ## % .#*#%*

String and list processing

Arithmetic. 2.2.l Basic Arithmetic Operations. 2.2 Arithmetic 37

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

Methods CSC 121 Spring 2017 Howard Rosenthal

Methods CSC 121 Fall 2016 Howard Rosenthal

Introduction to Python, Cplex and Gurobi

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

C++ Programming Lecture 11 Functions Part I

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

4. Modules and Functions

CS 115 Lecture 4. More Python; testing software. Neil Moore

Python Numbers. Learning Outcomes 9/19/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17

Programming with Python

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

Goals for This Lecture:

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

Data Types and Basic Calculation

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Computer Programming in MATLAB

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

Engineering Problem Solving with C++, Etter/Ingber

CHAPTER 3: CORE PROGRAMMING ELEMENTS

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Computer Science & Engineering 150A Problem Solving Using Computers

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

Python. Objects. Geog 271 Geographic Data Analysis Fall 2010

CSCE 120: Learning To Code

CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi

C++ Programming: From Problem Analysis to Program Design, Third Edition

Introduction to Matlab

ANSI C Programming Simple Programs

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

PIC 10A. Lecture 3: More About Variables, Arithmetic, Casting, Assignment

Fundamentals of Programming (Python) Getting Started with Programming

9 Using Equation Networks

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An

Chapter 2. Elementary Programming

CT 229 Java Syntax Continued

Program Structure and Format

CEN 414 Java Programming

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment

Getting Started with Python

3.1. Chapter 3: The cin Object. Expressions and Interactivity

ENGR 101 Engineering Design Workshop

Variables, expressions and statements

Math 340 Fall 2014, Victor Matveev. Binary system, round-off errors, loss of significance, and double precision accuracy.

Algorithms and Programming I. Lecture#12 Spring 2015

CSI33 Data Structures

Chapter 3 Mathematical Functions, Strings, and Objects

>>> * *(25**0.16) *10*(25**0.16)

MAT 003 Brian Killough s Instructor Notes Saint Leo University

Lecture 14. Daily Puzzle. Math in C. Rearrange the letters of eleven plus two to make this mathematical statement true. Eleven plus two =?

Table of Laplace Transforms

Custom Variables (Virtual Variables)

Math Day 2 Programming: How to make computers do math for you

ENCM 339 Fall 2017 Lecture Section 01 Lab 9 for the Week of November 20

cs1114 REVIEW of details test closed laptop period

Transcription:

Writing Python Programs, Numerical Data Types Michael Mandel Lecture 2 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture02final.ipyn b

Outline Writing python programs Software Development Process Example: Temperature Converter Elements of Programs Assignment Statements Definite Loops Example Program: Future Value Computing with nunmbers Numeric Data Types Type Conversions Using the Math Library Example: Factorial

Writing python programs Textbook chapter 2 https://github.com/ling78100/lectureexamples/blob/master/chapter02.ipynb

Objectives Concepts To know the steps in an orderly software development process. To understand programs following the input, process, output (IPO) pattern and be able to modify them in simple ways. To understand the rules for forming valid Python identifiers and expressions. Specifics: To be able to understand and write: Python statements to output information to the screen assign values to variables get numeric information entered from the keyboard perform a counted loop

The software development process Writing python programs

The Software Development Process The process of creating a program is often broken down into stages according to the information that is produced in each phase. Analyze the problem Determine specification Create a design Implement the design Test/debug the program Maintain the program

The Software Development Process Analyze the Problem Figure out exactly the problem to be solved. Try to understand it as much as possible.

The Software Development Process Determine Specifications Describe exactly what your program will do. Don t worry about how the program will work, but what it will do. Includes describing the inputs, outputs, and how they relate to one another.

The Software Development Process Create a Design Formulate the overall structure of the program. This is where the how of the program gets worked out. Develop your own algorithm that meets the specifications.

The Software Development Process Implement the Design Translate the design into a computer language. In this course we will use Python.

The Software Development Process Test/Debug the Program Try out your program to see if it worked. If there are any errors (bugs), they need to be located and fixed. This process is called debugging. Your goal is to find errors, so try everything that might break your program!

The Software Development Process Maintain the Program Continue developing the program in response to the needs of your users. In the real world, most programs are never completely finished they evolve over time.

Example program: Temperature converter Writing python programs

Example Program: Temperature Converter Analysis the temperature is given in Celsius, user wants it expressed in degrees Fahrenheit. Specification Input temperature in Celsius Output temperature in Fahrenheit Output = 9/5(input) + 32

Example Program: Temperature Converter Design Input, Process, Output (IPO) Prompt the user for input (Celsius temperature) Process it to convert it to Fahrenheit using F = 9/5(C) + 32 Output the result by displaying it on the screen

Example Program: Temperature Converter Before we start coding, let s write a rough draft of the program in pseudocode Pseudocode is precise English that describes what a program does, step by step. Using pseudocode, we can concentrate on the algorithm rather than the programming language.

Example Program: Temperature Converter Pseudocode: Input the temperature in degrees Celsius (call it celsius) Calculate fahrenheit as (9/5)*celsius+32 Output fahrenheit Now we need to convert this to Python!

Example Program: Temperature Converter # A program to convert Celsius temps to Fahrenheit # by: Susan Computewell def convert(): celsius = eval(input("what is the Celsius temperature? ")) fahrenheit = (9/5) * celsius + 32 print("the temperature is ",fahrenheit," degrees Fahrenheit.") convert()

Example Program: Temperature Converter Once we write a program, we should test it! >>> What is the Celsius temperature? 0 The temperature is 32.0 degrees Fahrenheit. >>> convert() What is the Celsius temperature? 100 The temperature is 212.0 degrees Fahrenheit. >>> convert() What is the Celsius temperature? -40 The temperature is -40.0 degrees Fahrenheit. >>>

Elements of programs Writing python programs

Elements of Programs Names Names are given to variables (celsius, fahrenheit), modules (main, convert), etc. These names are called identifiers Every identifier must begin with a letter or underscore ( _ ), followed by any sequence of letters, digits, or underscores. Identifiers are case sensitive.

Elements of Programs These are all different, valid names X Celsius Spam spam spam Spam_and_Eggs Spam_And_Eggs

Elements of Programs Some identifiers are part of Python itself. These identifiers are known as reserved words (or keywords). This means they are not available for you to use as a name for a variable, etc. in your program. and, del, for, is, raise, assert, elif, in, print, etc. For a complete list, see Table 2.1 (p. 32)

Elements of Programs Expressions The fragments of code that produce or calculate new data values are called expressions. Literals are used to represent a specific value, e.g. 3.9, 1, 1.0 Simple identifiers can also be expressions. Also included are strings (textual data) and string literals (like "Hello").

Elements of Programs >>> x = 5 >>> x 5 >>> print(x) 5 >>> print(spam) NameError is the error when you try to use a variable without a value assigned to it. Traceback (most recent call last): File "<pyshell#15>", line 1, in -toplevelprint spam NameError: name 'spam' is not defined >>>

Elements of Programs Simpler expressions can be combined using operators. +, -, *, /, ** Spaces are irrelevant within an expression. The normal mathematical precedence applies. ((x1 x2) / 2*n) + (spam / k**3)

Elements of Programs Output Statements print() print(<expr>, <expr>,, <expr>) A print statement can print any number of expressions. Successive print statements will display on separate lines. A bare print() will print a blank line.

Elements of Programs print(3+4) print(3, 4, 3+4) print() print(3, 4, end=" "), print(3 + 4) print("the answer is", 3+4) 7 3 4 7 3 4 7 The answer is 7

Assignment statements Writing python programs

Assignment Statements Simple Assignment <variable> = <expr> variable is an identifier, expr is an expression The expression on the RHS is evaluated to produce a value which is then associated with the variable named on the LHS.

Assignment Statements x = 3.9 * x * (1-x) fahrenheit = 9/5 * celsius + 32 x = 5

Assignment Statements Variables can be reassigned as many times as you want! >>> myvar = 0 >>> myvar 0 >>> myvar = 7 >>> myvar 7 >>> myvar = myvar + 1 >>> myvar 8 >>>

Assignment Statements Variables are like a box we can put values in. When a variable changes, the old value is erased and a new one is written in.

Assignment Statements Technically, this model of assignment is simplistic for Python. Python doesn't overwrite these memory locations (boxes). Assigning a variable is more like putting a sticky note on a value and saying, this is x.

Assigning Input The purpose of an input statement is to get input from the user and store it into a variable. <variable> = eval(input(<prompt>)) Here, eval is wrapped around the input function.

Assigning Input First the prompt is printed The input part waits for the user to enter a value and press <enter> The expression that was entered is evaluated to turn it from a string of characters into a Python value (a number). The value is assigned to the variable. For string input: <var> = input(<prompt>)

Assigning Input Beware: the eval function is very powerful and potentially dangerous! When we evaluate user input, we allow the user to enter a portion of our program, which Python will then evaluate.

Assigning Input Someone who knows Python could exploit this ability and enter malicious instructions, e.g. capture private information or delete files on the computer. This is called a code injection attack, because an attacker is injecting malicious code into the running program.

Assigning Input When writing programs for your own personal use, this is probably not much of an issue. When the input is coming from untrusted sources, like users on the Internet, the use of eval could be disastrous. We will see some safer alternatives in the next chapter.

Simultaneous Assignment Several values can be calculated at the same time <var>, <var>, = <expr>, <expr>, Evaluate the expressions in the RHS and assign them to the variables on the LHS

Simultaneous Assignment sum, diff = x+y, x-y How could you use this to swap the values for x and y? Why doesn t this work? x = y y = x We could use a temporary variable

Simultaneous Assignment We can swap the values of two variables quite easily in Python! x, y = y, x >>> x = 3 >>> y = 4 >>> print x, y 3 4 >>> x, y = y, x >>> print x, y 4 3

Simultaneous Assignment We can use this same idea to input multiple variables from a single input statement! Use commas to separate the inputs def spamneggs(): spam, eggs = eval(input("enter # of slices of spam followed by # of eggs: ")) print ("You ordered", eggs, "eggs and", spam, "slices of spam. Yum! ) >>> spamneggs() Enter the number of slices of spam followed by the number of eggs: 3, 2 You ordered 2 eggs and 3 slices of spam. Yum! >>>

Definite loops Writing python programs

Definite Loops A definite loop executes a definite number of times, i.e., at the time Python starts the loop it knows exactly how many iterations to do. for <var> in <sequence>: <body> The beginning and end of the body are indicated by indentation.

Definite Loops for <var> in <sequence>: <body> The variable after the for is called the loop index. It takes on each successive value in sequence. Often, the sequence portion consists of a list of values. A list is a sequence of expressions in square brackets.

Definite Loops >>> for i in [0,1,2,3]: print (i) >>> for odd in [1, 3, 5, 7]: print(odd*odd) 0 1 2 3 1 9 25 49 >>>

Definite Loops In chaos.py, what did range(10) do? >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range is a built-in Python function that generates a sequence of numbers, starting with 0. list is a built-in Python function that turns the sequence into an explicit list The body of the loop executes 10 times.

Definite Loops for loops alter the flow of program execution, so they are referred to as control structures.

Example program: Future value Writing python programs

Example Program: Future Value Analysis Money deposited in a bank account earns interest. How much will the account be worth 10 years from now? Inputs: principal, interest rate Output: value of the investment in 10 years

Example Program: Future Value Specification User enters the initial amount to invest, the principal User enters an annual percentage rate, the interest The specifications can be represented like this

Example Program: Future Value Program Future Value Inputs principal The amount of money being invested, in dollars apr The annual percentage rate expressed as a decimal number. Output The value of the investment 10 years in the future Relatonship Value after one year is given by principal * (1 + apr). This needs to be done 10 times.

Example Program: Future Value Design (pseudocode) Print an introduction Input the amount of the principal (principal) Input the annual percentage rate (apr) Repeat 10 times: principal = principal * (1 + apr) Output the value of principal

Example Program: Future Value Implementation Each line translates to one line of Python (in this case) Print an introduction print ("This program calculates the future") print ("value of a 10-year investment.") Input the amount of the principal principal = eval(input("enter the initial principal: "))

Example Program: Future Value Input the annual percentage rate apr = eval(input("enter the annual interest rate: ")) Repeat 10 times: for i in range(10): Calculate principal = principal * (1 + apr) principal = principal * (1 + apr) Output the value of the principal at the end of 10 years print ("The value in 10 years is:", principal)

Example Program: Future Value # A program to compute the value of an investment # carried 10 years into the future def futval(): print("this program calculates the future value of a 10-year investment.") principal = eval(input("enter the initial principal: ")) apr = eval(input("enter the annual interest rate: ")) for i in range(10): principal = principal * (1 + apr) print ("The value in 10 years is:", principal) futval()

Example Program: Future Value >>> futval() This program calculates the future value of a 10-year investment. Enter the initial principal: 100 Enter the annual interest rate:.03 The value in 10 years is: 134.391637934 >>> futval() This program calculates the future value of a 10-year investment. Enter the initial principal: 100 Enter the annual interest rate:.10 The value in 10 years is: 259.37424601

Computing with numbers Textbook chapter 3 https://github.com/ling78100/lectureexamples/blob/master/chapter03.ipynb

Objectives Concepts To understand the concept of data types. To be familiar with the basic numeric data types in Python. To understand the fundamental principles of how numbers are represented on a computer. Specifics To be able to use the Python math library. To understand the accumulator program pattern. To be able to read and write programs that process numerical data.

Numeric data types Computing with numbers

Numeric Data Types The information that is stored and manipulated by computer programs is referred to as data. There are two different kinds of numbers! (5, 4, 3, 6) are whole numbers they don t have a fractional part (.25,.10,.05,.01) are decimal fractions Inside the computer, whole numbers and decimal fractions are represented quite differently! We say that decimal fractions and whole numbers are two different data types.

Numeric Data Types The data type of an object determines what values it can have and what operations can be performed on it. Whole numbers are represented using the integer (int for short) data type. These values can be positive or negative whole numbers. Numbers that can have fractional parts are represented as floating point (or float) values.

Numeric Data Types How can we tell which is which? A numeric literal without a decimal point produces an int value A literal that has a decimal point is represented by a float (even if the fractional part is 0) Python has a special function to tell us the data type of any value: type() >>> type(3) <class 'int'> >>> type(3.1) <class 'float'> >>> type(3.0) <class 'float'> >>> myint = 32 >>> type(myint) <class 'int'>

Numeric Data Types Why do we need two number types? Values that represent counts can t be fractional (you can t have 3 ½ quarters) Most mathematical algorithms are very efficient with integers The float type stores only an approximation to the real number being represented! Since floats aren t exact, use an int whenever possible!

Numeric Data Types Operations on ints produce ints, operations on floats produce floats (except for /). >>> 3.0+4.0 7.0 >>> 3+4 7 >>> 3.0*4.0 12.0 >>> 3*4 12 >>> 10.0/3.0 3.3333333333333335 >>> 10/3 3.3333333333333335 >>> 10 // 3 3 >>> 10.0 // 3.0 3.0

Numeric Data Types Integer division produces a whole number. That s why 10//3 = 3! Think of it as gozinta, where 10//3 = 3 since 3 gozinta (goes into) 10 3 times (with a remainder of 1) 10%3 = 1 is the remainder of the integer division of 10 by 3. a = (a//b)(b) + (a%b)

Type conversion & rounding Computing with numbers

Type Conversions & Rounding We know that combining an int with an int produces an int, and combining a float with a float produces a float. What happens when you mix an int and float in an expression? x = 5.0 * 2 What do you think should happen?

Type Conversions & Rounding For Python to evaluate this expression, it must either convert 5.0 to 5 and do an integer multiplication, or convert 2 to 2.0 and do a floating point multiplication. Converting a float to an int will lose information Ints can be converted to floats by adding.0

Type Conversion & Rounding In mixed-typed expressions Python will convert ints to floats. Sometimes we want to control the type conversion. This is called explicit typing. Converting to an int simply discards the fractional part of a float the value is truncated, not rounded.

Type Conversion & Rounding To round off numbers, use the built-in round function which rounds to the nearest whole value. If you want to round a float into another float value, you can supply a second parameter that specifies the number of digits after the decimal point.

Type Conversions & Rounding >>> float(22//5) 4.0 >>> int(4.5) 4 >>> int(3.9) 3 >>> round(3.9) 4 >>> round(3) 3 >>> round(3.1415926, 2) 3.14

Type Conversions & Rounding >>> int("32") 32 >>> float("32") 32.0 This is useful as a secure alternative to the use of eval for getting numeric data from the user.

Type Conversions & Rounding Using int instead of eval ensures the user can only enter valid whole numbers illegal (non-int) inputs will cause the program to crash with an error message. One downside this method does not accommodate simultaneous input.

Type Conversions & Rounding # A program to calculate the value of some change in dollars def change(): print("change Counter") print() print("please enter the count of each coin type.") quarters = int(input("quarters: ")) dimes = int(input("dimes: ")) nickels = int(input("nickels: ")) pennies = int(input("pennies: ")) total = quarters *.25 + dimes *.10 + nickels *.05 + pennies *.01 print() print("the total value of your change is", total)

Using the math library Computing with numbers

Using the Math Library Besides (+, -, *, /, //, **, %, abs), we have lots of other math functions available in a math library. A library is a module with some useful definitions/functions.

Using the Math Library Let s write a program to compute the roots of a quadratic equation! x = - - 2a 2 b b 4ac The only part of this we don t know how to do is find a square root but it s in the math library!

Using the Math Library To use a library, we need to make sure this line is in our program: import math Importing a library makes whatever functions are defined within it available to the program.

Using the Math Library To access the sqrt library routine, we need to access it as math.sqrt(x) Using this dot notation tells Python to use the sqrt function found in the math library module. To calculate the root, you can do discroot = math.sqrt(b*b 4*a*c)

Using the Math Library # A program that computes the real roots of a quadratic equation. # Illustrates use of the math library. # Note: This program crashes if the equation has no real roots. import math # Makes the math library available. def quadratic(): print("this program finds the real solutions to a quadratic") print() a, b, c = eval(input("please enter the coefficients (a, b, c): ")) discroot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discroot) / (2 * a) root2 = (-b - discroot) / (2 * a) print() print("the solutions are:", root1, root2 )

Using the Math Library This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 3, 4, -1 What do you suppose this means? This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 1, 2, 3 The solutions are: 0.215250437022-1.54858377035 Traceback (most recent call last): File "<pyshell#26>", line 1, in -toplevelmain() File "C:\Documents and Settings\Terry\My Documents\Teaching\W04\CS 120\Textbook\code\chapter3\quadratic.py", line 14, in main discroot = math.sqrt(b * b - 4 * a * c) ValueError: math domain error

Using the Math Library If a = 1, b = 2, c = 3, then we are trying to take the square root of a negative number! Using the sqrt function is more efficient than using **. How could you use ** to calculate a square root?

Using the Math Library Python Mathematics English pi An approximation of pi e e An approximation of e sqrt(x) p x The square root of x sin(x) sin x The sine of x cos(x) cos x The cosine of x tan(x) tan x The tangent of x asin(x) arcsin x The inverse of sine x acos(x) arccos x The inverse of cosine x atan(x) arctan x The inverse of tangent x

Using the Math Library Python Mathematics English log(x) ln x The natural (base e) logarithm of x log10(x) exp(x) ceil(x) floor(x) log 10 e x x x x The common (base 10) logarithm of x The exponential of x The smallest whole number >= x The largest whole number <= x

Accumulating results: Factorial Computing with numbers

Accumulating Results: Factorial Say you are waiting in a line with five other people. How many ways are there to arrange the six people? 720 -- 720 is the factorial of 6 (abbreviated 6!) Factorial is defined as: n! = n(n-1)(n-2) (1) So, 6! = 6*5*4*3*2*1 = 720

Accumulating Results: Factorial How we could we write a program to do this? Input number to take factorial of: n Compute factorial of n: fact Output: fact

Accumulating Results: Factorial How did we calculate 6!? 6*5 = 30 Take that 30, and 30 * 4 = 120 Take that 120, and 120 * 3 = 360 Take that 360, and 360 * 2 = 720 Take that 720, and 720 * 1 = 720

Accumulating Results: Factorial What s really going on? We re doing repeated multiplications, and we re keeping track of the running product. This algorithm is known as an accumulator, because we re building up or accumulating the answer in a variable, known as the accumulator variable.

Accumulating Results: Factorial The general form of an accumulator algorithm looks like this: Initialize the accumulator variable Loop until final result is reached update the value of accumulator variable

Accumulating Results: Factorial It looks like we ll need a loop! fact = 1 for factor in [6, 5, 4, 3, 2, 1]: fact = fact * factor Let s trace through it to verify that this works!

Accumulating Results: Factorial Why did we need to initialize fact to 1? There are a couple reasons Each time through the loop, the previous value of fact is used to calculate the next value of fact. By doing the initialization, you know fact will have a value the first time through. If you use fact without assigning it a value, what does Python do?

Accumulating Results: Factorial Since multiplication is associative and commutative, we can rewrite our program as: fact = 1 for factor in [2, 3, 4, 5, 6]: fact = fact * factor Great! But what if we want to find the factorial of some other number??

Accumulating Results: Factorial What does range(n) return? 0, 1, 2, 3,, n-1 range has another optional parameter! range(start, n) returns start, start + 1,, n-1 But wait! There s more! range(start, n, step) start, start+step,, n-1 list(<sequence>) to make a list

Accumulating Results: Factorial Let s try some examples! >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(range(5,10)) [5, 6, 7, 8, 9] >>> list(range(5,10,2)) [5, 7, 9]

Accumulating Results: Factorial Using this souped-up range statement, we can do the range for our loop a couple different ways. We can count up from 2 to n: range(2, n+1) (Why did we have to use n+1?) We can count down from n to 2: range(n, 1, -1)

Accumulating Results: Factorial Our completed factorial program: # Program to compute the factorial of a number # Illustrates for loop with an accumulator def factorial(): n = eval(input("please enter a whole number: ")) fact = 1 for factor in range(n,1,-1): fact = fact * factor print("the factorial of", n, "is", fact) factorial()

The Limits of Int What is 100!? >>> factorial() Please enter a whole number: 100 The factorial of 100 is 933262154439441526816992388562667004907159682643816214685929638952 175999932299156089414639761565182862536979208272237582511852109168 64000000000000000000000000 Wow! That s a pretty big number!

The Limits of Int Newer versions of Python can handle it, but Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> import fact >>> fact.main() Please enter a whole number: 13 13 12 11 10 9 8 7 6 5 4 Traceback (innermost last): File "<pyshell#1>", line 1, in? fact.main() File "C:\PROGRA~1\PYTHON~1.2\fact.py", line 5, in main fact=fact*factor OverflowError: integer multiplication

The Limits of Int What s going on? While there are an infinite number of integers, there is a finite range of ints that can be represented. This range depends on the number of bits a particular CPU uses to represent an integer value.

The Limits of Int Typical PCs use 32 bits or 64. That means there are 2 32 possible values, centered at 0. This range then is 2 31 to 2 31-1. We need to subtract one from the top end to account for 0. But our 100! is much larger than this. How does it work?

Handling Large Numbers Does switching to float data types get us around the limitations of ints? If we initialize the accumulator to 1.0, we get >>> main() Please enter a whole number: 30 The factorial of 30 is 2.652528598121911e+32 We no longer get an exact answer!

Handling Large Numbers: Long Int Very large and very small numbers are expressed in scientific or exponential notation. 2.652528598121911e+32 means 2.652528598121911 * 10 32 Here the decimal needs to be moved right 32 decimal places to get the original number, but there are only 16 digits, so 16 digits of precision have been lost.

Handling Large Numbers Floats are approximations Floats allow us to represent a larger range of values, but with fixed precision. Python has a solution, expanding ints! Python ints are not a fixed size and expand to handle whatever value it holds.

Handling Large Numbers Newer versions of Python automatically convert your ints to expanded form when they grow so large as to overflow. We get indefinitely large values (e.g. 100!) at the cost of speed and memory

Summary

Outline Writing python programs Software Development Process Example: Temperature Converter Elements of Programs Assignment Statements Definite Loops Example Program: Future Value Computing with nunmbers Numeric Data Types Type Conversions Using the Math Library Example: Factorial

Things to do... Readings from Textbook for next time: Chapter 5: Sequences: Strings, Lists, and Files Practicum 3 Practice computing with numbers Homework 1 posted on course website Turn in via github classroom Go through code examples again Lecture 2 Chapter 2 Chapter 3

Any Questions?

Acknowledgements Slides adapted & reused from Rachel Rakov's Methods in Computational Linguistics 1 course, Fall 2016 Some slides in this presentation have been adapted from the following sources: Python Programming: An Introduction to Computer Science (third edition) textbook slides, by John Zelle, Franklin, Beedle & Associates, http://mcsp.wartburg.edu/zelle/python/