• No results found

Python Programming: An Introduction to Computer Science

N/A
N/A
Protected

Academic year: 2021

Share "Python Programming: An Introduction to Computer Science"

Copied!
33
0
0

Loading.... (view fulltext now)

Full text

(1)

Python Programming:

An Introduction to

Computer Science

Chapter 7

(2)

Objectives

 To understand the programming pattern

simple decision and its implementation

using a Python if statement.

 To understand the programming pattern

two-way decision and its implementation

(3)

Objectives (cont.)

 To understand the programming pattern

multi-way decision and its

implementation using a Python

if-elif-else statement.

 To understand the idea of exception

handling and be able to write simple exception handling code that catches

(4)

Objectives (cont.)

 To understand the concept of Boolean

expressions and the bool data type

(requires Python 2.3 and newer)

 To be able to read, write, and implement

algorithms that employ decision

structures, including those that employ sequences of decisions and nested

(5)

Simple Decisions

 So far, we’ve viewed programs as

sequences of instructions that are followed one after the other.

 While this is a fundamental

programming concept, it is not sufficient in itself to solve every problem. We need to be able to alter the sequential flow of a program to suit a particular situation.

(6)

Simple Decisions

 Control structures allow us to alter this

sequential program flow.

 In this chapter, we’ll learn about decision

structures, which are statements that allow a program to execute different sequences of instructions for different cases, allowing the program to “choose”

(7)

Example:

Temperature Warnings

 Let’s return to our Celsius to Fahrenheit

temperature conversion program from Chapter 2.

# convert.py

# A program to convert Celsius temps to Fahrenheit # by: Susan Computewell

def main():

celsius = input("What is the Celsius temperature? ") fahrenheit = 9.0 / 5.0 * celsius + 32

(8)

Example:

Temperature Warnings

 Let’s say we want to modify that

program to print a warning when the weather is extreme.

 Any temperature over 90 degrees

Fahrenheit and lower than 30 degrees Fahrenheit will cause a hot and cold weather warning, respectively.

(9)

Example:

Temperature Warnings

 Input the temperature in degrees Celsius

(call it celsius)

 Calculate fahrenheit as 9/5 celsius + 32

 Output fahrenheit

 If fahrenheit > 90

print a heat warning

 If fahrenheit > 30

(10)

Example:

Temperature Warnings

 This new algorithm has two decisions at

the end. The indentation indicates that a step should be performed only if the

condition listed in the previous line is true.

(11)

Example:

(12)

Example:

Temperature Warnings

# convert2.py

# A program to convert Celsius temps to Fahrenheit. # This version issues heat and cold warnings.

def main():

celsius = input("What is the Celsius temperature? ") fahrenheit = 9.0 / 5.0 * celsius + 32

print "The temperature is", fahrenheit, "degrees fahrenheit." if fahrenheit >= 90:

print "It's really hot out there, be careful!" if fahrenheit <= 30:

(13)

Example:

Temperature Warnings

 The Python if statement is used to

implement the decision.

 if <condition>:

<body>

 The body is a sequence of one or more

statements indented under the if

(14)

Example:

Temperature Warnings

 The semantics of the if should be clear.

 First, the condition in the heading is evaluated.

 If the condition is true, the sequence of statements

in the body is executed, and then control passes to the next statement in the program.

 If the condition is false, the statements in the body

are skipped, and control passes to the next statement in the program.

(15)

Example:

(16)

Example:

Temperature Warnings

 The body of the if either executes or

not depending on the condition. In any case, control then passes to the next

statement after the if.

(17)

Forming Simple Conditions

 What does a condition look like?

 At this point, let’s use simple

comparisons.

 <expr> <relop> <expr>

(18)

Forming Simple Conditions

Greater than >

>

Greater than or equal to ≥

>=

Equal to =

==

Less than or equal to ≤ <= Less than < < Meaning Mathematics Python

(19)

Forming Simple Conditions

 Notice the use of == for equality. Since

Python uses = to indicate assignment, a

different symbol is required for the concept of equality.

 A common mistake is using = in

(20)

Forming Simple Conditions

 Conditions may compare either numbers

or strings.

 When comparing strings, the ordering is

lexigraphic, meaning that the strings are sorted based on the underlying ASCII

