0% found this document useful (0 votes)
63 views

Stored Programs: Mastering Cyberspace: An Introduction To Practical Computing

Here is a program that does the conversion: # Author: Anonymous # Date: 6/10/2013 # Converts feet and inches to meters feet = float(input("How many feet? ")) inches = float(input("How many inches? ")) total_inches = feet * 12 + inches total_cm = total_inches * 2.54 total_m = total_cm / 100 print(feet, "feet and", inches, "inches =", total_m, "meters")

Uploaded by

TimmySmith
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)
63 views

Stored Programs: Mastering Cyberspace: An Introduction To Practical Computing

Here is a program that does the conversion: # Author: Anonymous # Date: 6/10/2013 # Converts feet and inches to meters feet = float(input("How many feet? ")) inches = float(input("How many inches? ")) total_inches = feet * 12 + inches total_cm = total_inches * 2.54 total_m = total_cm / 100 print(feet, "feet and", inches, "inches =", total_m, "meters")

Uploaded by

TimmySmith
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
You are on page 1/ 9

Stored Programs

In the previous lecture, we examined how digital devices


can carry out routine activities.
Basic idea: We can store the steps in a routine activity in
memory in ways that a computer can execute.

COMPSCI 111 / 111G

This notion of a stored program is one of the basic insights


that underlies computing and information technology.

Mastering Cyberspace:
An Introduction to Practical Computing

This concept is so fundamental that many courses assume


it is obvious, but it deserves close attention.
Variables, Input/Output, and
Conditions in Programming
10/7/14

COMPSCI 111/111G - Python 02

Storing and Interpreting Programs

Another Stored Program

We need two things to allow routine activity on computers:

To find the hidden treasure of Greenbeard the Data Pirate:

Encode and store the program in memory:


Giving the program a name or index so we can access it;
Specifying the programs initial, intermediate, final steps.
Access and run the program on demand:
Retrieving the program by its name or index;
Passing any arguments to the program;
Executing each of the programs steps in turn; and
Halting the program and returning any results.

1.
2.
3.
4.
5.

COMPSCI 111/111G - Python 02

Go to the dead tree in the center of the island.


Turn north and walk 200 paces.
Turn east and walk 100 paces.
Turn north and walk 50 paces.
Dig five feet down to the treasure.

This program requires you to count the number of steps


you take, resetting the count twice in the process.
To run the program, we need some way to keep track of
the count and update it when needed.

We explored these ideas in the context of Python, a recent


computer programming language.
10/7/14

10/7/14

COMPSCI 111/111G - Python 02

Using Variables in Python

Using Variables in Programs

To assign a value to a variable, type:

A stored program can keep track of things that change


during operation using variables, which:

The variable name


An equals (=) sign

Serve as place holders to store some form of information;

The desired value (or an expression that returns it)

Take some initial value at the programs outset;

count = 15
DollarsPerLitre1 = 2.16
Number_of_Geese = 7 * 2 + 3

Can change repeatedly during the programs execution;


May be returned by the program when it halts.

The use of variables adds substantially to the flexibility


and power of stored programs.

Variable names in Python:


May contain numbers or underscores
May not start with a number or contain blank spaces

Program variables are similar to those in mathematics,


but they are assigned values that can change in a run.

May not be reserved Python keywords (like in)


Examples: count, DollarsPerLitre1, Number_of_Geese

10/7/14

COMPSCI 111/111G - Python 02

10/7/14

COMPSCI 111/111G - Python 02

More on Variables in Python

More on Variables in Python

Here are some examples of setting variables in IDLE, the


Python development environment.
>>>
>>>
>>>
10
>>>
20
>>>
>>>
200
>>>

Here are more examples that illustrate the use of variables


as counters that change over time.
>>>
>>>
1
>>>
>>>
2
>>>
>>>
3
>>>

height = 10
width = 20
height
width
area = height * width
area

Note that Python does not return a variables value when


you set it, but it does when you type its name.
10/7/14

COMPSCI 111/111G - Python 02

age = 1
age
age = age + 1
age
age = age + 1
age

In this case, we start by setting the variable age to 1 and


incrementing it by 1 repeatedly.
7

10/7/14

COMPSCI 111/111G - Python 02

Exercise on Variables

Exercise on Variables

What results will these four Python statements produce?

