Python Programming: An Introduction To Computer Science
Python Programming: An Introduction To Computer Science
Chapter 2
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
The process of creating a program is often broken down into stages according to the information that is produced in each phase.
Analyze the Problem Figure out exactly the problem to be solved. Try to understand it as much as possible.
Dont worry about how the program will work, but what it will do. Includes describing the inputs, outputs, and how they relate to one another.
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.
Translate the design into a computer language. In this course we will use Python.
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!
Python Programming, 2/e 8
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.
Analysis the temperature is given in Celsius, user wants it expressed in degrees Fahrenheit. Specification
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 11
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 12
Pseudocode:
Input the temperature in degrees Celsius (call it celsius) Calculate fahrenheit as (9/5)*celsius+32 Output fahrenheit
13
14
>>> 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, 2/e 15
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.
Python Programming, 2/e 16
Elements of Programs
17
Elements of Programs
Some identifiers are part of Python itself. These identifiers 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. and, del, for, is, raise, assert, elif, in, print, etc. For a complete list, see table 2.1
Python Programming, 2/e 18
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 can also be expressions.
19
Elements of Programs
>>> 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 >>>
NameError is the error when you try to use a variable without a value assigned to it.
Python Programming, 2/e 20
Elements of Programs
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)
21
Elements of Programs
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.
22
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 347 347 The answer is 7
23
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 24
Assignment Statements
25
Assignment Statements
myVar = 7 myVar
myVar = myVar + 1 myVar
26
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.
27
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.
28
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>))
29
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.
30
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 31
Simultaneous Assignment
sum, diff = x+y, x-y How could you use this to swap the values for x and y?
Simultaneous Assignment
x, y = y, x
x=3 y=4 print x, y x, y = y, x print x, y
33
Simultaneous Assignment
We can use this same idea to input multiple variables from a single input statement! Use commas to separate the inputs
>>> 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! >>>
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!)
34
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 35
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.
36
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 >>>
37
Definite Loops
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 38
Definite Loops
for loops alter the flow of program execution, so they are referred to as control structures.
39
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
Python Programming, 2/e 40
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
41
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 Relatonship Value after one year is given by principal * (1 + apr). This needs to be done 10 times.
Python Programming, 2/e 42
43
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.")
44
45
47