Slides - Mypages

advertisement
Python Programming:
An Introduction to
Computer Science
Chapter 1
Computers and Programs
Python Programming, 2/e
1
Objectives



To understand the respective roles of
hardware and software in a computing
system.
To learn what computer scientists study
and the techniques that they use.
To understand the basic design of a
modern computer.
Python Programming, 2/e
2
Objectives (cont.)


To understand the form (syntax) and
function (semantics) of computer
programming languages.
To begin using the Python
programming language.
Python Programming, 2/e
3
The Universal Machine


A modern computer can be defined as
“a machine that stores and manipulates
information under the control of a
changeable program.”
Two key elements:


Computers are devices for manipulating
information.
Computers operate under the control of a
changeable program.
Python Programming, 2/e
4
The Universal Machine

What is a computer program?



A detailed, step-by-step set of instructions
telling a computer what to do.
If we change the program, the computer
performs a different set of actions or a
different task.
The machine stays the same, but the
program changes! (Von Neumann
model)
Python Programming, 2/e
5
The Universal Machine

Programs are executed, or carried out
by the CPU(s).
Python Programming, 2/e
6
Program Power



Software (programs) rule the hardware
(the physical machine).
The process of creating this software is
called programming.
Why learn to program?


Fundamental part of computer science
Having an understanding of programming
helps you have an understanding of the
strengths and limitations of computers.
Python Programming, 2/e
7
Program Power





Helps you become a more intelligent user
of computers
It can be fun!
Creative form of expression
Helps the development of problem solving
skills, especially in analyzing complex
systems by reducing them to interactions
between simpler systems.
Programmers are in great demand!
Python Programming, 2/e
8
What is Computer Science?



It is not the study of computers!
“Computers are to computer science
what telescopes are to astronomy.” –
E. Dijkstra
The question becomes, “What
processes can be described?”
This question is really, “What can be
computed?”
Python Programming, 2/e
9
What is Computer Science?

Design


One way to show a particular problem can
be solved is to actually design a solution.
This is done by developing an algorithm,
a step-by-step process for achieving the
desired result.
Python Programming, 2/e
10
Euclid’s Algorithm for GCD

1.
2.
Finding the greatest common divisor,
one of the 1st known algorithms
Get two numbers, call them num1 and
num2
While num2 is not zero
1.
2.
3.
If num1 > num2, num1 = num1 – num2
otherwise num2 = num2 - num1
Show num1 as the GCD
Python Programming, 2/e
11
What is Computer Science?

Analysis



Analysis is the process of examining
algorithms and problems mathematically.
Some seemingly simple problems are not
solvable by any algorithm. These problems
are said to be unsolvable (halting
problem)
Problems can be intractable if they would
take too long or take too much memory to
be of practical
value (traveling salesman)12.
Python Programming, 2/e
Alan Turing


First to formalize the concept of
“computation” using a hypothetical
device called the “Turing Machine”
In the 30s, he laid the foundations of
theoretical computer science
Python Programming, 2/e
13
Finite State Machine



Input
States
Transitions
Basically, a simple Turing Machine.
Python Programming, 2/e
14
Example FSM that recognizes the word “nice”
Python Programming, 2/e
15
Turing Machine


More complicated version of an FSM
using infinite amount of tape, actions
(move head left, right)
To this day, it is the model of
computation of choice for theoretical
computer scientists
Python Programming, 2/e
16
Graphic rendition of a Turing Machine
Python Programming, 2/e
17
Undecidability


In any axiomatic mathematical system,
there are statements that cannot be
proven true or false (Gödel’s Theorem)
E.g., proof by Turing: determine if a
program halts (ends) at some point or
continues to run forever
Python Programming, 2/e
18
On the other hand…

There exist problems that are
intractable


There are algorithms to solve them, but
they take prohibitive amount of time or
space to solve them
E.g.: traveling salesperson problem,
knapsack problem, many more

These problems become intractable as the
size of the input (e.g.: number of cities)
19
increases Python Programming, 2/e
Implementation


Computer scientists DO write code
See web page for Python
implementation of Euclid’s algorithm
Python Programming, 2/e
20
What is Computer Science?

Experimentation


Some problems are too complex for precise
mathematical analysis.
Instead, you can implement a system that
simulates the problem and then study its
behavior.
Python Programming, 2/e
21
Hardware Basics

The central processing unit (CPU) is the
“brain” of a computer.


