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

Similar documents
Python Programming: An Introduction to Computer Science

Introduction to Computer Programming for Non-Majors

CITS 4406 Problem Solving & Programming

Python Programming: An Introduction to Computer Science

Introduction to Computer Programming for Non-Majors

Writing Python Programs, Numerical Data Types

Worlframalpha.com Facebook Report

Chapter 2 Writing Simple Programs

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

Python Programming: An Introduction to Computer Science

Introduction to Computer Programming for Non-Majors

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

Python Programming: An Introduction to Computer Science

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Fundamentals of Programming (Python) Getting Started with Programming

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

CMSC 201 Computer Science I for Majors

Getting Started with Python

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

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

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming

Programming with Python

ENGR 101 Engineering Design Workshop

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Introduction to Python and Programming. 1. Python is Like a Calculator. You Type Expressions. Python Computes Their Values /2 2**3 3*4+5*6

Review. Input, Processing and Output. Review. Review. Designing a Program. Typical Software Development cycle. Bonita Sharif

Variables, expressions and statements

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

Variable and Data Type I

cs1114 REVIEW of details test closed laptop period

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

T H E I N T E R A C T I V E S H E L L

Introduction to Computer Programming for Non-Majors

CS 105 Lab As a review of what we did last week a. What are two ways in which the Python shell is useful to us?

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

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Chapter 2 Input, Processing and Output. Hong Sun COSC 1436 Spring 2017 Jan 30, 2017

Functions: Decomposition And Code Reuse

Variables, Expressions, and Statements

Full file at

Variable and Data Type I

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

Introduction to Python (All the Basic Stuff)

COMP 202 Java in one week

CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps

CMSC 201 Spring 2018

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Name Feb. 14, Closed Book/Closed Notes No electronic devices of any kind! 3. Do not look at anyone else s exam or let anyone else look at yours!

Functions: Decomposition And Code Reuse

CSE / ENGR 142 Programming I

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Jython. secondary. memory

CS242 COMPUTER PROGRAMMING

Introduction to Computer Programming for Non-Majors

Starting. Read: Chapter 1, Appendix B from textbook.

3. Java - Language Constructs I

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

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

PYTHON. Values and Variables

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

Decision Structures CSC1310. Python Programming, 2/e 1

CS 115 Lecture 8. Selection: the if statement. Neil Moore

Programming for Engineers Iteration

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

CSCE 110 Programming I Basics of Python: Lists, Tuples, and Functions

File processing and decision structures

Loop structures and booleans

CS Summer 2013

Introduction to Computer Programming for Non-Majors

Program Planning, Data Comparisons, Strings

Lecture 4: Basic I/O

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

Extended Introduction to Computer Science CS1001.py Lecture 10, part A: Interim Summary; Testing; Coding Style

Introduction to Python and programming. Ruth Anderson UW CSE 160 Winter 2017

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

CSEN 102 Introduction to Computer Science

4. The is a diagram that graphically depicts the steps that take place in a program. a. Program b. Flowchart c. Algorithm d. Code e.

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Gold Hw8 Problem 3: TT Securities, Incorporated

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Ruby: Introduction, Basics

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Lecture. Simulation && Design. Richard E Sarkis CSC 161: The Art of Programming

CITS 1401 Problem Solving & Programming

Control Structures 1 / 17

Python Programming: An Introduction To Computer Science

The >>> is a Python prompt indicating that Python is ready for us to give it a command. These commands are called statements.

Python Evaluation Rules

Programming to Python

Conditionals and Recursion. Python Part 4

Introduction to Computer Programming for Non-Majors CSC 2301, Fall The Department of Computer Science

Transcription:

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

Class Administrivia

Agenda To be able to understand and write Python statements to output information to the screen To assign values to variables To get numeric information entered from the keyboard To perform a counted loop

Software Development Process

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.

Software Development Process 1. Analyze the Problem 2. Determine Specifications 3. Create a Design 4. Implement the Design 5. Test/Debug the Program 6. Maintain the Program

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

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.

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

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

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!

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

Example: Temperature Converter 1. Analyze the Problem 2. Determine Specifications 3. Create a Design 4. Implement the Design 5. Test/Debug the Program Analysis The temperature is given in Celsius, user wants it expressed in degrees Fahrenheit. 6. Maintain the Program

Example: Temperature Converter 1. Analyze the Problem 2. Determine Specifications 3. Create a Design 4. Implement the Design 5. Test/Debug the Program 6. Maintain the Program Specification Input: temperature in Celsius Output: temperature in Fahrenheit Tout F = 9/5(Tin C) + 32

Example: Temperature Converter 1. Analyze the Problem 2. Determine Specifications 3. Create a Design 4. Implement the Design 5. Test/Debug the Program 6. Maintain the Program Design 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: Temperature Converter 1. Analyze the Problem 2. Determine Specifications 3. Create a Design 4. Implement the Design 5. Test/Debug the Program 6. Maintain the Program Design: Pseudocode Input the temperature in degrees Celsius Calculate fahrenheit as (9/5)*celsius+32 Output fahrenheit Now we need to convert this to Python!