What results will these four Python statements produce?

>>> a = 2
>>> b = 7
>>> a

>>> a
>>> b
>>> a
2
>>> c
>>> c
15
>>> c
>>> c
15.0
>>> d
>>> c
24.0

>>> c = a * b + 1
>>> c
>>> c = float(c)
>>> c
>>> d = a + b
>>> c + d

10/7/14

COMPSCI 111/111G - Python 02

10/7/14

Input and Output for Programs

= 2
= 7

= a * b + 1

= float(c)
= a + b
+ d

COMPSCI 111/111G - Python 02

10

Reading Input in Python


The Python function input accepts information typed by the
user and returns a string with its contents.

In many settings, we want our stored programs to interact


with users; for this they need some means for:

The operators one argument is printed as a prompt. E.g.,

Requesting and accepting external input


Generating and displaying external output

name = input("Enter your name: ")

Of course, we can use variables to store results of input


or to collect results for output.

would print "Enter your name: ", wait for a user to type
something and hit enter, then place the result in name.

We will examine how Python requests and accepts input,


as well as how it generates and displays output.

The input function returns a string, so if you want to obtain


a number, you must alter the data type, as in
children = int(input("How many children: "))
weight = float(input("Enter your weight: "))

10/7/14

COMPSCI 111/111G - Python 02

11

10/7/14

COMPSCI 111/111G - Python 02

12

Input Exercise

Input Exercise

What values does x take on given these input statements?

What values does x take on given these input statements?

>>> x = input("Enter some words: ")


Enter some words: Some words
>>> x = input("Enter an integer: ")
Enter an integer: 15
>>> x = int(input("Enter an integer: "))
Enter an integer: 15
>>> x = input("Enter a floating number: ")
Enter a floating number: 15.0
>>> x = float(input("Enter a floater: "))
Enter a floater: 15.0
>>> a = int(input("First number? "))
First number? 3
>>> b = float(input("Second number? "))
Second number? 5
>>> x = a * b
10/7/14

>>> x = input("Enter some words: ")


Enter some words: Some words

x is

>>> x = input("Enter an integer: ")


Enter an integer: 15

x is

>>> x = int(input("Enter an integer: "))


Enter an integer: 15

x is

>>> x = input("Enter a floating number: ")


Enter a floating number: 15.0

x is

>>> x = float(input("Enter a floater: "))


Enter a floater: 15.0

x is

>>> a = int(input("First number? "))


First number? 3
>>> b = float(input("Second number? "))
Second number? 5
>>> x = a * b

x is

COMPSCI 111/111G - Python 02

13

10/7/14

Printing Output in Python

x is 15
x is '15.0'
x is 15.0

x is 15.0

COMPSCI 111/111G - Python 02

14

What outputs do these Python print statements produce?


print("This", "is")
print("a program that has")
print(3, "lines.")
print(1,2,3,4)
print("1,2,3,4")
print("1234", 1,2)
print("1",2,3,"4")

For this purpose, you can use the print function:


>>> print("How are you?")
How are you?
>>> print(34.9)
34.9
>>> print(2)
2
>>> year = 2014
>>> print("The year is", year, ".")
The year is 2014 .

Given multiple arguments, it inserts a space between items.


COMPSCI 111/111G - Python 02

x is '15'

Printing Exercise

Although IDLE returns a value for each statement the user


inputs, sometimes you want to generate explicit output.

10/7/14

x is 'Some words'

15

