[go: up one dir, main page]

0% found this document useful (0 votes)
8 views65 pages

Lec 02

Uploaded by

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

Lec 02

Uploaded by

wanguenhle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 65

Variables, Expressions and Flowcharts

Objectives
Constants
• Fixed values such as numbers, letters, and strings are called
“constants” - because their value does not change
• Numeric constants are as you expect
• String constants use single-quotes (')
or double-quotes (")
Variables
• A variable is a named place in the memory where a programmer can
store data and later retrieve the data using the variable “name”
• Programmers get to choose the names of the variables
• You can change the contents of a variable in a later statement
Naming Variables
• Must start with a letter or underscore _
• Must consist of letters and numbers and underscores
• Case Sensitive
Good: spam eggs spam23 _speed
Bad: 23spam #sign var.12
Different: ze Ze ZE
Reserved words
• You can not use reserved words as variable names / identifiers

and del for is raise


assert elif from lambda return
break else global not try
class except if or while
continue exec import pass yield
def finally in print
Sentences and lines
Assignment with expression Assignment statement
Constant

Variable

Operator

Reserved
word

Print statement
Assignment Statements
• We assign a value to a variable using the assignment statement (=)
• An assignment statement consists of an expression on the right hand
side and a variable to store the result

x = 3.9 * x * ( 1 - x )
• A variable is a memory location used to store a value (0.6).
• Right side is an expression. Once expression is evaluated, the result is
placed in (assigned to) x

x = 0.6
• A variable is a memory location used to store a value. The
value stored in a variable can be updated by replacing the
old value (0.6) with a new value (0.93).
• Right side is an expression. Once expression is evaluated,
the result is placed in (assigned to) the variable on the left
side (i.e. x).
Numeric
Expressions

• Because of the lack of


mathematical symbols on
computer keyboards - we use
“computer-speak” to express
the classic math operations
• Asterisk is multiplication
• Exponentiation (raise to a
power) looks different from in
math.
Numeric Expression
Order of Evaluation
• When we string operators together - Python must know which
one to do first
• This is called “operator precedence”
• Which operator “takes precedence” over the others

x = 1 + 2 * 3 - 4 / 5 ** 6
Operator Precedence Rules
• Highest precedence rule to lowest precedence rule
• Parenthesis are always respected
• Exponentiation (raise to a power)
• Multiplication, Division, and Remainder
• Addition and Subtraction
• Left to right
• Remember the rules top to bottom
• When writing code - use parenthesis
• When writing code - keep mathematical expressions simple enough
that they are easy to understand
• Break long series of mathematical operations up to make them more
clear
Parenthesis – Power – Multiplication – Addiction - Left to right

Exam Question: x = 1 + 2 * 3 - 4 / 5
What does “Type” Mean?
• In Python variables, literals, and constants have a “type”
• Python knows the difference between an integer number and a string
• For example “+” means “addition” if something is a number and
“concatenate” if something is a string
Type Conversion

• When you put an integer and


floating point in an expression
the integer is implicitly
converted to a float
• You can control this with the
built-in functions int() and
float()
String Conversions
• You can also use int() and float() to convert between strings and
integers
• You will get an error if the string does not contain numeric characters
User Input
• We can instruct Python to pause and read data from the user using
the input function
• The input function returns a string
Converting User Input
• If we want to read a number from the user, we must convert it from a
string to a number using a type conversion function
• Later we will deal with bad input data
Commenting in Python
• Anything after a # is ignored by Python
• Why comment?
• Describe what is going to happen in a sequence of code
• Document who wrote the code or other ancillary information
• Turn off a line of code - perhaps temporarily
Flowcharts
and Python
Syntax
1.4 Programming Tools
• Flowcharts
• Pseudocode
• Hierarchy Chart
• Direction of Numbered NYC Streets Algorithm
• Class Average Algorithm

23
Programming Tools
• Three tools are used to convert algorithms into computer programs:
• Flowchart - Graphically depicts the logical steps to carry out a task
and shows how the steps relate to each other.
• Pseudocode - Uses English-like phrases with some Visual Basic terms
to outline the program.

24
Problem solving example
• How many stamps do you use when mailing a letter?
• One rule of thumb is to use one stamp for every five sheets of paper
or fraction thereof.

25
Algorithm
1. Request the number of sheets of paper; call it Sheets. (input)
2. Divide Sheets by 5. (processing)
3. Round the quotient up to the next highest whole number; call it
Stamps. (processing)
4. Reply with the number Stamps. (output)

26
Flowcharts
• Graphically depict the logical steps to carry out a task and show how
the steps relate to each other.

27
Flowchart symbols

28
Flowchart symbols continued

29
Flowchart
example

30
Pseudocode
• Uses English-like phrases to outline the task.

31
Pseudocode example
Determine the proper number of stamps for a
letter
Read Sheets (input)
Set the number of stamps to Sheets / 5 (processing)
Round the number of stamps up to the next
whole number (processing)
Display the number of stamps (output)

32
Divide-and-conquer method
• Used in problem solving – take a large problem and break it into
smaller problems solving the small ones first
• Breaks a problem down into modules

33
Statement structures
• Sequence – follow instructions from one line to
the next without skipping over any lines
• Decision - if the answer to a question is “Yes”
then one group of instructions is executed. If the
answer is “No,” then another is executed
• Looping – a series of instructions are executed
over and over

34
Sequence
flow chart

35
Decision flow chart

36
Looping flow chart

37
Controlling a Repetition Structure
• The action performed by a repetition structure must eventually cause the loop to
terminate. Otherwise, an infinite loop is created.
• In this flowchart segment, x is never changed. Once the loop starts, it will never
end.
• QUESTION: How can this
flowchart be modified so
it is no longer an infinite YES
loop? x < y? Display x

38
Controlling a Repetition Structure
• ANSWER: By adding an action within the repetition that changes the value of x.

YES
x < y? Display x Add 1 to x

39
Connectors

•The “A” connector


indicates that the second START A

flowchart segment begins


where the first segment
ends.

END
A

40
Modules

START
•The position of the module
symbol indicates the point the Read Input.
module is executed.
•A separate flowchart can be Call calc_pay

constructed for the module. function.

Display results.

END

41
Combining Structures
• This flowchart segment
shows two decision
structures combined. NO YES
x > min?

Display “x is NO YES
outside the limits.”
x < max?

Display “x is Display “x is
outside the limits.” within limits.”

42
Review
• What do each of the following symbols represent?

(Answer on next slide)


43
Answer
• What do each of the following symbols represent?

Decision
Terminal

Input/Output
Operation Connector

Process Module

44
Review
• Name the four flowchart structures.

(Answer on next slide)


45
Answer
• Sequence
• Decision
• Repetition
• Case

46
Review
• What type of structure is this?

(Answer on next slide)


47
Answer
• Repetition

48
Review
• What type of structure is this?

(Answer on next slide)


49
Answer
• Sequence

50
Review
• What type of structure is this?

(Answer on next slide)


51
Answer
• Decision

52
53
54
55
Examples ???

56
Direction of Numbered NYC Streets
Algorithm
• Problem: Given a street number of a one-way street in New York City,
decide the direction of the street, either eastbound or westbound
• Discussion: in New York City even numbered streets are Eastbound,
odd numbered streets are Westbound

57
Flowchart

58
Pseudocode
Program: Determine the direction of a numbered NYC street
Get street
If street is even Then
Display Eastbound
Else
Display Westbound
End If

59
Class Average Algorithm
• Problem: Calculate and report the grade-point average for a class
• Discussion: The average grade equals the sum of all grades divided by
the number of students
Output: Average grade
Input: Student grades
Processing: Find the sum of the grades; count the number of students;
calculate average

60
Flowchart

61
Pseudocode
Program: Determine the average grade of a class
Initialize Counter and Sum to 0
Do While there are more data
Get the next Grade
Add the Grade to the Sum
Increment the Counter
Loop
Computer Average = Sum / Counter
Display Average

62
Tips and tricks of flowcharts
• Flowcharts are time-consuming to write and difficult to update
• For this reason, professional programmers are more likely to favor
pseudocode and hierarchy charts
• Because flowcharts so clearly illustrate the logical flow of
programming techniques, they are a valuable tool in the education of
programmers

63
Tips and tricks of pseudocode
• There are many styles of pseudocode
• Some programmers use an outline form
• Some use a form that looks almost like a programming language
• The pseudocode in the case studies of this text focus on the primary
tasks to be performed by the program and leaves many of the routine
details to be completed during the coding process

64
URL’s for free Flowcharting software
• www.smartdraw.com
• www.gliffy.com/uses/flowchart-software/
• www.breezetree.com/flowcharting-software/
Flowchart Software, FREE Flowchart Examples and Templates ...
• www.edrawsoft.com/flowchart.php

65

You might also like