2 Programming
2 Programming
Introduction to Programming
What Is a Program?
Usually, one or more algorithms written in
a programming language that can be
translated to run on a real machine
Algorithm
Program
A real computer
The Program Development
Process (Data Flow)
Algorithm
Editor
Program in programming language
Compiler
A real computer
Input Output
The Program Development
Process (Control Flow)
Edit
Syntax errors
Compile
Run
Input Output
Runtime errors
Three kinds of errors
Syntax error : Some statement in the
program is not a legal statement in the
language.
Edit
Input
Computation
Output
The Big Plan
We want to get some experience of programming simple
algorithms in a real programming language. This gives us
an understanding of how software is written and allows us
to test our algorithms to see if they work.
In Python, identifiers
• Are made of letters, digits and underscores
• Must begin with a letter or an underscore
• Examples: temperature, myPayrate, score2
Keywords
A variable has
• A name – identifier
float
This type is for numbers with possible
fraction parts. Examples: 23.0, -14.561
Integer operators
The operations for integers are:
+ for addition
- for subtraction
* for multiplication
/ for integer division: The result of 14/5 is 2
% for remainder: The result of 14 % 5 is 4
• Integer Constants
• Integer Variables
• Integer Operators
• Parentheses
Python Assignment Statements
In Python, = is called the assignment operator
and an assignment statement has the form
<variable> = <expression>
Here
• <variable> would be replaced by an actual variable
• <expression> would be replaced by an expression
Python: age = 19
Python Assignment Statement
Syntax: <variable> = <expression>
• Note that variable is on left
Semantics:
Compute value of expression
Store this as new value of the variable
10 40 400
Payrate Hours Pay
Assignment Example
Before
X Y Z
3 5 12
Execute
Z=X*3+Z/Y
After
X Y Z
3 5 11
Python Session
Python Session
What about floats?
<variable> = input(<prompt>)
Here
• <prompt> would be replaced by a prompt for the user inside
quotation marks
• If there is no prompt, the parentheses are still needed
Semantics
• The prompt will be displayed
• User enters number
• Value entered is stored as the value of the variable
Print Statement
For output we use statements of the form
print <expression>
Semantics
• Value of expression is computed
• This value is displayed