Python Programming: An Introduction to Computer Science

Slides:



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

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.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Chapter 2 Writing Simple Programs
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.
Computer Science 101 Introduction to Programming.
CS190/295 Programming in Python for Life Sciences: Lecture 2 Instructor: Xiaohui Xie University of California, Irvine.
Introduction to Python
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 2.
General Programming Introduction to Computing Science and Programming I.
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.
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
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 2 Input, Processing, and Output.
The Software Development Process
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
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.
2. WRITING SIMPLE PROGRAMS Rocky K. C. Chang September 10, 2015 (Adapted from John Zelle’s slides)
Xiaojuan Cai Computational Thinking 1 Lecture 2 Simple Programs Xiaojuan Cai (蔡小娟) Fall, 2015.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 2.
Chapter 2 Writing Simple Programs
Introduction to Computing Science and Programming I
CMPT 120 Topic: Python’s building blocks -> More Statements
Topic: Python’s building blocks -> Variables, Values, and Types
Topics Designing a Program Input, Processing, and Output
Chapter 6 JavaScript: Introduction to Scripting
Python: Experiencing IDLE, writing simple programs
Chapter 2 Introduction to C++ Programming
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Topic: Python’s building blocks -> Statements
Completing the Problem-Solving Process
Chapter 2: Input, Processing, and Output
Python: Control Structures
Python Programming: An Introduction to Computer Science
Revision Lecture
Presented By S.Yamuna AP/IT
The Selection Structure
Variables, Expressions, and IO
Chapter Topics 2.1 Designing a Program 2.2 Output, Input, and Variables 2.3 Variable Assignment and Calculations 2.4 Variable Declarations and Data Types.
Intro to PHP & Variables
Introduction to C++ Programming
Programming Fundamentals (750113) Ch1. Problem Solving
CS190/295 Programming in Python for Life Sciences: Lecture 2
Rocky K. C. Chang September 18, 2018 (Based on Zelle and Dierbach)
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Programming Fundamentals (750113) Ch1. Problem Solving
15-110: Principles of Computing
Flowcharts and Pseudo Code
Topics Designing a Program Input, Processing, and Output
Programming Fundamentals (750113) Ch1. Problem Solving
Topics Designing a Program Input, Processing, and Output
Chapter 2: Input, Processing, and Output
Unit 3: Variables in Java
Chopin’s Nocturne.
Introduction to Computer Science
Introduction to Computer Science
The Last of the Mohicans (大地英豪)
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

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

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/e

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/e

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/e

The Software Development Process Determine Specifications Describe exactly what your program will do. (program assignment page here) 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/e

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/e

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

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/e

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, in the real world uses 2/3rd of the time spent on a program Python Programming, 2/e

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/e

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/e

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/e

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

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/e Python Programming, 1/e

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 212.0 degrees Fahrenheit. What is the Celsius temperature? -40 The temperature is -40.0 degrees Fahrenheit. Python Programming, 2/e

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/e

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/e

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

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

Identifiers age_of_dog taxRateY2K VALID NOT VALID (Why?) PrintHeading ageOfHorse NOT VALID (Why?) age# 2000TaxRate Age-Of-Cat in

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 are also expressions Use expressions to manipulate variables Python Programming, 2/e

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

Elements of Programs Expressions can be combined using operators. +, -, *, /, ** Spaces are irrelevant within an expression- please use them for ease of reading! The normal mathematical precedence applies, () then **, then * / then + or - ((x1 – x2) / 2*n) + (spam / k**3) Python Programming, 2/e

Operator Precedence Operator Description ( ) 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/e

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/e

Elements of Programs Output Statements A print statement can print any number of expressions. Successive print statements will display on separate lines unless you use “end=“. A bare print will print a blank line. Using print (17, end=“ “) will leave the cursor on the same line on the screen. Python Programming, 2/e

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 The answer is 7 Python Programming, 2/e

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

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

Assignment Statements Variables can be reassigned as many times as you want! >>> myVar = 0 >>> myVar >>> myVar = 7 7 >>> myVar = myVar + 1 8 >>> Python Programming, 2/e

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

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

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>)) Note precedence – input is done FIRST (because inner parentheses) THEN eval is done on what is input Python Programming, 2/e

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

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

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

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 4 3 Python Programming, 2/e

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

Types of variables You can change the TYPE of a variable with the data that you store in it! >>> a = 5 >>> a 5 >>>a = “abc” >>>a ‘abc’ >>> Python Programming, 2/e

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

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

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

Definite Loops What does 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. Python Programming, 2/e

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

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

Hand work for analysis given amount $100.00 and rate 5% per year 100 + interest after 1 year = 105.00 105 + interest = 110.25 110.25 + interest = 115.7625 four years = 121.550625 five years = 127.62815625 Python Programming, 2/e

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

Example 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 5 years in the future Relatonship Value after one year is given by principal * (1 + apr). This needs to be done 5 times. Python Programming, 2/e

Example Program: Future Value Design Print an introduction Input the amount of the principal (principal) Input the annual percentage rate (apr) Repeat 5 times: principal = principal * (1 + apr) Output the value of principal Python Programming, 2/e

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 5-year investment.") Input the amount of the principal principal = eval(input("Enter the initial principal: ")) Python Programming, 2/e

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

Example Program: Future Value # futval.py # A program to compute the value of an investment # carried 5 years into the future def main(): print("This program calculates the future value of a 5-year investment.") principal = eval(input("Enter the initial principal: ")) apr = eval(input("Enter the annual interest rate: ")) for i in range(5): principal = principal * (1 + apr) print ("The value in 5 years is:", principal) main() Python Programming, 2/e

Example Program: Future Value >>> main() This program calculates the future value of a 5-year investment. Enter the initial principal: 100 Enter the annual interest rate: .05 The value in 5 years is: 127.62815625 Enter the annual interest rate: .10 The value in 5 years is: 161.051 Python Programming, 2/e

Program Style Use of spacing and blank lines put blanks around operators blank lines in between some lines of code help readability Use of comments header comments at the top of the file – filename, name, section, date, PURPOSE pre- and post-conditions document algorithm steps, describe difficult code

Syntax Errors Reported by the interpreter Program won’t run if there are any! Try to understand what the error was Error messages are not clear keep a log of messages and what they mean

Logic (Semantic) Errors Caused by a faulty algorithm They are only found by testing - interpreter does not detect them! Testing choose an input value calculate by hand the expected output run the program and check the actual output Test several different input values

You should be familiar with <var>, <var> … = simultaneous assignment (2.5.3) for i in [0,1,…] using a sequence of numbers in a for loop (2.6) Python Programming, 2/e