Example: Temperature Converter 1. Analyze the Problem 2. Determine Specifications 3. Create a Design 4. Implement the Design 5. Test/Debug the Program 6. Maintain the Program # 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()

Example: Temperature Converter 1. Analyze the Problem 2. Determine Specifications 3. Create a Design 4. Implement the Design 5. Test/Debug the Program 6. Maintain the Program Implement 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. >>> main() What is the Celsius temperature? -40 The temperature is -40.0 degrees Fahrenheit. >>>

Example: Temperature Converter 1. Analyze the Problem 2. Determine Specifications 3. Create a Design 4. Implement the Design 5. Test/Debug the Program 6. Maintain the Program Maintain Keep your code updated! Come back after, say, a year and review your code If others use it, you ll support it for life!

Elements of Programs

Elements of Programs Identifiers Names are given to data values (celsius, fahrenheit), modules (convert), functions (main), etc. These names are called identifiers, and they're used to describe objects in Python

Elements of Programs Identifiers Required: identifiers must begin with a letter or underscore ( _ ), followed by any sequence of letters, digits, or underscores Identifiers are case sensitive, e.g. FooBar!= foobar

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

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

Elements of Programs Reserved Words Some words are part of Python itself These words are known as reserved words This means they are not available for you to use as a name for a variable, etc. in your program, e.g. and, del, for, is, raise, assert, elif, in For a complete list: https://docs.python.org/3/reference/lexical_analysis.html#keywords

Elements of Programs Literals Literals are values in source code that are written exactly as they are meant to be interpreted. Strings, integers, floating point numbers, boolean values, etc. 3.9, 24, True, Cheezburger

Elements of Programs Expressions The fragments of code that produce or calculate new data value(s) are called expressions Simple identifiers can also be expressions They can consist of function calls, variable names, literals, and operators, etc.

Elements of Programs Expressions 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 Expressions 3 + 5 x y == 22

Elements of Programs Statements Statements are lines of code that 'do something' Expressions are often parts of statements print(42) if x == 22: do_y() return a = 7

Elements of Programs Statements Output Statements 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) 7 >>> print(3, 4, 3+4) 3 4 7 >>> print() >>> print("the answer is", 3+4) The answer is 7 >>>

Assignment Statements

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) >>> T_out = 9/5 * (T_in) + 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 Before x 10 x = x + 1 x After 11 Figure 2.1: Variable as box view of x = x + 1

Assignment Statements However! 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 Before After x = x + 1 x 10 x 10 11 Figure 2.2: Variable as sticky note (Python) view of x = x + 1

In the C Language int num = 0; In the Python Language num = 0 0 10 10

Assignment Statements User Input The purpose of an input statement is to get input from the user and store it into a variable <variable> = eval(input(<prompt>))

Assignment Statements User 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

Assignment Statements 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 sum, diff = x+y, x-y

Assignment Statements Simultaneous Assignment 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

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

Assignment Statements Simultaneous Assignment We can use this same idea to assign 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

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 <var> after the for is called the loop index It is assigned each successive value in <sequence>

Definite Loops >>> for i in [0,1,2,3]: print (i) 0 1 2 3 >>> for odd in [1, 3, 5, 7]: print(odd*odd) 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 more items in <sequence> no for loops alter the flow of program execution, so they are referred to as control structures yes <var> = next item <body> Figure 2.3: Flowchart of a for loop.

Example Program: Future Value

Example: Future Value 1. Analyze the Problem 2. Determine Specifications 3. Create a Design 4. Implement the Design 5. Test/Debug the Program 6. Maintain the Program 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: Future Value 1. Analyze the Problem 2. Determine Specifications 3. Create a Design 4. Implement the Design 5. Test/Debug the Program 6. Maintain the Program Specifications 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: Future Value 1. Analyze the Problem 2. Determine Specifications 3. Create a Design 4. Implement the Design 5. Test/Debug the Program 6. Maintain the Program 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 Relationship: Value after one year is given by principal * (1 + apr) This needs to be done 10 times.

Example: Future Value 1. Analyze the Problem 2. Determine Specifications 3. Create a Design 4. Implement the Design 5. Test/Debug the Program 6. Maintain the Program Design 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: Future Value 1. Analyze the Problem 2. Determine Specifications 3. Create a Design 4. Implement the Design 5. Test/Debug the Program 6. Maintain the Program 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: Future Value 1. Analyze the Problem 2. Determine Specifications 3. Create a Design 4. Implement the Design 5. Test/Debug the Program 6. Maintain the Program Implementation Input the annual percentage rate apr = eval(input("enter the annual interest rate: ")) Repeat 10 times: for i in range(10): Calculate principal 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: Future Value 1. Analyze the Problem 2. Determine Specifications 3. Create a Design 4. Implement the Design 5. Test/Debug the Program 6. Maintain the Program # futval.py # A program to compute the value of an investment # carried 10 years into the future def main(): 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) main()

Example: Future Value 1. Analyze the Problem 2. Determine Specifications 3. Create a Design 4. Implement the Design 5. Test/Debug the Program 6. Maintain the Program >>> main() 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 >>> main() 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

Coding in Style

PEP 8

Questions?