codes. Because of this, all upper-case letters come before lower-case letters.

(21)

Forming Simple Conditions

 Conditions are based on Boolean expressions,

named for the English mathematician George Boole.

 When a Boolean expression is evaluated, it

produces either a value of true (meaning the condition holds), or it produces false (it does not hold).

(22)

Forming Simple Conditions

 Boolean conditions are of type bool and the

Boolean values of true and false are

represented by the literals True and False. >>> 3 < 4 True >>> 3 * 4 < 3 + 4 False >>> "hello" == "hello" True

(23)

Two-Way Decisions

 Let’s look at the quadratic program as we left

it.

# quadratic.py

# A program that computes the real roots of a quadratic equation. # Illustrates use of the math library.

# Note: This program crashes if the equation has no real roots.

import math # Makes the math library available.

def main():

print "This program finds the real solutions to a quadratic" print

a, b, c = input("Please enter the coefficients (a, b, c): ")

discRoot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discRoot) / (2 * a)

(24)

Two-Way Decisions

 As the comment implies, when

b2-4ac < 0, the program tries to take the square

root of a negative number, and then crashes.

This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 1,1,2

Traceback (most recent call last):

File "C:\Documents and Settings\Terry\My Documents\Teaching\W04\CS 120\Textbook\code\chapter3\quadratic.py", line 21, in main()

File "C:\Documents and Settings\Terry\My Documents\Teaching\W04\CS 120\Textbook\code\chapter3\quadratic.py", line 14, in main

(25)

Two-Way Decisions

 We can check for this situation. Here’s our first attempt.

# quadratic2.py

# A program that computes the real roots of a quadratic equation. # Bad version using a simple if to avoid program crash

import math def main():

print "This program finds the real solutions to a quadratic\n" a, b, c = input("Please enter the coefficients (a, b, c): ") discrim = b * b - 4 * a * c

if discrim >= 0:

(26)

Two-Way Decisions

 We first calculate the discriminant

(b2-4ac) and then check to make sure it’s

nonnegative. If it is, the program

proceeds and we calculate the roots.

 Look carefully at the program. What’s

wrong with it? Hint: What happens when there are no real roots?

(27)

Two-Way Decisions

 This program finds the real solutions to a

quadratic

Please enter the coefficients (a, b, c): 1,1,1 >>>

 This is almost worse than the version

that crashes, because we don’t know what went wrong!

(28)

Two-Way Decisions

 We could add another if to the end:

if discrim < 0:

print "The equation has no real roots!"

 This works, but feels wrong. We have

two decisions, with mutually exclusive

outcomes (if discrim >= 0 then

(29)
(30)

Two-Way Decisions

 In Python, a two-way decision can be

implemented by attaching an else

clause onto an if clause.

 This is called an if-else statement:

if <condition>: <statements> else:

(31)

Two-Way Decisions

 When Python first encounters this structure, it

first evaluates the condition. If the condition is true, the statements under the if are

executed.

 If the condition is false, the statements under

the else are executed.

 In either case, the statements following the

(32)

Two-Way Decisions

# quadratic3.py

# A program that computes the real roots of a quadratic equation. # Illustrates use of a two-way decision

import math def main():

print "This program finds the real solutions to a quadratic\n" a, b, c = input("Please enter the coefficients (a, b, c): ") discrim = b * b - 4 * a * c

if discrim < 0:

print "\nThe equation has no real roots!" else:

(33)

Two-Way Decisions

>>>

This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 1,1,2

The equation has no real roots! >>>

This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 2, 5, 2

References

Related documents

 Every structure in programming language has a precise form, called its syntax.  Every structure in programming language has a precise meaning,

Example Program: Future Value.

 Whole numbers are represented using the integer ( int for short) data type..  These values can be positive or negative

 A string is stored as a sequence of binary numbers, one number per character..  It doesn’t matter what value is assigned as long as it’s

 The formal parameters balance and rate are assigned the values of the actual parameters amount and rate.  Even

 If the condition is false, the statements in the body are skipped, and control passes to the next statement in the

Boolean algebra and be able to analyze and write Boolean expressions involving Boolean operators.... For Loops: A

 In our simulation, the ability level of the players will be represented by the probability that the player wins the rally when he or she serves..  Example: Players with a