0% found this document useful (0 votes)
9 views50 pages

Chapter 2

Chapter 2 outlines the steps in the software development process, including problem analysis, specification determination, design creation, implementation, testing, and maintenance. It introduces the input-process-output (IPO) pattern and provides examples of simple Python programs, such as a temperature converter and a future value calculator. The chapter also covers Python identifiers, expressions, assignment statements, and loops.

Uploaded by

vkelechi2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views50 pages

Chapter 2

Chapter 2 outlines the steps in the software development process, including problem analysis, specification determination, design creation, implementation, testing, and maintenance. It introduces the input-process-output (IPO) pattern and provides examples of simple Python programs, such as a temperature converter and a future value calculator. The chapter also covers Python identifiers, expressions, assignment statements, and loops.

Uploaded by

vkelechi2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 2

Writing Simple Programs

1
Objectives
◼ To know the steps in an orderly software development
process.
◼ To understand programs following the input, process, output
(IPO) pattern and be able to modify them in simple ways.
◼ To understand the rules for forming valid Python identifiers
and expressions.
◼ 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

2
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.
◼ Analyze the Problem
◼ Determine Specifications
◼ Create a Design
◼ Implement the Design
◼ Test/Debug the Program
◼ Maintain the Program

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

4
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.

5
The Software Development
Process
◼ Create a Design
◼ Formulate the overall structure of the
program.
◼ This is where the how of the program gets
worked out.
◼ Develop your own algorithm that meets the
specifications.

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

7
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.
◼ Your goal is to find errors, so try
everything that might “break” your
program!

8
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.

9
Example Program:
Temperature Converter
◼ Problem
◼ Tom is studying in an Asian country for a year. He struggles to figure out
the morning temperature and, therefore, what to wear. He listens to the
weather forecast every morning, but the temperature is in Celsius, whereas
he is used to Fahrenheit. As a computer science student, he thinks a
computer program might be able to help.

◼ 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

10
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

11
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.

12
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!

13
Example Program:
Temperature Converter
#[Link]
# A program to convert Celsius temperatures to Fahrenheit

def main():
celsius = float(input("What is the Celsius temperature? "))
fahrenheit = (9/5) * celsius + 32
print("The temperature is ", fahrenheit, " degrees Fahrenheit.")

main()

14
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.
>>> main()
What is the Celsius temperature? -40
The temperature is -40.0 degrees Fahrenheit.
>>>

15
Elements of Programs
◼ Names
◼ Names are given to variables (celsius, fahrenheit),
functions (main), modules (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.
◼ Identifiers should not contain white space.
◼ Identifiers should not contain any special character other
than an underscore (_).
◼ Identifiers cannot be reserved Python keywords.

16
Elements of Programs
◼ These are all different, valid names
◼ X
◼ Celsius
◼ Spam
◼ spam
◼ spAm
◼ Spam_and_Eggs
◼ Spam_And_Eggs

17
Elements of Programs
◼ 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.
◼ Python keywords

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.
◼ Also included are strings (textual data) and string
literals (like "Hello").

19
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
>>>
◼ NameError is the error when you try to use a variable
without a value assigned to it.

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
◼ print(<expr>, <expr>, …, <expr>)
◼ print()
◼ 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.
◼ print(<expr>, end=" ")

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
3 4 7

3 4 7
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.
◼ Examples
◼ x = 3.9 * x * (1-x)
◼ fahrenheit = 9/5 * celsius + 32
◼ x = 5
24
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
>>>

25
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.

26
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”.

27
Assigning Input
◼ The purpose of an input statement is to get input from the
user and store it into a variable.
◼ <variable> = input(<prompt>)
◼ Here, prompt is a string expression used to prompt the
user for input.

28
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 a string of
characters.
◼ The value is assigned to the variable.
◼ For string input:
<var> = input(<prompt>)

29
Assigning Input
◼ When you want a number from the user, include either int
or float around the input to convert the digits into either a
whole value (integer) or fractional value (float).

◼ Examples
◼ age = int(input("Please enter your current age: "))
◼ celsius = float(input("What is the Celsius temperature? "))

30
Simultaneous Assignment
◼ Several values can be calculated at the same
time
◼ <var1>, <var2>, … = <expr1>, <expr2>, …

◼ Evaluate the expressions in the RHS and assign


them to the variables on the LHS
◼ sum, diff = x+y, x-y

31
Simultaneous Assignment
◼ Suppose there are two variables x and y.
◼ How could you swap the values for x and y?
◼ Why doesn’t this work?
x = y
y = x

◼ We could use a temporary variable…


temp = x
x = y
y = temp

32
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, 4/e 33


Review Questions
◼ True/False
1. The best way to write a program is to immediately type in some code and
then debug it until it works.
2. An algorithm can be written without using a programming language.
3. Python identifiers must start with a letter or underscore.
◼ Multiple Choice
1. The process of describing exactly what a computer program will do to solve
a) design b) implementation c) programming d) specification
2. Which of the following are not used in expressions?
a) variables b) statements c) operators d) literals

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.
◼ This is the counted loop pattern.

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.


