Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 2.

Slides:



Advertisements
Similar presentations
Computer Programming w/ Eng. Applications
Advertisements

Types and Arithmetic Operators
Adapted from John Zelle’s Book Slides
Python Programming: An Introduction to Computer Science
CSC 110 Writing simple programs [Reading: chapter 2] CSC 110 C 1.
Vahé Karamian Python Programming CS-110 CHAPTER 2 Writing Simple Programs.
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.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Expressions and Operators Program Style.
Data types and variables
Introduction to Python
Chapter 2 Writing Simple Programs
Chapter 2 Data Types, Declarations, and Displays
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Testing Test Plans and Regression Testing. Programs need testing! Writing a program involves more than knowing the syntax and semantics of a language.
Data Types. Every program must deal with data The data is usually described as a certain type This type determines what you can do with the data and how.
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
Identifiers and Assignment Statements. Data structures In any programming language you need to refer to data The simplest way is with the actual data.
Fundamentals of Python: From First Programs Through Data Structures
Computer Science 101 Introduction to Programming.
Objectives You should be able to describe: Data Types
A First Book of ANSI C Fourth Edition
INLS 560 – V ARIABLES, E XPRESSIONS, AND S TATEMENTS Instructor: Jason Carter.
(2.1) Fundamentals  Terms for magnitudes – logarithms and logarithmic graphs  Digital representations – Binary numbers – Text – Analog information 
Fortran 1- Basics Chapters 1-2 in your Fortran book.
Introduction to Python
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 2.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
CS 127 Writing Simple Programs.  Stages involved  Analyze the problem  Understand as much as possible what is trying to be solved  Determine Specifications.
Computer Science 101 Introduction to Programming.
Python Libraries Importing and Calling functions.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
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
CPS120: Introduction to Computer Science
Operators in Python. Arithmetic operators Some operators in Python will look familiar (+, -, *, /) Others are new to you (%, //, **) All of these do work.
1 INTRODUCTION TO PROBLEM SOLVING AND PROGRAMMING.
CPS120: Introduction to Computer Science Operations Lecture 9.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
2. WRITING SIMPLE PROGRAMS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
Python Let’s get started!.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 2.
Type Casting. Type casting Sometimes you need a piece of data converted to a different type In Python you do a typecast to cause that to happen int(3.599)
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter 2 Writing Simple Programs
Fundamentals of Programming I Overview of Programming
Topics Designing a Program Input, Processing, and Output
Python: Experiencing IDLE, writing simple programs
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Python Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science
The Selection Structure
Variables, Expressions, and IO
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Chopin’s Nocturne.
Presentation transcript:

Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 2

Python Programming, 2/e2 Objectives 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, and perform a counted loop

Python Programming, 2/e3 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.

Python Programming, 2/e4 The Software Development Process Analyze the Problem Figure out exactly the problem to be solved. Try to understand it as much as possible. (done by instructor here) Try doing a problem by hand to verify you understand it – this also generates some test data for later.

Python Programming, 2/e5 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.

Python Programming, 2/e6 The Software Development Process Create a Design Formulate the overall structure of the program. (done by individual /team here) This is where the how of the program gets worked out. You choose or develop your own algorithm that meets the specifications. This is where you write pseudocode.

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

Python Programming, 2/e8 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. (using test cases done by team here) Your goal is to find errors, so try everything that might “ break ” your program! Don’t be afraid to Experiment!

Python Programming, 2/e9 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. Not done in this class

Python Programming, 2/e10 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

Python Programming, 2/e11 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

Python Programming, 2/e12 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.

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

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

Python Programming, 2/e15 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. >>> main() What is the Celsius temperature? 100 The temperature is degrees Fahrenheit. >>> main() What is the Celsius temperature? -40 The temperature is degrees Fahrenheit. >>>

Elements of Programs # at the start of a line is a comment This line is ignored by the Python interpreter It is meant to be read by humans Explain the code there, don’t repeat the code! Required in every program in this class! Python Programming, 2/e16

Python Programming, 2/e17 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! No spaces allowed in an identifier

Python Programming, 2/e18 Elements of Programs These are all different, valid names X Celsius Spam spam spAm Spam_and_Eggs Spam_And_Eggs

Python Programming, 2/e19 Elements of Programs Some identifiers are part of Python itself. These identifiers are known as reserved words. (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. “Good programmers use names that describe the item being named”

Identifiers An identifier has to being with an alphabetic character or the underscore character _ There can be more characters in the identifier, those can be alphabetic, numeric or the underscore character Upper or lower case alphabetic characters are allowed

Identifiers VALID age_of_dogtaxRateY2K PrintHeading ageOfHorse NOT VALID (Why?) age# 2000TaxRateAge-Of-Cat in

Keywords Keywords define the language’s syntax rules and structure Keywords cannot be used as variable names.

Keywords andasbreakclass continue defelifelse finallyforfromglobalifimport inisnotor passreturntrywhile with True FalseNone

Data Types Every program must deal with data The data is usually described as a certain type This type determines what you can do with the data and how the data is stored In Python basic types are integers (int), floating point (float), strings and Booleans The first two are numeric and can be used in arithmetic, the last two are not

Integers vs. Floating point Integers are numbers which have no decimals, no fractions They can be positive, negative, zero Python can handle numbers of very, very large magnitude Floating point numbers are ones which have fractions, like 3.14 and 2.0 and They are stored differently in the computer and their arithmetic is done differently

Floating point numbers - storage Each floating point number is stored in several pieces. You can think of one as being written in scientific notation, like x 10 2 = In Python this is written as 3.592e2 (the base is assumed to be 10) The is the mantissa

Floating point numbers - storage The 2 is the power or exponent – it can be positive or negative. Positive powers make numbers larger, negative powers make numbers smaller (towards zero) Example: 4.923e-3 = Example: e10 =

Strings These data items are delimited by quotes, either single quotes (‘) or double quotes (“) (Delimited by means that they are enclosed by the quotes, marked off by the quotes) We will use them in many ways simply as labels “Total of numbers” variables like names and address Examples: “Joe”, “ adfa123.s8234&*”, “”, ‘”hi” he said’

Booleans Named after George Boole, English mathematician, logician Created Boolean algebra, a two-valued logic based on True and False The basis of all computer circuits (see EE 280) In Python the Boolean constants are True and False – note that these are not strings – no quotes They can be assigned to variables, they can be output They are used most often with if statements

Data type check type() function to check type Example: type(3) : type(4.5): type(‘abc’): type(True):

Type casting Sometimes you need a piece of data converted to a different type In Python you do a typecast to cause that to happen int(3.599) will give 3 – note that it throws away the fraction, does not round it float (4349) will give – it looks the same but remember that it is stored differently in memory

Type casting float(“23.4”) will give 23.4, but float(“abc”) will give a runtime error The type converter float can turn an integer, a float, or a syntactically legal string into a float x = 5.3 y = int(x) makes y have the value 5, does NOT change x’s value

Type cast for strings str will turn a number into a string. This is handy when you are using functions which require a string as an argument str(3.5) will give “3.5” str(“abc”) will give “abc” – this one is silly but Python allows it. If the data is already a string, why make it a string again?

Input function The input function allows the user to provide a prompt string. n = input("Please enter your name: ") It is very important to note that the input function returns a string value. n = input("Please enter your age: ")

Typecasting with input function Typecasting is used pretty often with the input function my_num = int(input(“Enter a number “)) This is the shorthand way of writing two statements my_data = input(“Enter a number “)) my_num = int(my_data)

Arithmetic operators Some operators in Python will look familiar (+, -, *, /) Others are new to you (%, //, **) All of these do work with numbers and produce numbers

For any operator you need to know How many arguments does it have and what do they mean What data type are the arguments? (int, float, string, etc.) The semantics of the operator, which is what does it do? What does it mean? What data type does the operator return? NOT always the same as the type of the arguments What is its precedence or priority with other operators?

Example: addition + It has two arguments (we are talking about the addition operator here, not the unary plus sign) The arguments can be ints or floats It produces the sum of the values of the two arguments It produces an integer if the arguments are both integers, otherwise it produces a floating point number It is relatively low precedence, comes after * and /

Other familiar operators Multiplication * works on ints and floats, produces an int if 2 int arguments, float otherwise Subtraction works similarly to multiplication Division / works on ints and floats, but always returns a float

Operator Precedence Precedence is same as in algebra, multiplication and division higher than addition and subtraction If there are two operators in an expression of the same level of precedence, they are executed left to right in the expression a + b + c is done as (a + b) + c

Operator Precedence OperatorDescription ( )Parentheses (grouping) function( )function call, execute a function and get what it returns **Exponentiation (raise to a power) * /Multiplication, division + -Addition, subtraction =Assignment Python Programming, 2/e41

Operator Precedence Important! principal = principal * (1 + apr) is not the same as principal = principal * 1 + apr answer = 20 – ((5+3)/(5-1)) answer = 18 Python Programming, 2/e42

New Operators // and % // is similar to division but always gives the whole number part of the quotient (result of dividing) If give two ints, will give an int, otherwise a float 5 // 4 = 1, 5 // 4.0 = 1.0 (not 1.25)

New Operators // and % % is the modulus operator, gives the remainder of a division operation If give two ints, yields an int, otherwise a float 13 % 4 = 1 (the remainder when 13 is divided by 4), 8 % 4 = 0 These two operators have the same precedence as multiplication and division

New Operator ** ** means exponentiation Has two arguments a ** b a is the base, b is the power to raise a to 5 **3 = 5 * 5 * 5, 7 ** 2 = 7 * 7 = 49 The precedence is higher than the other arithmetic operators The base or power can be integer or float As usual, if two int arguments, gives int result, otherwise float

New operator ** Is right associative (different from all of the other operators) Associativity is only needed when the operators in an expression have the same precedence 4 ** 3 ** 2 = 4 ** (3 ** 2) = 4 ** 9 = But +, –, *, / are left associative = (7 -4) + 1 not 7 – (4+1)

Expressions The fragments of code that produce or calculate new data values are called expressions Expressions can be combined using operators. +, -, *, /, ** Spaces are irrelevant within an expression- please use them for ease of reading!

Assignment statements Syntax is simple identifier = expression Python does allow more than one identifier on the left, see “Simultaneous Assignments” for more information Semantics: evaluate the expression on the right and then assign the value to the identifier on the left The expression can be as simple as a literal or more complex by using function calls, list indexing, arithmetic operators, etc.

Python Programming, 2/e49 Assignment Statements x = 3.9 * x * (1-x) fahrenheit = 9/5 * celsius + 32 x = 5

Python Programming, 2/e50 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 >>>

Simultaneous assignments (Only in Python) If you use more than one identifier on the left hand side of an assignment statement, you can store more than one thing. Example: x, y = 5, 4 Semantics: x gets the 5 and y gets the 4 You have to be careful – If the right hand side does not yield as many values as the left hand side expects, it causes a crash.

Python Programming, 2/e52 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

Python Programming, 2/e53 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 = int(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! >>>

Library – a group of prewritten functions and predefined constants Many actions are frequently done in programming, like taking the square root, finding a sine or cosine, drawing a graphics shape, getting a random number The maker of the language (or sometimes a third party) creates a library which contains these actions already written for you.

Library – a group of prewritten functions and predefined constants You don’t have to know how to do these things, you just know how to call the function given in the library. Many disciplines use special constants. The most famous one is pi. It is convenient to have these already defined instead of having to look them up and type them in yourself.

Importing a library Before you are allowed to use library functions, you have to import the library into your code There are 3 different ways to do this The simplest is just “import math” (to get the math library) If you use this method, you have to qualify the names of the functions with “math.” example “math.sqrt”

Importing a library The next way is “from math import sqrt” (to get one specific function) If you use this method, you can just use the function name “sqrt” The third way is “from math import *” (to get all functions in the library) Again, you do not have to qualify names if you do this, just “sqrt”

Using the functions After you have done the import statement, you need to call or invoke the library functions This is done in two ways, depending on whether the function returns a value or does not A function which returns a value is called as part of another statement A function which does not return a value is called as a stand-alone statement

Example of using a library function and constant from math import sin, cos def main(): angle = float(input(“Enter an angle in radians “)) radius = float(input(“Enter a radius”)) print(sin(angle), cos(angle)) s = sin(angle) c = cos(angle) area = pi * radius ** 2

Example of using a library function which does not return a value from graphics import * def main(): win = GraphWin() # returns a value win.close() # does not return a value

A few notes about libraries Note where the import statement was placed in the examples It is put before and outside of the main function definition It is better in general to be put near the top of your source file and outside all function definitions Why? Because that way all functions in your file can use the library functions (it has to do with scope, which will be discussed in chapter 5)

A few notes about libraries Don’t include a library if you do not need to use it – it only confuses things and reduces the confidence of anyone reading your code! You do not need to import the math library to use the math operators like +, *, -, //, %, etc.

Testing Writing a program involves more than knowing the syntax and semantics of a language You need to verify that your program runs correctly, i.e. does not crash unexpectedly and gives the correct answers/outputs. A simple program may be obviously right or wrong, but once it gets past more than 10 lines, a program needs to be tested systematically. Putting in some data picked at random will do a little good, but to be confident that your program works, you need to have a plan.

A test case A typical test case has four items: A description of the case – what are you testing for here? Input data which causes the case to happen The expected output/outcome from that input The actual output/outcome from that input In a software company, the authors of the software would write up test cases with the first three items, then hand off the job to the testers. The testers would run the tests, record the actual outputs and return the results to the authors, who would fix the errors found.

A Test plan A test plan is a table which contains a number of test cases. The quality of the test cases is more important than the quantity. It is important to give test cases that do not overlap if possible. If your program has two paths through it and all your test cases run through just one of the two possible paths, then you have not thoroughly tested your program. Python Programming, 2/e

A test plan Making good test plans requires thought and knowledge of the specifications of the problem. Think about normal cases, boundary cases, special cases, error cases. Python Programming, 2/e

Test plan for CS115 Our test plans will only have three major columns instead of four. The last one, the Actual Output, is assumed to be unnecessary. If you find a case where the expected output and the actual output do not agree, you have found a bug and we assume you will fix it. I say “major columns” because as the programs get more complex, there may be several different inputs for one run of the program. These would all be under “Input” but would have their own columns

Boundary case If your problem involves ranges of values (numbers from 1 to 10, letters from C to R, etc.) then you should be careful to test the boundary cases. Humans commonly make the error of going one time too far or stopping one time too soon. In the case of numbers from 1 to 10 (assuming integers), test cases should be done for 0, 1 and 2, and 9, 10, and 11. This is an example of checking boundary conditions.

Error case Some problems have cases which will not have correct answers or will have unusual behaviors (crashing). These cases should be investigated also, as far as possible. "non-numeric characters" will cause a program in Python to crash if it is entered as input when the program expects a numeric type

Error case "non-numeric characters" covers ALL of the characters except the numeric digits (and possibly "+" and "-" and "." which are all valid parts of a number) (also "e" and "E" for exponential numbers) so use non-numeric characters when you mean "anything BUT numbers"