Python Programming: An Introduction to Computer Science

Similar documents
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

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

Python Programming: An Introduction to Computer Science

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

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

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

Functions: Decomposition And Code Reuse

Fundamentals of Programming (Python) Getting Started with Programming

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

CMSC 201 Computer Science I for Majors

Programming with Python

Getting Started with Python

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

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

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

Functions: Decomposition And Code Reuse

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

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

Variable and Data Type I

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

ENGR 101 Engineering Design Workshop

Variables, Expressions, and Statements

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?

Variables, expressions and statements

Ruby: Introduction, Basics

File processing and decision structures

Variable and Data Type I

Python Intro GIS Week 1. Jake K. Carr

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

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

Basic Syntax - First Program 1

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

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

Python Evaluation Rules

Conditionals and Recursion. Python Part 4

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

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han

CMSC 201 Spring 2018

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!

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

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

3. Java - Language Constructs I

Introduction to Computer Programming for Non-Majors

COMP 202 Java in one week

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

CS Summer 2013

Ruby: Introduction, Basics

Chapter 3 : Informatics Practices. Class XI ( As per CBSE Board) Python Fundamentals. Visit : python.mykvs.in for regular updates

PYTHON. Values and Variables

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

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

Chapter 2. Elementary Programming

Full file at

CSCE 120: Learning To Code

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

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

Introduction to Computer Programming for Non-Majors

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

Python Programming: An Introduction to Computer Science

Introduction to Computer Programming for Non-Majors

Functions: Decomposition And Code Reuse

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

String and list processing

Decision Structures CSC1310. Python Programming, 2/e 1

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

Program Planning, Data Comparisons, Strings

Expressions and Variables

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

The float type and more on variables FEB 6 TH 2012

cs1114 REVIEW of details test closed laptop period

About Variables in Python F E B 1 1 T H

Table of Contents EVALUATION COPY

CS242 COMPUTER PROGRAMMING

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

Some material adapted from Upenn cmpe391 slides and other sources

Introduction to Computer Programming for Non-Majors

Unit 1: Algorithmic problem solving 1

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

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

Introduction to Python, Cplex and Gurobi

Introduction to Computer Programming for Non-Majors

Introduction to Python (All the Basic Stuff)

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

1/11/2010 Topic 2: Introduction to Programming 1 1

Transcription:

Python Programming: An Introduction to Computer Science Chapter 2 Writing Simple Programs Python Programming, 3/e 1

Objectives n To know the steps in an orderly software development process. n To understand programs following the input, process, output (IPO) pattern and be able to modify them in simple ways. n To understand the rules for forming valid Python identifiers and expressions. Python Programming, 3/e 2

Objectives n 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, 3/e 3

The Software Development Process n The process of creating a program is often broken down into stages according to the information that is produced in each phase. Python Programming, 3/e 4

The Software Development Process n Analyze the Problem Figure out exactly the problem to be solved. Try to understand it as much as possible. Python Programming, 3/e 5

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

The Software Development Process n Create a Design n Formulate the overall structure of the program. n This is where the how of the program gets worked out. n Develop your own algorithm that meets the specifications. Python Programming, 3/e 7

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

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

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

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

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

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

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

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, 3/e 15

Example Program: Temperature Converter n 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. >>> Python Programming, 3/e 16

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

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

Elements of Programs n 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. n and, del, for, is, raise, assert, elif, in, print, etc. n For a complete list, see Table 2.1 (p. 32) Python Programming, 3/e 19

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

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

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

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

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

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

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

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

Assignment Statements n Variables are like a box we can put values in. n When a variable changes, the old value is erased and a new one is written in. Python Programming, 3/e 28

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

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

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

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

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

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

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

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

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

Simultaneous Assignment n We can use this same idea to input multiple variables from a single input statement! n 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, 3/e 38

Definite Loops n 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. n for <var> in <sequence>: <body> n The beginning and end of the body are indicated by indentation. Python Programming, 3/e 39

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

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

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

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

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

Example Program: Future Value n Specification n User enters the initial amount to invest, the principal n User enters an annual percentage rate, the interest n The specifications can be represented like this Python Programming, 3/e 45

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

Example Program: Future Value n 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 Python Programming, 3/e 47

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

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

Example Program: Future Value # 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.") main() 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) Python Programming, 3/e 50

Example Program: Future Value >>> 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 Python Programming, 3/e 51