◼ Often, the sequence portion consists of a list of
values.
◼ A list is a sequence of expressions in square brackets.

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
◼ In [Link], 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 from 0 by default.
◼ list is a built-in Python function that turns the
sequence into an explicit list
◼ The body of the loop executes 10 times.

38
Definite Loops
◼ The name of the index variable doesn’t
matter much.
◼ Programmers often use i or j.
◼ If you don’t reference the index variable inside
your loop, you can leave it anonymous.
◼ for _ in range(3):
print("Howdy!")

39
Definite Loops
◼ for loops alter the
flow of control, so
they are referred to
as control
structures.
for <var> in <sequence>:
<body>

40
Example Program: Future
Value
◼ Problem
◼ Money deposited in a bank account earns interest, and this
interest accumulates over time. What will this account be
worth in ten years?

◼ 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

41
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 …

42
Example Program: Future
Value
◼ 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.

43
Example Program: Future
Value
◼ 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

44
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", end=" ")
print("value of a 10-year investment.")

◼ Input the amount of the principal


principal = float(input("Enter the initial principal: "))

45
Example Program: Future
Value
◼ Input the annual percentage rate
apr = float(input("Enter the annual interest rate: "))
◼ Repeat 10 times:
for i in range(10):
◼ Calculate principal = principal * (1 + apr)
principal = principal * (1 + apr)
◼ Output the value of the principal at the end of 10 years
print("The value in 10 years is:", principal)

46
Example Program: Future
Value
# [Link]
# A program to compute the value of an investment
# carried 10 years into the future

def main():
# Print an introduction
print("This program calculates the future", end=" ")
print("value of a 10-year investment.")

# Input
principal = float(input("Enter the initial principal: "))
apr = float(input("Enter the annual interest rate: "))

# Processing
for _ in range(10):
principal = principal * (1 + apr)

# Output
print("The value in 10 years is:", principal)

main()

47
Example Program: Future
Value
>>>
This program calculates the future value of a 10-year investment.
Enter the initial principal: 100
Enter the annual interest rate: 0.03
The value in 10 years is: 134.39163793441222
>>> 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.37424601000026

48
Review Questions
◼ True/False
1. A counted loop is designed to iterate a specific number of times.
2. The function int and float are used to turn user inputs into numbers.
◼ Multiple Choice
1. Fragments of code that produce or calculate new data values are called
a) identifiers b) expressions c) productive clauses d) assignment statements
2. Which of the following is the most accurate model of assignment in Python?
a) sticky-note b) variable-as-box c) simultaneous d) plastic-scale

49
Question
What is the output of the following Python code?
def main():
x = 3
y = x
x = 4
y = y + x

print(x)
print(y)

main()

A: 3 B: 4 C: 8 D: 3 E: 4
6 8 8 7 7

50

You might also like