The CPU carries out all the basic
operations on the data.
Examples: simple arithmetic operations,
testing to see if two numbers are equal,
I/O requests sent to peripherals.
Python Programming, 2/e
22
Hardware Basics

Memory and secondary storage hold
programs and data.



CPU can only directly access information
stored in main memory (RAM or Random
Access Memory).
Main memory is fast but volatile, i.e. when
the power is interrupted, the contents of
memory are lost.
Secondary storage provides more
permanent storage: magnetic (hard drive,
floppy), optical
(CD, DVD) but slower 23
Python Programming, 2/e
Memory (RAM)




A memory cell (also called a word)
has an address, has contents
Contents are expressed in bits / bytes binary code; a byte is made up of 8 bits
Holds a value which may be data, may
be an instruction
data retrieval = a "copy" not a "cut"
getting a value does not erase it
Memory Cells
Address Contents
0
1
2
3
-27.2
354
0.005
-26
4
5
6
H
RTV 001
...
...
999
X
75.62
Secondary Storage





Files - source files, data file, output file
Devices - hard disk, floppy, CD, SD
card, flash memory stick
Slower than RAM, and cheaper per byte
Usually much larger capacity than RAM
Permanent – does not change when
power is cut off
Computer Units


Units of capacity - Kilobyte (2^10),
Megabyte (2^20), Gigabyte (2^30),
Terabyte (2^40), Petabyte (2^50),
Exabyte (2^60)
Units of speed – MegaHertz, GigaHertz
speed of signals from system clock
Python Programming, 2/e
27
Hardware Basics

Input devices


Output devices


Information is passed to the computer
through keyboards, mice, etc.
Processed information is presented to the
user through the monitor, printer, etc.
Both are peripherals
Python Programming, 2/e
28
Programming Languages

Natural language has ambiguity and
precision problems when used to
describe complex algorithms.



Programs expressed in an unambiguous ,
precise way using programming languages.
Every structure in programming language
has a precise form, called its syntax
Every structure in programming language
has a precise meaning, called its
semantics. (What does the computer
do when that
structure
is executed?)
Python Programming,
2/e
29
Programming Languages

Programming language is a code for
writing the instructions the computer
will follow.


Programmers will often refer to their
program as source code.
Process of writing an algorithm in a
programming language often called coding.
Python Programming, 2/e
30
Programming Languages

High-level computer languages


Designed to be used and understood by
humans
Low-level language

Computer hardware can only understand a
very low level language known as machine
language (actually binary codes)
Python Programming, 2/e
31
Languages

Telling a robot to leave a room

In Machine languages


In Assembly languages


take a step, lift arm, grasp knob, turn knob...
LEAVE through DOOR
In High-level languages

"get outta here!"
Programming Languages



High-level language
c=a+b
High-level languages are portable - they
can be moved from one kind of CPU to
another without rewriting the code.
Examples -- FORTRAN, COBOL, Pascal,
Python, Ada, Modula-2, C++, Java
Python Programming, 2/e
33
Programming Languages


But high-level languages need to be
translated into machine language that
the computer can execute.
TWO ways of translation:
compilers and interpreters

Compilers convert an entire program
written in a high-level language into the
machine language of some computer. A
compiler does NOT run the code.
Python Programming, 2/e
34
Programming Languages



Interpreters simulate a computer that
understands a high-level language.
The source program is not translated
into machine language all at once.
An interpreter analyzes and executes
the source code instruction by
instruction, one at a time.
Python Programming, 2/e
35
Programming Languages

Compiling vs. Interpreting


Once program is compiled, it can be
executed over and over without the source
code or compiler. If it is interpreted, the
source code and interpreter are needed
each time the program runs
Compiled programs generally run faster
since the translation of the source code
happens only once.
Python Programming, 2/e
36
Programming Languages

Interpreted languages are part of a more
flexible programming environment since
they can be developed and run
interactively
Python Programming, 2/e
37
The Translation Process

Syntax - the rules governing the
formation of statements in the language




Spelling
Order of words, statements
Punctuation
Semantics – meaning of the statement

What does it DO? What action does the
computer do when the statement is
executed?
Tools for programming


Compilers and interpreters for highlevel languages
IDE (integrated development environment)




Translator (compiler or interpreter)
editor (creates text format files)
loader (get machine code into RAM so it
can be run)
debugger
The Magic of Python
When you start Python, you will see
something like:
Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
Python Programming, 2/e
40
The Magic of Python


