Introduction to Computer Programming for Non-Majors

Similar documents
Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Python Programming: An Introduction to Computer Science

Multi-Way Decisions. The newest program is great, but it still has some quirks! This program finds the real solutions to a quadratic

Introduction to Computer Programming for Non-Majors

" # # if $ " %&% # ifelse $ " #&% # ifelif-else $ +bool ##%# # #.* $ ## # .# *#%$ % ## % .#*#%*

Introduction to Computer Programming for Non-Majors

Decision Structures CSC1310. Python Programming, 2/e 1

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

CITS 1401 Problem Solving & Programming

Lecture Numbers. Richard E Sarkis CSC 161: The Art of Programming

Introduction to Computer Programming for Non-Majors

File processing and decision structures

Python Programming: An Introduction to Computer Science

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming

CMSC201 Computer Science I for Majors

Decision structures. A more complex decision structure is an if-else-statement: if <condition>: <body1> else: <body2>

Writing Python Programs, Numerical Data Types

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

Introduction to: Computers & Programming: Exception Handling

Errors. And How to Handle Them

Last Time. integer/float/string. import math math.sqrt() math.pi. Python Programming, 2/e 2

Introduction to Computer Programming for Non-Majors

Python for Non-programmers

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

Introduction to Computer Programming for Non-Majors

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Class extension and. Exception handling. Genome 559

Test #2 October 8, 2015

1 Lecture 6: Conditionals and Exceptions

Python for Informatics

Python Programming: An Introduction to Computer Science

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

CIS192 Python Programming

CIS192 Python Programming

Python Programming: An Introduction to Computer Science

Lecture Writing Programs. Richard E Sarkis CSC 161: The Art of Programming

CITS 4406 Problem Solving & Programming

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

Class extension and. Exception handling. Genome 559

CIS192 Python Programming

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Exception Handling. Genome 559

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

Introduction to python

Chapter 9: Dealing with Errors

Introduction to Computational Models Using Python

Subtraction Understand Subtraction on a Number Line Using a number line let s demonstrate the subtraction process using the problem 7 5.

Python for C programmers

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Introduction to Python

CSI33 Data Structures

Ch.2: Loops and lists

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016

A453 Task 1: Analysis: Problem: Solution:

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

Introduction to Python Code Quality

Python Programming: An Introduction to Computer Science

Programming to Python

>>> * *(25**0.16) *10*(25**0.16)

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Cosmology with python: Beginner to Advanced in one week. Tiago Batalha de Castro

CS 11 python track: lecture 3. n Today: Useful coding idioms

Variables, expressions and statements

Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer. October 6th, Universität des Saarlandes. Introduction to Python

Text Input and Conditionals

ENGR 102 Engineering Lab I - Computation

Exceptions CS GMU

Control Structures in Java if-else and switch

Introduction to Computer Programming for Non-Majors

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Conditional Execution

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

Python I. Some material adapted from Upenn cmpe391 slides and other sources

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0

Chapter 5 : Informatics practices. Conditional & Looping Constructs. Class XI ( As per CBSE Board)

Control Structures in Java if-else and switch

CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi

Introduction to Computer Programming for Non-Majors

Control Structures 1 / 17

Getting Started with Python

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

Repetition CSC 121 Fall 2014 Howard Rosenthal

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

MEIN 50010: Python Flow Control

Modular Arithmetic. is just the set of remainders we can get when we divide integers by n

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Did you ever think that a four hundred year-old spider may be why we study linear relationships today?

Decision Structures Zelle - Chapter 7

Transcription:

Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 7 Part 2 Instructor: Long Ma The Department of Computer Science

Quick review one-way or simple decision if <condition>: <body> two-way decision This is called an if-else statement: if <condition>: <statements> else: <statements>

Quick review Multi-Way Decisions if <condition1>: <case1 statements> elif <condition2>: <case2 statements> elif <condition3>: <case3 statements> else: <default statements>

Forming Simple Conditions 4 Python Mathematics Meaning < < Less than <= Less than or equal to == = Equal to >= Greater than or equal to > > Greater than!= Not equal to

Example: Conditional Program Execution 5 If a module is imported, the code in the module will see a variable called name whose value is the name of the module. When a file is run directly, the code will see the value main. We can change the final lines of our programs to: if name == ' main ': main() Virtually every Python module ends this way! 10/12/16-5- 2014 http://cs.gsu.edu/~mhan7