print(1 + 2 + 3)
print("1" + "2" + "3")
print([1, 2] * 2)
print(1 + 3 // 2)
x = 20
print(x % 7)
print(x // 7)
10/7/14

COMPSCI 111/111G - Python 02

16

Printing Exercise

Commenting Programs

What outputs do these Python print statements produce?


print("This", "is")
print("a program that has")
print(3, "lines.")
print(1,2,3,4)
print("1,2,3,4")
print("1234", 1,2)
print("1",2,3,"4")

This is
a program that has
3 lines.
1 2 3 4
1,2,3,4
1234 1 2
1 2 3 4

print(1 + 2 + 3)
print("1" + "2" + "3")
print([1, 2] * 2)
print(1 + 3 // 2)
x = 20
print(x % 7)
print(x // 7)

6
123
[1, 2, 1, 2]
2

10/7/14

Including comments in a program can make it easier for


humans to understand it.
In Python, a line that includes a hash sign (#) causes the
interpreter to ignore everything until the lines end.
# Author: Andrew Luxton-Reilly
# Date: 7/05/06
# Purpose: Show the use of comments
print("Hello")
# Hello, Hello
print("Is there anybody in there")
print("Just nod if you can hear me")
print("Is there anyone at home")

6
2

COMPSCI 111/111G - Python 02

As in this example, you should begin each file with comments


about its author, date, and purpose.
17

10/7/14

Combining Input and Output

Here is Python code that asks the user to enter a number


in centimetres.
# Author: Andrew Luxton-Reilly
# Date: 7/05/06

# Author: Andrew Luxton-Reilly


# Date: 7/05/06

# Ask the user to enter the number of centimetres


cm = int(input("Please enter the number of centimetres: "))

# Ratio of NZD to USD


currencyRatio = 0.6409 # 1 NZD = 0.6409 USD

# Calculate the number of metres and centimetres


m = cm // 100
cm = cm % 100

# Ask the user to enter the NZD value


nzd = float(input("Please enter the dollar value (NZD): "))
# Calculate the amount of USD
usd = nzd * currencyRatio

# Print the output to the user


print(m, "metres and", cm, "centimeters")

# Print the output to the user


print(nzd, "NZ dollars is worth", usd, "US dollars")

COMPSCI 111/111G - Python 02

18

Another Conversion Program

Here is a program that converts NZD to USD, assuming


that 1.0 NZD = 0.6409 USD.

10/7/14

COMPSCI 111/111G - Python 02

The stored program then prints the number of metres and


centimeters that are equivalent to the input.
19

10/7/14

COMPSCI 111/111G - Python 02

20

Combined Exercise

Exercise

Write a program that asks the user to enter a number of


feet and then a number of inches.

Write a program that asks the user to enter a number of


feet and then a number of inches.

The program should convert this length to the number of


meters (with decimals) and print the specific relation.

The program should convert this length to the number of


meters (with decimals) and print the specific relation.

Assume: 1.0 inch = 2.54 centimetres, 1 foot = 12 inches

Assume: 1.0 inch = 2.54 centimetres, 1 foot = 12 inches


# Author: Anonymous
# Date: 6/10/2013
# This function requests feet and inches from the user, computes
# the number of centimetres for each, then divides by 100.0 and
# prints the corresponding number of metres.
feet = int(input("How many feet? "))
inches = int(input("How many inches? "))
cm = 12 * 2.54 * feet + 2.54 * inches
print(feet,"feet and",inches,"inches is",(cm / 100.0),"meters.")

10/7/14

COMPSCI 111/111G - Python 02

21

10/7/14

COMPSCI 111/111G - Python 02

22

Conditionals in Stored Programs

More on Jamaican Curry Chicken


Note that our recipe incorporates conditional statements:

Many of our everyday routine activities involve conditional


behavior of this sort.

1. Wash chicken with lemon and cut into bite-sized pieces.


2. Season with all dry ingredients.
3. Chop all herbs and add to chicken (use hands to rub in
seasonings, and let sit in refrigerator for 1/2 hr.).
4. Place chicken, water, and oil in a pot, stir, cook on high until it
comes to a boil, stir, lower heat until chicken is almost cooked.
5. Add potatoes and butter.
6. Cook until water is reduced and potatoes are tender.
7. Serve over steamed white rice.

We can produce conditional activity in stored programs by


stating that some steps should happen only if a test is met.
Such constructs ease construction of computer programs
because it makes them more flexible and adaptive.
Nearly all nontrivial stored programs include some form of
conditional behavior.

These tests are essential to produce an edible dish that is


neither undercooked or overcooked.
10/7/14

COMPSCI 111/111G - Python 02

23

10/7/14

COMPSCI 111/111G - Python 02

24

Conditional Behavior in Python

Python Comparison Operators

One way to specify conditional behavior in Python involves


the if construction, which takes the form:

Python includes a number of operators that compare two


items of the same type.
These evaluate to a Boolean value, making them eligible
for use in conditions.

if <condition>:
statements to execute if condition is True
else:
statements to execute if condition is False

Meaning

This includes colons after both the condition and the else.

Less than

Operator

Examples

<

0 < x, a < b

<=

y <= 10, a <= b

>

x > 0, a > b
y >= 10, a >= b

The condition should be some Boolean expression that


evaluates to either True or False.

Less than or equal to

Multiple statements may appear in a block associated with


a condition, provided they are indented the same amount.

Greater than or equal to

>=

Equal to

==

z = "here", a == b

Not equal to

!=

z != [1, 2], a != b

10/7/14

COMPSCI 111/111G - Python 02

Greater than

25

10/7/14

A Conditional Python Program

Write a program that asks the user to enter his or her age,
and then prints out a ticket based on that age:
Child tickets (below the age of 12) cost $5.00
Adult tickets (age 12 or above) cost $9.99

# Author: Andrew Luxton-Reilly


# Date: 7/05/06

Tickets for children should look like the display on the left,
while those for adults should look like that on the right.

# Ask the user to enter a number


number = int(input("Please enter a number: "))

************
Child Ticket
Price: $5.00
************

# Determine if the number is odd or even


if (number % 2 == 0):
print("You entered the number", number)
print("That number is even")
else:
print("You entered the number", number)
print("That number is odd")
COMPSCI 111/111G - Python 02

26

Conditional Exercise

Here is a Python program that asks the user to enter some


integer. It determines whether the number is odd or even,
then prints an appropriate message.

10/7/14

COMPSCI 111/111G - Python 02

27

10/7/14

*************
Adult Ticket
Price: $9.99
*************

COMPSCI 111/111G - Python 02

28

Conditional Exercise

Conditional Exercise

Write a program that asks the user to enter his or her age,
and then prints out a ticket based on that age:

Write a program that asks the user to enter his or her age,
and then prints out a ticket based on that age:

Child tickets (below the age of 12) cost $5.00

Child tickets (below the age of 12) cost $5.00

Adult tickets (age 12 or above) cost $9.99

Adult tickets (age 12 or above) cost $9.99

Tickets for children should look like the display on the left,
while those for adults should look like that on the right.
************
Child Ticket
Price: $5.00
************

10/7/14

Tickets for children should look like the display on the left,
while those for adults should look like that on the right.
age = int(input("What is your age? "))
print("************")
************
*************
if age < 12:
Child Ticket
Adult Ticket
print("Child
Ticket")
print("Price:
$5.00")
Price: $5.00
Price: $9.99
else:
************
*************
print("Adult Ticket")
print("Price: $9.99")
print("************")

*************
Adult Ticket
Price: $9.99
*************

COMPSCI 111/111G - Python 02

29

10/7/14

Python Logical Operators

Operator

Example

Logical AND

and

number >= 1 and number < 10

or

z == "here" or z == "there"

not

not(number < 1 or number >= 10)

Logical OR
Logical NOT

30

Yet Another Exercise

Python also includes some operators that combine Boolean


expressions into more complex constructions.
Meaning

COMPSCI 111/111G - Python 02

Write a program that asks the user to enter a number


between one and ten (inclusive).
The program should print "Correct" if the number is in the
range and "Incorrect" if the number is outside the range.

These let Python programs support an even broader class


of conditional statements.
Note that you can embed one logical expression in another,
just as with numeric expressions.
10/7/14

COMPSCI 111/111G - Python 02

31

10/7/14

COMPSCI 111/111G - Python 02

32

Yet Another Exercise

Review of Key Ideas

Write a program that asks the user to enter a number


between one and ten (inclusive).

We examined three constructs for use in stored programs:


Variables that store values in a persistent manner
But that can change during the course of a run

The program should print "Correct" if the number is in the


range and "Incorrect" if the number is outside the range.

Commands that accept external input and print output


To support interaction with human users
Conditional statements that produce alternative behaviors
Depending on the results of Boolean test expressions

# Author: Andrew Luxton-Reilly


# Date: 7/05/06
# Ask the user to enter a number
number = int(input("Please enter a number (1-10): "))

Together, these abilities extend considerably the ability of


stored programs to carry out routine tasks.

# Determine if the number is within the range


if (number >= 1 and number <= 10):
print("Correct")
else:
print("Incorrect")
10/7/14

COMPSCI 111/111G - Python 02

We discussed these ideas in the context of Python, but


they appear in most programming languages.
33

10/7/14

COMPSCI 111/111G - Python 02

34

You might also like