Python Programming: An Introduction to Computer Science
|
|
- Marian Craig
- 5 years ago
- Views:
Transcription
1 Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures Python Programming, 2/e 1
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 using a Python if-else statement. æ 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 standard Python run-time errors. 2
3 Objectives (cont.) æ To understand the concepts of definite and indefinite loops as they are realized in the Python for and while statements. æ To understand the programming patterns interactive loop and sentinel loop and their implementations using a Python while statement. æ To understand the programming pattern end-of-file loop and ways of implementing such loops in Python. æ To be able to design and implement solutions to problems involving loop patterns including nested loop structures. 3
4 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. 4
5 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 an appropriate course of action. 5
6 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 = eval(input("what is the Celsius temperature? ")) fahrenheit = 9/5 * celsius + 32 print("the temperature is", fahrenheit, "degrees Fahrenheit.") main() 6
7 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. 7
8 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 print a cold warning 8
9 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. 9
10 Example: Temperature Warnings 10
11 Example: Temperature Warnings # convert2.py # A program to convert Celsius temps to Fahrenheit. # This version issues heat and cold warnings. def main(): celsius = eval(input("what is the Celsius temperature? ")) fahrenheit = 9 / 5 * celsius + 32 print("the temperature is", fahrenheit, "degrees fahrenheit.") if fahrenheit >= 90: print("it's really hot out there, be careful!") if fahrenheit <= 30: print("brrrrr. Be sure to dress warmly") main() 11
12 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 heading. 12
13 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. 13
14 Example: Temperature Warnings 14
15 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. æ This is a one-way or simple decision. 15
16 Forming Simple Conditions æ What does a condition look like? æ At this point, let s use simple comparisons. æ <expr> <relop> <expr> æ <relop> is short for relational operator 16
17 Forming Simple Conditions Python Mathematics Meaning < < Less than <= Less than or equal to == = Equal to >= Greater than or equal to > > Greater than!= Not equal to 17
18 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 conditions! 18
19 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 Unicode. Because of this, all upper-case letters come before lower-case letters. ( Bbbb comes before aaaa ) 19
20 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). æ Some computer languages use 1 and 0 to represent true and false. 20
21 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 < False >>> "hello" == "hello" True >>> "Hello" < "hello" True 21
22 Two-Way Decisions æ Consider the quadratic program as we left it. # quadratic.py # A program that computes the real roots of a quadratic equation. # Note: This program crashes if the equation has no real roots. import math def main(): print("this program finds the real solutions to a quadratic") main() a, b, c = eval(input("\nplease 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) 22
23 Two-Way Decisions æ As per the comment, when b 2-4ac < 0, the program 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 -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 23
24 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 = eval(input("please enter the coefficients (a, b, c): ")) discrim = b * b - 4 * a * c if discrim >= 0: discroot = math.sqrt(discrim) root1 = (-b + discroot) / (2 * a) root2 = (-b - discroot) / (2 * a) print("\nthe solutions are:", root1, root2) 24
25 Two-Way Decisions æ We first calculate the discriminant (b 2-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? 25
26 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! 26
27 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 discrim < 0 must be false, and vice versa). 27
28 Two-Way Decisions 28
29 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: <statements> 29
30 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 ifelse are executed after either set of statements are executed. 30
31 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" main() a, b, c = eval(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: discroot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discroot) / (2 * a) root2 = (-b - discroot) / (2 * a) print ("\nthe solutions are:", root1, root2 ) 31
32 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 The solutions are:
33 Multi-Way Decisions æ The newest program is great, but it still has some quirks! This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 1,2,1 The solutions are:
34 Multi-Way Decisions æ While correct, this method might be confusing for some people. It looks like it has mistakenly printed the same number twice! æ Double roots occur when the discriminant is exactly 0, and then the roots are b/2a. æ It looks like we need a three-way decision! 34
35 Multi-Way Decisions æ Check the value of discrim when < 0: handle the case of no roots when = 0: handle the case of a double root when > 0: handle the case of two distinct roots æ We can do this with two if-else statements, one inside the other. æ Putting one compound statement inside of another is called nesting. 35
36 Multi-Way Decisions if discrim < 0: print("equation has no real roots") else: if discrim == 0: root = -b / (2 * a) print("there is a double root at", root) else: # Do stuff for two roots 36
37 Multi-Way Decisions 37
38 Multi-Way Decisions æ Imagine if we needed to make a five-way decision using nesting. The ifelse statements would be nested four levels deep! æ There is a construct in Python that achieves this, combining an else followed immediately by an if into a single elif. 38
39 Multi-Way Decisions æ if <condition1>: <case1 statements> elif <condition2>: <case2 statements> elif <condition3>: <case3 statements> else: <default statements> 39
40 Multi-Way Decisions æ This form sets of any number of mutually exclusive code blocks. æ Python evaluates each condition in turn looking for the first one that is true. If a true condition is found, the statements indented under that condition are executed, and control passes to the next statement after the entire if-elifelse. æ If none are true, the statements under else are performed. 40
41 Multi-Way Decisions æ The else is optional. If there is no else, it s possible no indented block would be executed. 41
42 Multi-Way Decisions # quadratic4.py # Illustrates use of a multi-way decision import math def main(): print("this program finds the real solutions to a quadratic\n") a, b, c = eval(input("please enter the coefficients (a, b, c): ")) discrim = b * b - 4 * a * c if discrim < 0: print("\nthe equation has no real roots!") elif discrim == 0: root = -b / (2 * a) print("\nthere is a double root at", root) else: discroot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discroot) / (2 * a) root2 = (-b - discroot) / (2 * a) print("\nthe solutions are:", root1, root2 ) 42
43 For Loops: A Quick Review æ The for statement allows us to iterate through a sequence of values. æ for <var> in <sequence>: <body> æ The loop index variable var takes on each successive value in the sequence, and the statements in the body of the loop are executed once for each value. 43
44 For Loops: A Quick Review æ Suppose we want to write a program that can compute the average of a series of numbers entered by the user. æ To make the program general, it should work with any size set of numbers. æ We don t need to keep track of each number entered, we only need know the running sum and how many numbers have been added. 44
45 For Loops: A Quick Review æ We ve run into some of these things before! A series of numbers could be handled by some sort of loop. If there are n numbers, the loop should execute n times. We need a running sum. This will use an accumulator. 45
46 For Loops: A Quick Review æ Input the count of the numbers, n æ Initialize sum to 0 æ Loop n times Input a number, x Add x to sum æ Output average as sum/n 46
47 For Loops: A Quick Review # average1.py # A program to average a set of numbers # Illustrates counted loop with accumulator def main(): n = eval(input("how many numbers do you have? ")) sum = 0.0 for i in range(n): x = eval(input("enter a number >> ")) sum = sum + x print("\nthe average of the numbers is", sum / n) æ Note that sum is initialized to 0.0 so that sum/n returns a float! 47
48 For Loops: A Quick Review How many numbers do you have? 5 Enter a number >> 32 Enter a number >> 45 Enter a number >> 34 Enter a number >> 76 Enter a number >> 45 The average of the numbers is
49 Indefinite Loops æ That last program got the job done, but you need to know ahead of time how many numbers you ll be dealing with. æ What we need is a way for the computer to take care of counting how many numbers there are. æ The for loop is a definite loop, meaning that the number of iterations is determined when the loop starts. 49
50 Indefinite Loops æ We can t use a definite loop unless we know the number of iterations ahead of time. We can t know how many iterations we need until all the numbers have been entered. æ We need another tool! æ The indefinite or conditional loop keeps iterating until certain conditions are met. 50
51 Indefinite Loops æ while <condition>: <body> æ condition is a Boolean expression, just like in if statements. The body is a sequence of one or more statements. æ Semantically, the body of the loop executes repeatedly as long as the condition remains true. When the condition is false, the loop terminates. 51
52 Indefinite Loops æ The condition is tested at the top of the loop. This is known as a pre-test loop. If the condition is initially false, the loop body will not execute at all. 52
53 Indefinite Loop æ Here s an example of a while loop that counts from 0 to 10: i = 0 while i <= 10: print(i) i = i + 1 æ The code has the same output as this for loop: for i in range(11): print(i) 53
54 Indefinite Loop æ The while loop requires us to manage the loop variable i by initializing it to 0 before the loop and incrementing it at the bottom of the body. æ In the for loop this is handled automatically. 54
55 Indefinite Loop æ The while statement is simple, but yet powerful and dangerous they are a common source of program errors. æ i = 0 while i <= 10: print(i) æ What happens with this code? 55
56 Indefinite Loop æ When Python gets to this loop, i is equal to 0, which is less than 10, so the body of the loop is executed, printing 0. Now control returns to the condition, and since i is still 0, the loop repeats, etc. æ This is an example of an infinite loop. 56
57 Indefinite Loop æ What should you do if you re caught in an infinite loop? First, try pressing control-c If that doesn t work, try control-alt-delete If that doesn t work, push the reset button! 57
58 Interactive Loops æ One good use of the indefinite loop is to write interactive loops. Interactive loops allow a user to repeat certain portions of a program on demand. æ Remember how we said we needed a way for the computer to keep track of how many numbers had been entered? Let s use another accumulator, called count. 58
59 Interactive Loops æ At each iteration of the loop, ask the user if there is more data to process. We need to preset it to yes to go through the loop the first time. æ set moredata to yes while moredata is yes get the next data item process the item ask user if there is moredata 59
60 Interactive Loops æ Combining the interactive loop pattern with accumulators for sum and count: æ initialize sum to 0.0 initialize count to 0 set moredata to yes while moredata is yes input a number, x add x to sum add 1 to count ask user if there is moredata output sum/count 60
61 Interactive Loops # average2.py # A program to average a set of numbers # Illustrates interactive loop with two accumulators def main(): moredata = "yes" sum = 0.0 count = 0 while moredata[0] == 'y': x = eval(input("enter a number >> ")) sum = sum + x count = count + 1 moredata = input("do you have more numbers (yes or no)? ") print("\nthe average of the numbers is", sum / count) æ Using string indexing (moredata[0]) allows us to accept y, yes, yeah to continue the loop 61
62 Interactive Loops Enter a number >> 32 Do you have more numbers (yes or no)? y Enter a number >> 45 Do you have more numbers (yes or no)? yes Enter a number >> 34 Do you have more numbers (yes or no)? yup Enter a number >> 76 Do you have more numbers (yes or no)? y Enter a number >> 45 Do you have more numbers (yes or no)? nah The average of the numbers is
63 Sentinel Loops æ A sentinel loop continues to process data until reaching a special value that signals the end. æ This special value is called the sentinel. æ The sentinel must be distinguishable from the data since it is not processed as part of the data. 63
64 Sentinel Loops æ get the first data item while item is not the sentinel process the item get the next data item æ The first item is retrieved before the loop starts. This is sometimes called the priming read, since it gets the process started. æ If the first item is the sentinel, the loop terminates and no data is processed. æ Otherwise, the item is processed and the next one is read. 64
65 Sentinel Loops æ In our averaging example, assume we are averaging test scores. æ We can assume that there will be no score below 0, so a negative number will be the sentinel. 65
66 Sentinel Loops # average3.py # A program to average a set of numbers # Illustrates sentinel loop using negative input as sentinel def main(): sum = 0.0 count = 0 x = eval(input("enter a number (negative to quit) >> ")) while x >= 0: sum = sum + x count = count + 1 x = eval(input("enter a number (negative to quit) >> ")) print("\nthe average of the numbers is", sum / count) 66
67 Sentinel Loops Enter a number (negative to quit) >> 32 Enter a number (negative to quit) >> 45 Enter a number (negative to quit) >> 34 Enter a number (negative to quit) >> 76 Enter a number (negative to quit) >> 45 Enter a number (negative to quit) >> -1 The average of the numbers is
68 Sentinel Loops æ This version provides the ease of use of the interactive loop without the hassle of typing y all the time. æ There s still a shortcoming using this method we can t average a set of positive and negative numbers. æ If we do this, our sentinel can no longer be a number. 68
69 Sentinel Loops æ We could input all the information as strings. æ Valid input would be converted into numeric form. Use a character-based sentinel. æ We could use the empty string ( )! 69
70 Sentinel Loops initialize sum to 0.0 initialize count to 0 input data item as a string, xstr while xstr is not empty convert xstr to a number, x add x to sum add 1 to count input next data item as a string, xstr Output sum / count 70
71 Sentinel Loops # average4.py # A program to average a set of numbers # Illustrates sentinel loop using empty string as sentinel def main(): sum = 0.0 count = 0 xstr = input("enter a number (<Enter> to quit) >> ") while xstr!= "": x = eval(xstr) sum = sum + x count = count + 1 xstr = input("enter a number (<Enter> to quit) >> ") print("\nthe average of the numbers is", sum / count) 71
72 Sentinel Loops Enter a number (<Enter> to quit) >> 34 Enter a number (<Enter> to quit) >> 23 Enter a number (<Enter> to quit) >> 0 Enter a number (<Enter> to quit) >> -25 Enter a number (<Enter> to quit) >> Enter a number (<Enter> to quit) >> 22.7 Enter a number (<Enter> to quit) >> The average of the numbers is
73 File Loops æ The biggest disadvantage of our program at this point is that they are interactive. æ What happens if you make a typo on number 43 out of 50? æ A better solution for large data sets is to read the data from a file. 73
74 File Loops # average5.py # Computes the average of numbers listed in a file. def main(): filename = input("what file are the numbers in? ") infile = open(filename,'r') sum = 0.0 count = 0 for line in infile.readlines(): sum = sum + eval(line) count = count + 1 print("\nthe average of the numbers is", sum / count) 74
75 File Loops æ Many languages don t have a mechanism for looping through a file like this. Rather, they use a sentinel! æ We could use readline in a loop to get the next line of the file. æ At the end of the file, readline returns an empty string, 75
76 File Loops æ line = infile.readline() while line!= "" #process line line = infile.readline() æ Does this code correctly handle the case where there s a blank line in the file? æ Yes. An empty line actually ends with the newline character, and readline includes the newline. \n!= 76
77 File Loops # average6.py # Computes the average of numbers listed in a file. def main(): filename = input("what file are the numbers in? ") infile = open(filename,'r') sum = 0.0 count = 0 line = infile.readline() while line!= "": sum = sum + eval(line) count = count + 1 line = infile.readline() print("\nthe average of the numbers is", sum / count) 77
78 Nested Loops æ In the last chapter we saw how we could nest if statements. We can also nest loops. æ Suppose we change our specification to allow any number of numbers on a line in the file (separated by commas), rather than one per line. 78
79 Nested Loops æ At the top level, we will use a file-processing loop that computes a running sum and count. sum = 0.0 count = 0 line = infile.readline() while line!= "": #update sum and count for values in line line = infile.readline() print("\nthe average of the numbers is", sum/count) 79
80 Nested Loops æ In the next level in we need to update the sum and count in the body of the loop. æ Since each line of the file contains one or more numbers separated by commas, we can split the string into substrings, each of which represents a number. æ Then we need to loop through the substrings, convert each to a number, and add it to sum. æ We also need to update count. 80
81 Nested Loops æ for xstr in line.split(","): sum = sum + eval(xstr) count = count + 1 æ Notice that this for statement uses line, which is also the loop control variable for the outer loop. 81
82 Nested Loops # average7.py # Computes the average of numbers listed in a file. # Works with multiple numbers on a line. import string def main(): filename = input("what file are the numbers in? ") infile = open(filename,'r') sum = 0.0 count = 0 line = infile.readline() while line!= "": for xstr in line.split(","): sum = sum + eval(xstr) count = count + 1 line = infile.readline() print("\nthe average of the numbers is", sum / count) 82
83 Nested Loops æ The loop that processes the numbers in each line is indented inside of the file processing loop. æ The outer while loop iterates once for each line of the file. æ For each iteration of the outer loop, the inner for loop iterates as many times as there are numbers on the line. æ When the inner loop finishes, the next line of the file is read, and this process begins again. 83
84 Nested Loops æ Designing nested loops Design the outer loop without worrying about what goes inside Design what goes inside, ignoring the outer loop. Put the pieces together, preserving the nesting. 84
Introduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 7 Part 1 The Department of Computer Science Objectives 2 To understand the programming pattern simple decision and its implementation
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 7 Part 1 Instructor: Long Ma The Department of Computer Science Objectives---Decision Structures 2 To understand the programming
More informationPython Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures Python Programming, 2/e 1 Objectives n To understand the programming pattern simple decision and its implementation
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 8 Part 1 The Department of Computer Science Chapter 8 Loop Structures and Booleans 2 Objectives To understand the concepts
More informationFile processing and decision structures
File processing and decision structures Michael Mandel Lecture 4 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture04final.ipynb
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 7 Part 2 The Department of Computer Science Quick review one-way or simple decision if : two-way decision
More informationLecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming
Lecture Loops && Booleans Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda (In-)definite loops (for/while) Patterns: interactive loop and sentinel loop Solve problems using (possibly
More informationLoop structures and booleans
Loop structures and booleans Michael Mandel Lecture 7 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture07final.ipynb
More informationPython Programming: An Introduction To Computer Science
Python Programming: An Introduction To Computer Science Chapter 8 Loop Structures and Booleans Python Programming, 3/e 1 Objectives To understand the concepts of definite and indefinite loops as they are
More information" # # if $ " %&% # ifelse $ " #&% # ifelif-else $ +bool ##%# # #.* $ ## # .# *#%$ % ## % .#*#%*
! " if " %&% ifelse!()!() " &% ifelif-else "*+ % + & "*- +bool (.%) "%.* *%!!%.* *%* 0* **!! 0.*%* %. *% % % % +*.* **% * 3 4! * convert.py A program to convert Celsius temps to Fahrenheit by: Susan Computewell
More informationPython Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures Python Programming, 2/e 1 Simple Decisions So far, we ve viewed programs as sequences of instructions that are followed
More informationIntroduction to Computer Programming for Non-Majors
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 :
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 7 Part 2 The Department of Computer Science Quick review one-way or simple decision if : two-way decision
More informationMulti-Way Decisions. The newest program is great, but it still has some quirks! This program finds the real solutions to a quadratic
Multi-Way Decisions The newest program is great, but it still has some quirks! This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 1,2,1 The solutions are: -1.0-1.0
More informationDecision Structures CSC1310. Python Programming, 2/e 1
Decision Structures CSC1310 Python Programming, 2/e 1 Simple Decisions Decision structures, which are statements that allow a program to execute different sequences of instructions for different cases,
More informationPython Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers Python Programming, 2/e 1 Objectives n To understand the concept of data types. n To be familiar with the basic
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 3 The Department of Computer Science Review of Chapter 2 Stages of creating a program: Analyze the problem Determine specifications
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 3 The Department of Computer Science Review of Chapter 2 Stages of creating a program: Analyze the problem Determine specifications
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 3 Instructor: Long Ma The Department of Computer Science Review of Chapter 2 Stages of creating a program: Analyze the problem
More informationCITS 1401 Problem Solving & Programming
CITS 1401 Problem Solving & Programming Tim French Lecture 03 Numeric Data Processing (These slides are based on John Zelle s powerpoint slides for lectures accompanied with the text book) Objectives of
More informationPython Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers Python Programming, 3/e 1 Objectives n To understand the concept of data types. n To be familiar with the basic
More informationLecture Numbers. Richard E Sarkis CSC 161: The Art of Programming
Lecture Numbers Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda To understand the concept of data types To be familiar with the basic numeric data types in Python To be able
More informationChapter 2 Writing Simple Programs
Chapter 2 Writing Simple Programs Charles Severance Textbook: Python Programming: An Introduction to Computer Science, John Zelle (www.si182.com) Software Development Process Figure out the problem - for
More informationPython Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 2 Python Programming, 2/e 1 Objectives n To be able to understand and write Python statements to output information to the screen, assign
More informationCITS 4406 Problem Solving & Programming
CITS 4406 Problem Solving & Programming Tim French Lecture 02 The Software Development Process (These slides are based on John Zelle s powerpoint slides for lectures accompanied with the text book) Objectives
More informationPython Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 2 Writing Simple Programs Python Programming, 3/e 1 Objectives n To know the steps in an orderly software development process. n To understand
More informationLecture Writing Programs. Richard E Sarkis CSC 161: The Art of Programming
Lecture Writing Programs Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda To be able to understand and write Python statements to output information to the screen To assign values
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2014 Chapter 2 The Department of Computer Science Chapter 2 Elements of Programs-Objectives To be able to understand and write Python
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 2 Instructor: Long Ma The Department of Computer Science Review Install and test python Basic concept of computers Test simple
More informationSI Networked Computing: Storage, Communication, and Processing, Winter 2009
University of Michigan Deep Blue deepblue.lib.umich.edu 2009-01 SI 502 - Networked Computing: Storage, Communication, and Processing, Winter 2009 Severance, Charles Severance, C. (2008, December 19). Networked
More informationCMSC201 Computer Science I for Majors
CMSC201 Computer Science I for Majors Lecture 06 Decision Structures Prof. Katherine Gibson Prof. Jeremy Dixon Based on concepts from: https://blog.udemy.com/python-if-else/ Last Class We Covered Just
More informationWriting Python Programs, Numerical Data Types
Writing Python Programs, Numerical Data Types Michael Mandel Lecture 2 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture02final.ipyn
More informationComp 151. Control structures.
Comp 151 Control structures. admin quiz this week believe it or not only 2 weeks from exam. one a week each week after that. idle debugger Debugger: program that will let you look at the program as it
More informationControl structure: Repetition - Part 2
Control structure: Repetition - Part 2 01204111 Computers and Programming Chalermsak Chatdokmaiprai Department of Computer Engineering Kasetsart University Cliparts are taken from http://openclipart.org
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 11 Part 1 Instructor: Long Ma The Department of Computer Science Chapter 11 Data Collections Objectives: To understand the
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 11 Part 1 The Department of Computer Science Objectives Chapter 11 Data Collections To understand the use of lists (arrays)
More informationLOOPS. Repetition using the while statement
1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while
More informationPython for Informatics
Python for Informatics Exploring Information Version 0.0.6 Charles Severance Chapter 3 Conditional execution 3.1 Boolean expressions A boolean expression is an expression that is either true or false.
More informationCS 115 Lecture 4. More Python; testing software. Neil Moore
CS 115 Lecture 4 More Python; testing software Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 8 September 2015 Syntax: Statements A statement
More informationComp 151. Control structures.
Comp 151 Control structures. admin For these slides read chapter 7 Yes out of order. Simple Decisions So far, we ve viewed programs as sequences of instructions that are followed one after the other. While
More informationCPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)
Name Definition Matching (8 Points) 1. (8 pts) Match the words with their definitions. Choose the best definition for each word. Relational Expression Iteration Counter Count-controlled loop Loop Flow
More informationReview Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts
Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Simple Data Types There are a number of data types that are considered primitive in that they contain only a single value. These data
More informationIntro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming
Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals
More informationCondition Controlled Loops. Introduction to Programming - Python
+ Condition Controlled Loops Introduction to Programming - Python + Repetition Structures n Programmers commonly find that they need to write code that performs the same task over and over again + Example:
More informationProgramming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.
Plan for the rest of the semester: Programming We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. We saw earlier that computers
More informationCS 105 Lab As a review of what we did last week a. What are two ways in which the Python shell is useful to us?
1 CS 105 Lab 3 The purpose of this lab is to practice the techniques of making choices and looping. Before you begin, please be sure that you understand the following concepts that we went over in class:
More informationText Input and Conditionals
Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()
More informationChapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationTest #2 October 8, 2015
CPSC 1040 Name: Test #2 October 8, 2015 Closed notes, closed laptop, calculators OK. Please use a pencil. 100 points, 5 point bonus. Maximum score 105. Weight of each section in parentheses. If you need
More information\n is used in a string to indicate the newline character. An expression produces data. The simplest expression
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationIf Statements, For Loops, Functions
Fundamentals of Programming If Statements, For Loops, Functions Table of Contents Hello World Types of Variables Integers and Floats String Boolean Relational Operators Lists Conditionals If and Else Statements
More informationC++ Programming: From Problem Analysis to Program Design, Third Edition
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 5: Control Structures II (Repetition) Why Is Repetition Needed? Repetition allows you to efficiently use variables Can input,
More informationCONDITION CONTROLLED LOOPS. Introduction to Programming - Python
CONDITION CONTROLLED LOOPS Introduction to Programming - Python Generating Random Numbers Generating a random integer Sometimes you need your program to generate information that isn t available when you
More informationConditional Expressions and Decision Statements
Conditional Expressions and Decision Statements June 1, 2015 Brian A. Malloy Slide 1 of 23 1. We have introduced 5 operators for addition, subtraction, multiplication, division, and exponentiation: +,
More informationTopics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop
Topics C H A P T E R 4 Repetition Structures Introduction to Repetition Structures The for Loop: a Count- Sentinels Nested Loops Introduction to Repetition Structures Often have to write code that performs
More informationCMSC 201 Fall 2016 Lab 09 Advanced Debugging
CMSC 201 Fall 2016 Lab 09 Advanced Debugging Assignment: Lab 09 Advanced Debugging Due Date: During discussion Value: 10 points Part 1: Introduction to Errors Throughout this semester, we have been working
More informationControl structure: Selections
Control structure: Selections 01204111 Computers and Programming Chalermsak Chatdokmaiprai Department of Computer Engineering Kasetsart University Cliparts are taken from http://openclipart.org Revised
More informationA453 Task 1: Analysis: Problem: Solution:
: Analysis: Problem: The problem I need to solve is that I need to design, code, and test a program that simulates a dice throw of a 4, 6, or 12 sided die and outputs the result before repeating the process
More informationLast Time. integer/float/string. import math math.sqrt() math.pi. Python Programming, 2/e 2
1 Last Time integer/float/string import math math.sqrt() math.pi Python Programming, 2/e 2 Extra Ques:on from Lab 2 Using loops and two print statements, have Python print out the following: * * * * *
More informationIntro. Speed V Growth
Intro Good code is two things. It's elegant, and it's fast. In other words, we got a need for speed. We want to find out what's fast, what's slow, and what we can optimize. First, we'll take a tour of
More informationCS 115 Lecture 8. Selection: the if statement. Neil Moore
CS 115 Lecture 8 Selection: the if statement Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 24 September 2015 Selection Sometime we want to execute
More informationControl and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators
CS 61A Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions 1 Control Control structures direct the flow of logic in a program. For example, conditionals (if-elif-else) allow a program
More informationDecision structures. A more complex decision structure is an if-else-statement: if <condition>: <body1> else: <body2>
Decision structures Read: Chapter 7, Sections 8.1-8.2 from Chapter 8 from textbook Decisions about what to do next in a program are based on logical conditions: these are conditions that evaluate to either
More information(Python) Chapter 3: Repetition
(Python) Chapter 3: Repetition 3.1 while loop Motivation Using our current set of tools, repeating a simple statement many times is tedious. The only item we can currently repeat easily is printing the
More informationCS112 Lecture: Repetition Statements
CS112 Lecture: Repetition Statements Objectives: Last revised 2/18/05 1. To explain the general form of the java while loop 2. To introduce and motivate the java do.. while loop 3. To explain the general
More informationMITOCW watch?v=0jljzrnhwoi
MITOCW watch?v=0jljzrnhwoi The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To
More informationSSEA Computer Science: Track A. Dr. Cynthia Lee Lecturer in Computer Science Stanford
SSEA Computer Science: Track A Dr. Cynthia Lee Lecturer in Computer Science Stanford Topics for today Java programming language: new tools Two new kinds of operators: RELATIONAL operators (>,
More informationREPETITION CONTROL STRUCTURE LOGO
CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of
More informationControl Structures 1 / 17
Control Structures 1 / 17 Structured Programming Any algorithm can be expressed by: Sequence - one statement after another Selection - conditional execution (not conditional jumping) Repetition - loops
More informationPrinciples of Computer Science I
Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120A - Fall 2004 Lecture Unit 7 Review Chapter 4 Boolean data type and operators (&&,,) Selection control flow structure if, if-else, nested
More informationName Section: M/W T/TH Number Definition Matching (6 Points)
Name Section: M/W T/TH Number Definition Matching (6 Points) 1. (6 pts) Match the words with their definitions. Choose the best definition for each word. Event Counter Iteration Counter Loop Flow of Control
More informationComputing with Numbers
Computing with Numbers Example output: Numeric Data Types Numeric Data Types Whole numbers are represented using the integer data type (int for short).values of type int can be positive or negative whole
More informationCS112 Lecture: Loops
CS112 Lecture: Loops Objectives: Last revised 3/11/08 1. To introduce some while loop patterns 2. To introduce and motivate the java do.. while loop 3. To review the general form of the java for loop.
More informationWorlframalpha.com Facebook Report
Worlframalpha.com Facebook Report For Tuesday: have read up through chapter 2 Next week will start chapter 3 New lab today: Simple Programs Integer division? o 1//3 o - 1//3 Range start at something other
More informationChapter 4: Making Decisions
Chapter 4: Making Decisions 4.1 Relational Operators Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than or equal to
More informationThere are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.
Introduction In the programs that we have dealt with so far, all statements inside the main function were executed in sequence as they appeared, one after the other. This type of sequencing is adequate
More informationChapter 4: Making Decisions
Chapter 4: Making Decisions CSE 142 - Computer Programming I 1 4.1 Relational Operators Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >=
More informationChapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14
Chapter 4: Making Decisions 4.1 Relational Operators Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than or equal to
More informationwhile for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)
Week 7: Advanced Loops while Loops in C++ (review) while (expression) may be a compound (a block: {s) Gaddis: 5.7-12 CS 1428 Fall 2015 Jill Seaman 1 for if expression is true, is executed, repeat equivalent
More informationIntro. Scheme Basics. scm> 5 5. scm>
Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if
More informationPDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs
PDS Lab Section 16 Autumn-2017 Tutorial 3 C Programming Constructs This flowchart shows how to find the roots of a Quadratic equation Ax 2 +Bx+C = 0 Start Input A,B,C x B 2 4AC False x If 0 True B x 2A
More informationSTATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration
STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the
More informationCS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore
CS 115 Data Types and Arithmetic; Testing Taken from notes by Dr. Neil Moore Statements A statement is the smallest unit of code that can be executed on its own. So far we ve seen simple statements: Assignment:
More informationChapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++
Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure
More informationName Section: M/W T/TH Number Definition Matching (8 Points)
Name Section: M/W T/TH Number Definition Matching (8 Points) 1. (8 pts) Match the words with their definitions. Choose the best definition for each word. Iteration Counter Event Counter Loop Abstract Step
More information5. Control Statements
5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements
More informationFlow Charts. Visual Depiction of Logic Flow
Flow Charts Visual Depiction of Logic Flow Flow Charts Describe a sequence of events using pictures Often associated with computer programs, but are quite common in other fields General way to depict a
More informationLecture 7 Tao Wang 1
Lecture 7 Tao Wang 1 Objectives In this chapter, you will learn about: Interactive loop break and continue do-while for loop Common programming errors Scientists, Third Edition 2 while Loops while statement
More informationPython Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 9 Simulation and Design Python Programming, 2/e 1 Objectives æ To understand the potential applications of simulation as a way to solve real-world
More informationChapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the
More informationSECOND EDITION SAMPLE CHAPTER. First edition by Daryl K. Harms Kenneth M. McDonald. Naomi R. Ceder MANNING
SECOND EDITION SECOND EDITION Covers Python 3 SAMPLE CHAPTER First edition by Daryl K. Harms Kenneth M. McDonald Naomi R. Ceder MANNING The Quick Python Book Second Edition by Naomi R. Ceder Chapter 8
More informationChapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );
Chapter 4 Loops Sections Pages Review Questions Programming Exercises 4.1 4.7, 4.9 4.10 104 117, 122 128 2 9, 11 13,15 16,18 19,21 2,4,6,8,10,12,14,18,20,24,26,28,30,38 Loops Loops are used to make a program
More informationControl Structures. Lecture 4 COP 3014 Fall September 18, 2017
Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls
More informationComputer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons
Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite
More informationLists, loops and decisions
Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence
More informationCMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi
CMPT 120 Control Structures in Python Summer 2012 Instructor: Hassan Khosravi The If statement The most common way to make decisions in Python is by using the if statement. The if statement allows you
More informationObjectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators
Objectives Chapter 4: Control Structures I (Selection) In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)
More informationCh.2: Loops and lists
Ch.2: Loops and lists Joakim Sundnes 1,2 Hans Petter Langtangen 1,2 Simula Research Laboratory 1 University of Oslo, Dept. of Informatics 2 Aug 29, 2018 Plan for 28 August Short quiz on topics from last
More informationINTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0
INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0 OCTOBER 2014 Python Selection and Conditionals 1 SELECTION AND CONDITIONALS WHAT YOU MIGHT KNOW ALREADY You will probably be familiar
More informationPython Evaluation Rules
Python Evaluation Rules UW CSE 160 https://courses.cs.washington.edu/courses/cse160/15sp/ Michael Ernst and Isaac Reynolds mernst@cs.washington.edu April 1, 2015 Contents 1 Introduction 2 1.1 The Structure
More information