The “>>>” is a Python prompt indicating that
Python is ready for us to give it a command.
These commands are called statements.
>>> print("Hello, world“)
Hello, world
>>> print(2+3)
5
>>> print("2+3=", 2+3)
2+3= 5
>>>
Python Programming, 2/e
41
The Magic of Python




When we exit Python, the functions we’ve defined
cease to exist!
However, the source code is saved on secondary
storage and can be accessed and ran many times
Programs are usually composed of functions,
modules, or scripts that are saved on disk so that
they can be used again and again.
A module file is a file created in text editing software
(saved as “plain text”) that contains function
definitions.
Python Programming, 2/e
42
The Magic of Python
# File: stars.py
# this is a sample program
# it prints out a string of stars on the screen
def main ():
stars = "“
num = eval(input("How many stars do you want? "))
for i in range(num):
stars = stars + "*"
print (stars)
main()
When we run the program, here’s the output:
>>>
How many stars do you want? 25
*************************
Python Programming, 2/e
>>>
43
The Magic of Python



We’ll use filename.py when we save our
work to indicate it’s a Python program.
In this code we’re defining a new
function called main.
The main() at the end tells Python to
run the code.
Python Programming, 2/e
44
Inside a Python Program
# File: stars.py
# A simple program

Lines that start with # are called
comments


Intended for human readers and
ignored by Python
Python skips text from # to end of line
Python Programming, 2/e
45
Inside a Python Program
def main():



Beginning of the definition of a function
called main
Since our program has only this one
module, it could have been written
without the main function.
The use of main is customary, however.
Python Programming, 2/e
46
Inside a Python Program
print (stars)

This line causes Python to print the
value of a variable.
Python Programming, 2/e
47
Inside a Python Program
num = eval(input(“How many stars do you
want? "))



num is an example of a variable
A variable is used to assign a name to a
value so that we can refer to it later.
The quoted information is displayed,
and the number typed in response is
stored in num.
Python Programming, 2/e
48
Inside a Python Program
for i in range(num):



For is a loop control structure
A loop tells Python to repeat the same
thing over and over.
In this example, the following code will
be repeated num times.
Python Programming, 2/e
49
Inside a Python Program
stars = stars + “*”




This line is the body of the loop.
The body of the loop is what gets repeated
each time through the loop.
The body of the loop is identified through
indentation.
The effect of the loop is the same as
repeating this line num times!
Python Programming, 2/e
50
Inside a Python Program
stars = stars + “*”


This is called an assignment statement
The part on the right-hand side (RHS) of the
“=“ is a mathematical expression.

* is used to indicate multiplication

In this case, it is a character in a string

Once the value on the RHS is computed, it is
stored back into (assigned) into stars
Python Programming, 2/e
51
Inside a Python Program
main()

This last line tells Python to execute the
code in the function main
Python Programming, 2/e
52
Case Study: Converting Miles
to Kilometers

Problem Your summer surveying job
requires you to study some maps that give
distances in kilometers and some that use
miles. You and your coworkers prefer to
deal in metric measurements. Write a
program that performs the necessary
conversion.
Case Study

Analysis The first step in solving this
problem is to determine what you are
asked to do. You must convert from one
system of measurement to another, but
are you supposed to convert from
kilometers to miles, or vice versa? The
problem states that you prefer to deal in
metric measurements, so you must convert
distance measurements in miles to
kilometers.
Data Requirements



Problem Input
miles
distance in miles
Problem Output
kms
the distance in kilometers
Relevant Formula
1 mile = 1.609 kilometers
Design an Algorithm that solves the
problem

Algorithm (Pseudocode)
1. Get the distance in miles.
2. Convert the distance to kilometers.
3. Display the distance in kilometers.

Algorithm Refinement
2.1 The distance in kilometers is 1.609
times the distance in miles

Desk check!
Implementation in Python
# converter.py
# converts miles to kilometers
def main ():
miles = eval(input("distance in miles? "))
kilometers = miles * 1.609
print("The equivalent distance in kilometers is",
kilometers)
main()
Python Programming, 2/e
57
Testing


Test with input data for which you can
easily determine the expected results
E.g.
10 miles should convert to 16.09
kilometers
Ethics






Responsibility comes with knowledge
Don’t do hacking!
Don’t do piracy!
Don’t do data theft
Protect data privacy
You have a responsibility to develop
programs without errors or at least let
the users know there are flaws
Python keywords used in Ch.1








print
def
#
eval, input
for, while, range
if
assignment =
+, -, /, *, **
Python Programming, 2/e
60
Download