Example: Conditional Program Execution 6 #Test.py Class Test: def f(): print hello, world If name == main : Test().f() >>> Python Test.py >>> hello world >>>import Test >>> >>>Test. name >>> Test 10/12/16-6- 2014 http://cs.gsu.edu/~mhan7

Exception Handling 7 In the quadratic program we used decision structures to avoid taking the square root of a negative number, thus avoiding a run-time error. This is true for many programs: decision structures are used to protect against rare but possible errors. Drawback: Sometimes programs get so many checks for special cases that the algorithm becomes hard to follow.

Exception Handling 8 Programming language designers have come up with a mechanism to handle exception handling to solve this design problem. Python Standard Exception: https://www.tutorialspoint.com/python/standard_exce ptions.htm

What is Exception? An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error. When a Python script raises an exception, it must handle the exception immediately otherwise it terminates and quits. 10/12/16-9- 2014 http://cs.gsu.edu/~mhan7

Exception Handling 10 The programmer can write code that catches and deals with errors that arise while the program is running This approach obviates the need to do explicit checking at each step in the algorithm.

Handling an Exception If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible. 10/12/16-11- 2014 http://cs.gsu.edu/~mhan7

Exception Handling 12 The try statement has the following form: try: <body> except <ErrorType>: <handler> When Python encounters a try statement, it attempts to execute the statements inside the body. If there is no error, control passes to the next statement after the try except.

Syntax try: You do your operations here;... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block.... else: If there is no exception then execute this block. 10/12/16-13- 2014 http://cs.gsu.edu/~mhan7

Exception Handling 14 # quadratic5.py # A program that computes the real roots of a quadratic equation. # Illustrates exception handling to avoid crash on bad inputs import math def main(): print("this program finds the real solutions to a quadratic\n") try: a, b, c = eval(input("please enter the coefficients (a, b, c): ")) discroot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discroot) / (2 * a) root2 = (-b - discroot) / (2 * a) print("\nthe solutions are:", root1, root2) except ValueError: print("\nno real roots")

Traceback (most recent call last): File "C:\Documents and Settings\Terry\My Documents\Teaching\W04\CS120\Textbook\code\chapter3 \quadratic.py", line 21, in -toplevelmain() File "C:\Documents and Settings\Terry\My Documents\Teaching\W04\CS 120\Textbook\code\chapter3\quadratic.py", line 14, in main discroot = math.sqrt(b * b - 4 * a * c) ValueError: math domain error Exception Handling 15 If an error occurs while executing the body, Python looks for an except clause with a matching error type. If one is found, the handler code is executed. The original program generated this error with a negative discriminant:

10/12/16-16- 2014 http://cs.gsu.edu/~mhan7

Exception Handling 17 The last line, ValueError: math domain error, indicates the specific type of error. Here s the new code in action: This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 1, 1, 1 No real roots Instead of crashing, the exception handler prints a message indicating that there are no real roots.

Exception Handling 18 The try except can be used to catch any kind of error and provide for a graceful exit. In the case of the quadratic program, other possible errors include: not entering the right number of parameters ( unpack tuple of wrong size ) entering an identifier instead of a number (NameError) entering an invalid Python expression (TypeError). A single try statement can have multiple except clauses.

Exception Handling 19 # quadratic6.py import math def main(): print("this program finds the real solutions to a quadratic\n") main() try: a, b, c = eval(input("please enter the coefficients (a, b, c): ")) discroot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discroot) / (2 * a) root2 = (-b - discroot) / (2 * a) print("\nthe solutions are:", root1, root2 ) except ValueError as excobj: if str(excobj) == "math domain error": print("no Real Roots") else: print("you didn't give me the right number of coefficients.") except NameError: print("\nyou didn't enter three numbers.") except TypeError: print("\nyour inputs were not all numbers.") except SyntaxError: print("\nyour input was not in the correct form. Missing comma?") except: print("\nsomething went wrong, sorry!")

Exception Handling 20 The multiple excepts act like elifs. If an error occurs, Python will try each except looking for one that matches the type of error. The bare except at the bottom acts like an else and catches any errors without a specific match. If there was no bare except at the end and none of the except clauses match, the program would still crash and report an error.

Exception Handling 21 Exceptions themselves are a type of object. If you follow the error type with an identifier in an except clause, Python will assign that identifier the actual exception object.

Example >>> try:... print a+6... except NameError:... Pass... >>> >>> error = NameError >>> try:... print a+6... except error:... Pass... >>> 10/12/16-22- 2014 http://cs.gsu.edu/~mhan7

