Computing with Numbers Zelle - Chapter 3 Charles Severance - www.dr-chuck.com Textbook: Python Programming: An Introduction to Computer Science, John.

Slides:



Advertisements
Similar presentations
Computer Programming w/ Eng. Applications
Advertisements

Types and Arithmetic Operators
Chapter 3: Expressions and Interactivity. Outline cin object Mathematical expressions Type Conversion and Some coding styles.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
CS1 Lesson 3 Expressions and Interactivity CS1 -- John Cole1.
Copyright © 2012 Pearson Education, Inc. Chapter 3: Expressions and Interactivity.
1 Fundamental Data types Overview l Primitive Data Types l Variable declaration l Arithmetical Operations l Expressions l Assignment statement l Increment.
Python November 14, Unit 7. Python Hello world, in class.
CS 1 with Robots Variables, Data Types & Math Institute for Personal Robots in Education (IPRE)‏
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 3: Expressions and Interactivity.
1 Python Chapter 2 © Samuel Marateck, After you install the compiler, an icon labeled IDLE (Python GUI) will appear on the screen. If you click.
1 Data types, operations, and expressions Continued l Overview l Assignment statement l Increment and Decrement operators l Short hand operators l The.
Variables, Expressions, and Statements
CS 100: Roadmap to Computing Fall 2014 Lecture 01.
Programming Training Main Points: - Python Statements - Problems with selections.
Chapter 4 Numbers. Python Program Structure Python programs consist of: Modules Statements Expressions Objects.
Chapter 3.  Traditionally, programming languages have assigned different types of data for different types of numbers.  In many languages, there may.
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
D-1 University of Washington Computer Programming I Lecture 4: Arithmetic Expressions © 2000 UW CSE.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 2 Input,
Input, Output, and Processing
Operators in Python. Arithmetic operators Some operators in Python will look familiar (+, -, *, /) Others are new to you (%, //, **) All of these do work.
Functions Chapter 4 Python for Informatics: Exploring Information
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Variables, Expressions, and Statements
Variables, Expressions and Statements
Conditional Execution Chapter 3 Python for Informatics: Exploring Information
CS 1 with Robots Variables, Data Types & Math Institute for Personal Robots in Education (IPRE)‏ Sec 9-7 Web Design.
Expressions and Interactivity. 3.1 The cin Object.
Math, Data Types. Python Math Operations OperationOperator Addition + Subtraction – Multiplication * Division (floating point) / Division (integer) //
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
Doing math In java.
Chapter 3 Numerical Data. Objectives After you have read and studied this chapter, you should be able to Select proper types for numerical data. Write.
D-1 University of Washington Computer Programming I Lecture 4: Arithmetic Expressions © 2000 UW CSE.
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
29 January 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
PYTHON VARIABLES : CHAPTER 2 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST.
Functions Chapter 4 Python for Informatics: Exploring Information Slightly modified by Recep Kaya Göktaş on March 2015.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
1 09/10/04CS150 Introduction to Computer Science 1 What Actions Do We Have Part 2.
Variables, Expressions, and Statements Chapter 2 Python for Everybody
Fundamentals of Programming I Overview of Programming
Topics Designing a Program Input, Processing, and Output
Functions Chapter 4 Python for Everybody
Expressions An expression is a portion of a C++ statement that performs an evaluation of some kind Generally requires that a computation or data manipulation.
Presented By S.Yamuna AP/IT
Variables, Expressions, and IO
Python - Functions.
Variables, Expressions, and Statements
Introduction to Programming
Conditional Execution
Python - Conditional Execution
Conditional Execution
Conditional Execution
Variables, Expressions, and Statements
Variables, Data Types & Math
Computing in COBOL: The Arithmetic Verbs and Intrinsic Functions
Python for Informatics: Exploring Information
Variables, Data Types & Math
Expressions An expression is a portion of a C++ statement that performs an evaluation of some kind Generally requires that a computation or data manipulation.
Variables, Expressions, and Statements
CHAPTER 3: String And Numeric Data In Python
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Terminal-Based Programs
Decision Structures Zelle - Chapter 7
Primitive Data Types and Operators
Data Types and Expressions
Presentation transcript:

Computing with Numbers Zelle - Chapter 3 Charles Severance - Textbook: Python Programming: An Introduction to Computer Science, John Zelle (

Numbers Numeric Data Types and Numeric Operators Using the Math Library Type Conversions Strings and Numbers

What does “Type” Mean? In Python variables, literals, and constants have a “type” Python knows the difference between an integer number and a string For example “+” means “addition” if something is a number and “concatenate” if something is a string >>> ddd = >>> print ddd 5 >>> eee = "hello " + "there" >>> print eee hello there concatenate = put together

Type Matters Python knows what “type” everything is Some operations are prohibited You cannot “add 1” to a string We can ask Python what type something is by using the type() function. >>> eee = "hello " + "there" >>> eee = eee + 1 Traceback (most recent call last): File " ", line 1, in TypeError: cannot concatenate 'str' and 'int' objects >>> type(eee) >>> type("hello") >>> type(1) >>>

Several Types of Numbers Numbers have two main types Integers are whole numbers: -14, - 2, 0, 1, 100, Floating Point Numbers have decimal parts: -2.5, 0.0, 98.6, 14.0 There are other number types - they are variations on float and integer >>> xx = 1 >>> type (xx) >>> temp = 98.6 >>> type(temp) >>> type(1) >>> type(1.0) >>>

Numeric Expressions Because of the lack of mathematical symbols on computer keyboards - we use “computer-speak” to express the classic math operations Asterisk is multiplication Exponentiation (raise to a power) and absolute value | X | look different from in math.

Numeric Expressions >>> xx = 2 >>> xx = xx + 2 >>> print xx 4 >>> yy = 440 * 12 >>> print yy 5280 >>> zz = yy / 1000 >>> print zz 5 >>> jj = 23 >>> kk = jj % 5 >>> print kk 3 >>> print 4 ** 3 64 >>> print abs( ) >>>

Order of Evaluation When we string operators together - Python must know which one to do first This is called “operator precedence” Which operator “takes precedence” over the others x = * / 5 ** 6

Operator Precedence Rules Highest precedence rule to lowest precedence rule Parenthesis are always respected Exponentiation (raise to a power) Multiplication, Division, and Remainder Addition and Subtraction Left to right Parenthesis Power Multiplication Addition Left to Right

Parenthesis Power Multiplication Addition Left to Right >>> x = ** 3 / 4 * 5>>> print x11>>> ** 3 / 4 * / 4 * *

Parenthesis Power Multiplication Addition Left to Right >>> x = ** 3 / 4 * 5>>> print x11>>> ** 3 / 4 * / 4 * * Note 8/4 goes before 4*5 because of the left-right rule.

Operator Precedence Remember the rules top to bottom When writing code - use parenthesis When writing code - keep mathematical expressions simple enough that they are easy to understand Break long series of mathematical operations up to make them more clear Parenthesis Power Multiplication Addition Left to Right Exam Question: x = * / 5

Integer Division Integer division truncates Floating point division produces floating point numbers >>> print 10/2 5 >>> print 9/2 4 >>> print 99/100 0 >>> print 10.0 / >>> print 99.0 /

Mixing Integer and Floating When you perform an operation where one operand is an integer and the other operand is a floating point the result is a floating point The integer is converted to a floating point before the operation >>> print 99 / >>> print 99 / >>> print 99.0 / >>> print * 3 / >>> z-66

Type Conversions When you put an integer and floating point in an expression the integer is implicitly converted to a float You can control this with the built in functions int() and float() >>> print float(99) / >>> i = 42 >>> type(i) >>> f = float(i) >>> print f 42.0 >>> type(f) >>> print * float(3) / >>>

String Conversions You can also use int() and float() to convert between strings and integers You will get an error if the string does not contain numeric characters >>> sval = "123" >>> type(sval) >>> print sval + 1 Traceback (most recent call last): File " ", line 1, in TypeError: cannot concatenate 'str' and 'int' >>> ival = int(sval) >>> type(ival) >>> print ival >>> nsv = "hello bob" >>> niv = int(nsv) Traceback (most recent call last): File " ", line 1, in ValueError: invalid literal for int()

Sneak Peek: Error Recovery Are you tired of seeing trace back errors? Do you want to do something about it? Do you want to take control of error recovery? Then you should take advantage of the try/accept capability in Python! z-216 >>> niv = int(nsv) Traceback (most recent call last): File " ", line 1, in ValueError: invalid literal for int()

The try / except Structure You surround a dangerous section of code with try and except. If the code in the try works - the except is skipped If the code in the try fails - it jumps to the except section z-216

$ cat notry.py astr = "Hello Bob"istr = int(astr)print "First", istrastr = "123"istr = int(astr)print "Second", istr $ python notry.py Traceback (most recent call last): File "notry.py", line 6, in istr = int(astr)ValueError: invalid literal for int() with base 10: 'Hello Bob' The program stops here All Done z-216

$ cat tryexcept.py astr = "Hello Bob" try: istr = int(astr) except: istr = -1 print "First", istr astr = "123" try: istr = int(astr) except: istr = -1 print "Second", istr $ python tryexcept.py First -1 Second 123 When the first conversion fails - it just drops into the except: clause and the program continues. When the second conversion succeeds - it just skips the except: clause and the program continues. z-216

Math Library Python also includes common math functions You must import math to use these >>> import math >>> print math.sqrt(25.0) 5.0

(in radians) (returns radians)

Trigonometry Review Radians represent the length of an arc described by an angle in the unit circle (radius 1.0) So 45 degrees is pi / 4 or 1/8 the way around the entire unit circle (2 * pi) 45 pi >>> import math >>> print math.pi >>> print math.pi / >>> print math.cos(math.pi / 4) cos

Math Function Summary The math functions are there when you need them Unless we are solving complex trigonometry problems or statistics problems - pretty much all we use is the square root >>> import math >>> print math.sqrt(25.0) 5.0

Summary Variables, Literals, and constants have a type Python knows what type each object is Operations may work differently between types The common number types are floating point and integer We use functions to convert between strings, integers, and floats Peek Ahead Page We can use try / except blocks to keep our program from blowing up with bad data Python has rich support for common mathematical functions These functions are mostly useful for statistics and trigonometry Games use lots of trigonometry