Study in Design: Max of Three 23 Now that we have decision structures, we can solve more complicated programming problems. The negative is that writing these programs becomes harder! Suppose we need an algorithm to find the largest of three numbers.

Study in Design: Max of Three 24 def main(): x1, x2, x3 = eval(input("please enter three values: ")) # missing code sets max to the value of the largest print("the largest value is", max)

Strategy 1: Compare Each to All 25 This looks like a three-way decision, where we need to execute one of the following: case 1: max = x1 case 2: max = x2 case 3: max = x3 All we need to do now is preface each one of these with the right condition!

Strategy 1: Compare Each to All 26 Let s look at the case where x1 is the largest. if x1 >= x2 >= x3: max = x1 Is this syntactically correct? Many languages would not allow this compound condition Python does allow it, though. It s equivalent to x1 x2 x3.

Strategy 1: Compare Each to All 27 Whenever you write a decision, there are two crucial questions: When the condition is true, is executing the body of the decision the right action to take? x1 is at least as large as x2 and x3, so assigning max to x1 is OK. Secondly, ask the converse of the first question, namely, are we certain that this condition is true in all cases where x1 is the max? Suppose the values are 5, 2, and 4. Clearly, x1 is the largest, but does x1 x2 x3 hold? We don t really care about the relative ordering of x2 and x3, so we can make two separate tests: x1 >= x2 and x1 >= x3.

Strategy 1: Compare Each to All 28 We can separate these conditions with and if x1 >= x2 and x1 >= x3: max = x1 elif x2 >= x1 and x2 >= x3: max = x2 else: max = x3 We re comparing each possible value against all the others to determine which one is largest.

Strategy 1: Compare Each to All 29 What would happen if we were trying to find the max of five values? We would need four Boolean expressions, each consisting of four conditions anded together. No!!!

Strategy 2: Decision Tree 30 We can avoid the redundant tests of the previous algorithm using a decision tree approach. Suppose we start with x1 >= x2. This knocks either x1 or x2 out of contention to be the max. If the condition is true, we need to see which is larger, x1 or x3.

31 Strategy 2: Decision Tree

Strategy 2: Decision Tree 32 if x1 >= x2: if x1 >= x3: max = x1 else: max = x3 else: if x2 >= x3: max = x2 else max = x3

Strategy 2: Decision Tree 33 This approach makes exactly two comparisons, regardless of the ordering of the original three variables. However, this approach is more complicated than the first. To find the max of four values you d need ifelses nested three levels deep with eight assignment statements.

Strategy 3: Sequential Processing 34 How would you solve the problem? You could probably look at three numbers and just know which is the largest. But what if you were given a list of a hundred numbers? One strategy is to scan through the list looking for a big number. When one is found, mark it, and continue looking. If you find a larger value, mark it, erase the previous mark, and continue looking.

Strategy 3: Sequential Processing 35

Strategy 3: Sequential Processing 36 This idea can easily be translated into Python. max = x1 if x2 > max: max = x2 if x3 > max: max = x3 This process is repetitive and lends itself to using a loop. We prompt the user for a number, we compare it to our current max, if it is larger, we update the max value, repeat.

Strategy 3: Sequential Programming 37 # maxn.py # Finds the maximum of a series of numbers def main(): n = eval(input("how many numbers are there? ")) # Set max to be the first value max = eval(input("enter a number >> ")) # Now compare the n-1 successive values for i in range(n-1): x = eval(input("enter a number >> ")) if x > max: max = x print("the largest value is", max)

Strategy 4: Use Python 38 Python has a built-in function called max that returns the largest of its parameters. def main(): x1, x2, x3 = eval(input("please enter three values: ")) print("the largest value is", max(x1, x2, x3))

Some Lessons 39 There s usually more than one way to solve a problem. Think about the design and ask if there s a better way to approach the problem. Your first task is to find a correct algorithm. After that, strive for clarity, simplicity, efficiency, scalability, and elegance.

Some Lessons 40 Be the computer One of the best ways to formulate an algorithm is to ask yourself how you would solve the problem. This straightforward approach is often simple, clear, and efficient enough.

Some Lessons 41 Don t reinvent the wheel. If the problem you re trying to solve is one that lots of other people have encountered, find out if there s already a solution for it! As you learn to program, designing programs from scratch is a great experience! Truly expert programmers know when to borrow.

Questions Thank You!