Python Programming: An Introduction To Computer Science

Save this PDF as:

Size: px
Start display at page:

Transcription

1 Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e 1

2 Objectives æ To understand the concept of Boolean expressions and the bool data type. æ To be able to read, write, and implement algorithms that employ decision structures, including those that employ sequences of decisions and nested decision structures. æ To understand the basic ideas of Boolean algebra and be able to analyze and write Boolean expressions involving Boolean operators. 2

3 Computing with Booleans æ if and while both use Boolean expressions. æ Boolean expressions evaluate to True or False. æ So far we ve used Boolean expressions to compare two values, e.g. (while x >= 0) 3

4 Boolean Operators æ Sometimes our simple expressions do not seem expressive enough. æ Suppose you need to determine whether two points are in the same position their x coordinates are equal and their y coordinates are equal. 4

5 Boolean Operators æ if p1.getx() == p2.getx(): if p1.gety() == p2.gety(): # points are the same else: # points are different else: # points are different æ Clearly, this is an awkward way to evaluate multiple Boolean expressions! æ Let s check out the three Boolean operators and, or, and not. 5

6 Boolean Operators æ The Boolean operators and and or are used to combine two Boolean expressions and produce a Boolean result. æ <expr> and <expr> æ <expr> or <expr> 6

7 Boolean Operators æ The and of two expressions is true exactly when both of the expressions are true. æ We can represent this in a truth table. P Q P and Q T T T T F F F T F F F F 7

8 Boolean Expressions æ In the truth table, P and Q represent smaller Boolean expressions. æ Since each expression has two possible values, there are four possible combinations of values. æ The last column gives the value of P and Q. 8

9 Boolean Expressions æ The or of two expressions is true when either expression is true. P Q P or Q T T T T F T F T T F F F 9

10 Boolean Expressions æ The only time or is false is when both expressions are false. æ Also, note that or is true when both expressions are true. This isn t how we normally use or in language. 10

11 Boolean Operators æ The not operator computes the opposite of a Boolean expression. æ not is a unary operator, meaning it operates on a single expression. P T F not P F T 11

12 Boolean Operators æ We can put these operators together to make arbitrarily complex Boolean expressions. æ The interpretation of the expressions relies on the precedence rules for the operators. 12

13 Boolean Operators æ Consider a or not b and c æ How should this be evaluated? æ The order of precedence, from high to low, is not, and, or. æ This statement is equivalent to (a or ((not b) and c)) æ Since most people don t memorize the the Boolean precedence rules, use parentheses to prevent confusion. 13

14 Boolean Operators æ To test for the co-location of two points, we could use an and. æ if p1.getx() == p2.getx() and p2.gety() == p1.gety(): # points are the same else: # points are different æ The entire condition will be true only when both of the simpler conditions are true. 14

15 Boolean Operators æ Say you re writing a racquetball simulation. The game is over as soon as either player has scored 15 points. æ How can you represent that in a Boolean expression? æ scorea == 15 or scoreb == 15 æ When either of the conditions becomes true, the entire expression is true. If neither condition is true, the expression is false. 15

16 Boolean Operators æ We want to construct a loop that continues as long as the game is not over. æ You can do this by taking the negation of the game-over condition as your loop condition! æ while not(scorea == 15 or scoreb == 15): #continue playing 16

17 Boolean Operators æ Some racquetball players also use a shutout condition to end the game, where if one player has scored 7 points and the other person hasn t scored yet, the game is over. æ while not(scorea == 15 or scoreb == 15 or \ (scorea == 7 and scoreb == 0) or (scoreb == 7 and scorea == 0): #continue playing 17

18 Boolean Operators æ Let s look at volleyball scoring. To win, a volleyball team needs to win by at least two points. æ In volleyball, a team wins at 15 points æ If the score is 15 14, play continues, just as it does for æ (a >= 15 and a - b >= 2) or (b >= 15 and b - a >= 2) æ (a >= 15 or b >= 15) and abs(a - b) >= 2 18

19 Boolean Algebra æ The ability to formulate, manipulate, and reason with Boolean expressions is an important skill. æ Boolean expressions obey certain algebraic laws called Boolean logic or Boolean algebra. 19

20 Boolean Algebra Algebra a * 0 = 0 a * 1 = a a + 0 = a Boolean algebra a and false == false a and true == a a or false == a æ and has properties similar to multiplication æ or has properties similar to addition æ 0 and 1 correspond to false and true, respectively. 20

21 Boolean Algebra æ Anything ored with true is true: a or true == true æ Both and and or distribute: a or (b and c) == (a or b) and (a or c) a and (b or c) == (a and b) or (a and c) æ Double negatives cancel out: not(not a) == a æ DeMorgan s laws: not(a or b) == (not a) and (not b) not(a and b) == (not a) or (not b) 21

22 Boolean Algebra æ We can use these rules to simplify our Boolean expressions. æ while not(scorea == 15 or scoreb == 15): #continue playing æ This is saying something like While it is not the case that player A has 15 or player B has 15, continue playing. æ Applying DeMorgan s law: while (not scorea == 15) and (not scoreb == 15): #continue playing 22

23 Boolean Algebra æ This becomes: while scorea!= 15 and scoreb!= 15 # continue playing æ Isn t this easier to understand? While player A has not reached 15 and player B has not reached 15, continue playing. 23

24 Boolean Algebra æ Sometimes it s easier to figure out when a loop should stop, rather than when the loop should continue. æ In this case, write the loop termination condition and put a not in front of it. After a couple applications of DeMorgan s law you are ready to go with a simpler but equivalent expression. 24

25 Exception Handling æ 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. 25

26 Exception Handling æ In the quadratic example, we checked the data before calling sqrt. Sometimes functions will check for errors and return a special value to indicate the operation was unsuccessful. æ E.g., a different square root operation might return a 1 to indicate an error (since square roots are never negative, we know this value will be unique). 26

27 Exception Handling æ discrt = othersqrt(b*b - 4*a*c) if discrt < 0: print("no real roots. ) else:... æ Sometimes programs get so many checks for special cases that the algorithm becomes hard to follow. æ Programming language designers have come up with a mechanism to handle exception handling to solve this design problem. 27

28 Exception Handling æ The programmer can write code that catches and deals with errors that arise while the program is running, i.e., Do these steps, and if any problem crops up, handle it this way. æ This approach obviates the need to do explicit checking at each step in the algorithm. 28

29 Exception Handling # 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") 29

30 Exception Handling æ 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. 30

31 Exception Handling æ 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: 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 31

32 Exception Handling æ 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. 32

33 Exception Handling æ 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. 33

34 Exception Handling # quadratic6.py 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 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!") main() 34

35 Exception Handling æ 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. 35

36 Exception Handling æ 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. 36

37 Study in Design: Max of Three æ 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. 37

38 Study in Design: Max of Three 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) 38

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

40 Strategy 1: Compare Each to All æ 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. 40

41 Strategy 1: Compare Each to All æ 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. Always pay attention to borderline values!! 41

42 Strategy 1: Compare Each to All 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. 42

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

44 Strategy 1: Compare Each to All æ 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. æ Yuck! 44

45 Strategy 2: Decision Tree æ 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 conidition is true, we need to see which is larger, x1 or x3. 45

46 Strategy 2: Decision Tree 46

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

48 Strategy 2: Decision Tree æ 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 if-elses nested three levels deep with eight assignment statements. 48

49 Strategy 3: Sequential Processing æ 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. 49

50 Strategy 3: Sequential Processing 50

51 Strategy 3: Sequential Processing æ This idea can easily be translated into Python. max = x1 if x2 > max: max = x2 if x3 > max: max = x3 51

52 Strategy 3: Sequential Programming æ 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. 52

53 Strategy 3: Sequential Programming # 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) 53

54 Strategy 4: Use Python æ 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)) 54

55 Some Lessons æ There s usually more than one way to solve a problem. Don t rush to code the first idea that pops out of your head. 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. 55

56 Some Lessons æ 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. 56

57 Some Lessons æ Generality is good. Consideration of a more general problem can lead to a better solution for a special case. If the max of n program is just as easy to write as the max of three, write the more general program because it s more likely to be useful in other situations. 57

58 Some Lessons æ 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. 58

59 Example: Conditional Program Execution æ There are several ways of running Python programs. Some modules are designed to be run directly. These are referred to as programs or scripts. Others are made to be imported and used by other programs. These are referred to as libraries. Sometimes we want to create a hybrid that can be used both as a stand-alone program and as a library. 59

60 Example: Conditional Program Execution æ When we want to start a program once it s loaded, we include the line main() at the bottom of the code. æ Since Python evaluates the lines of the program during the import process, our current programs also run when they are imported into an interactive Python session or into another Python program. 60

61 Example: Conditional Program Execution æ Generally, when we import a module, we don t want it to execute! æ In a program that can be either run stand-alone or loaded as a library, the call to main at the bottom should be made conditional, e.g. if <condition>: main() 61

62 Example: Conditional Program Execution æ Whenever a module is imported, Python creates a special variable in the module called name to be the name of the imported module. æ Example: >>> import math >>> math. name 'math' 62

63 Example: Conditional Program Execution æ When imported, the name variable inside the math module is assigned the string math. æ When Python code is run directly and not imported, the value of name is main. E.g.: >>> name ' main ' 63

64 Example: Conditional Program Execution æ To recap: 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! 64

65 Post-Test Loop æ Say we want to write a program that is supposed to get a nonnegative number from the user. æ If the user types an incorrect input, the program asks for another value. æ This process continues until a valid value has been entered. æ This process is input validation. 65

66 Post-Test Loop æ repeat get a number from the user until number is >= 0 66

67 Post-Test Loop æ When the condition test comes after the body of the loop it s called a posttest loop. æ A post-test loop always executes the body of the code at least once. æ Python doesn t have a built-in statement to do this, but we can do it with a slightly modified while loop. 67

68 Post-Test Loop æ We seed the loop condition so we re guaranteed to execute the loop once. æ number = -1 while number < 0: number = eval(input("enter a positive number: ")) æ By setting number to 1, we force the loop body to execute at least once. 68

69 Post-Test Loop æ Some programmers prefer to simulate a post-test loop by using the Python break statement. æ Executing break causes Python to immediately exit the enclosing loop. æ break is sometimes used to exit what looks like an infinite loop. 69

70 Post-Test Loop æ The same algorithm implemented with a break: while True: number = eval(input("enter a positive number: ")) if x >= 0: break # Exit loop if number is valid æ A while loop continues as long as the expression evaluates to true. Since True always evaluates to true, it looks like an infinite loop! 70

71 Post-Test Loop æ When the value of x is nonnegative, the break statement executes, which terminates the loop. æ If the body of an if is only one line long, you can place it right after the :! æ Wouldn t it be nice if the program gave a warning when the input was invalid? 71

72 Post-Test Loop æ In the while loop version, this is awkward: number = -1 while number < 0: number = eval(input("enter a positive number: ")) if number < 0: print("the number you entered was not positive") æ We re doing the validity check in two places! 72

73 Post-Test Loop æ Adding the warning to the break version only adds an else statement: while True: number = eval(input("enter a positive number: ")) if x >= 0: break # Exit loop if number is valid else: print("the number you entered was not positive.") 73

74 Loop and a Half æ Stylistically, some programmers prefer the following approach: while True: number = eval(input("enter a positive number: ")) if x >= 0: break # Loop exit print("the number you entered was not positive") æ Here the loop exit is in the middle of the loop body. This is what we mean by a loop and a half. 74

75 Loop and a Half æ The loop and a half is an elegant way to avoid the priming read in a sentinel loop. æ while True: get next data item if the item is the sentinel: break process the item æ This method is faithful to the idea of the sentinel loop, the sentinel value is not processed! 75

76 Loop and a Half 76

77 Loop and a Half æ To use or not use break. That is the question! æ The use of break is mostly a matter of style and taste. æ Avoid using break often within loops, because the logic of a loop is hard to follow when there are multiple exits. 77

78 Boolean Expressions as Decisions æ Boolean expressions can be used as control structures themselves. æ Suppose you re writing a program that keeps going as long as the user enters a response that starts with y (like our interactive loop). æ One way you could do it: while response[0] == "y" or response[0] == "Y": 78

79 Boolean Expressions as Decisions æ Be careful! You can t take shortcuts: while response[0] == "y" or "Y": æ Why doesn t this work? æ Python has a bool type that internally uses 1 and 0 to represent True and False, respectively. æ The Python condition operators, like ==, always evaluate to a value of type bool. 79

80 Boolean Expressions as Decisions æ However, Python will let you evaluate any built-in data type as a Boolean. For numbers (int, float, and long ints), zero is considered False, anything else is considered True. 80

81 Boolean Expressions as Decisions >>> bool(0) False >>> bool(1) True >>> bool(32) True >>> bool("hello") True >>> bool("") False >>> bool([1,2,3]) True >>> bool([]) False 81

82 Boolean Expressions as Decisions æ An empty sequence is interpreted as False while any non-empty sequence is taken to mean True. æ The Boolean operators have operational definitions that make them useful for other purposes. 82

83 Boolean Expressions as Decisions Operator Operational definition x and y If x is false, return x. Otherwise, return y. x or y If x is true, return x. Otherwise, return y. not x If x is false, return True. Otherwise, return False. 83

84 Boolean Expressions as Decisions æ Consider x and y. In order for this to be true, both x and y must be true. æ As soon as one of them is found to be false, we know the expression as a whole is false and we don t need to finish evaluating the expression. æ So, if x is false, Python should return a false result, namely x. 84

85 Boolean Expressions as Decisions æ If x is true, then whether the expression as a whole is true or false depends on y. æ By returning y, if y is true, then true is returned. If y is false, then false is returned. 85

86 Boolean Expressions as Decisions æ These definitions show that Python s Booleans are short-circuit operators, meaning that a true or false is returned as soon as the result is known. æ In an and where the first expression is false and in an or, where the first expression is true, Python will not evaluate the second expression. 86

87 Boolean Expressions as Decisions æ response[0] == "y" or "Y æ The Boolean operator is combining two operations. æ Here s an equivalent expression: (response[0] == "y") or ("Y") æ By the operational description of or, this expression returns either True, if response[0] equals y, or Y, both of which are interpreted by Python as true. 87

88 Boolean Expressions as Decisions æ Sometimes we write programs that prompt for information but offer a default value obtained by simply pressing <Enter> æ Since the string used by ans can be treated as a Boolean, the code can be further simplified. 88

89 Boolean Expressions as Decisions æ ans = input("what flavor fo you want [vanilla]: ") if ans: flavor = ans else: flavor = "vanilla" æ If the user just hits <Enter>, ans will be an empty string, which Python interprets as false. 89

90 Boolean Expressions as Decisions æ We can code this even more succinctly! ans = input("what flavor fo you want [vanilla]: ") flavor = ans or "vanilla æ Remember, any non-empty answer is interpreted as True. æ This exercise could be boiled down into one line! flavor = input("what flavor do you want [vanilla]: ) or "vanilla" 90

91 Boolean Expressions as Decisions æ Again, if you understand this method, feel free to utilize it. Just make sure that if your code is tricky, that it s well documented! 91

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures Python Programming, 1/e 1 Objectives To understand the programming pattern simple decision and its implementation using

Python Loops and String Manipulation

WEEK TWO Python Loops and String Manipulation Last week, we showed you some basic Python programming and gave you some intriguing problems to solve. But it is hard to do anything really exciting until

Introduction to Python

WEEK ONE Introduction to Python Python is such a simple language to learn that we can throw away the manual and start with an example. Traditionally, the first program to write in any programming language

for while ' while ' for * for <var> in <sequence>: <body> \$ %%" 0 *0

# & for while while # * # & *, /01* for * 2 for in : ,var 0 2, /01* *** 0 *0 *& 4 00 *0* * /01* 4 6, 4 * /01* Input the count of the numbers, n Initialize sum to 0 Loop n times Input

Exercise 4 Learning Python language fundamentals

Exercise 4 Learning Python language fundamentals Work with numbers Python can be used as a powerful calculator. Practicing math calculations in Python will help you not only perform these tasks, but also

Writing Simple Programs

Chapter 2 Writing Simple Programs Objectives To know the steps in an orderly software development process. To understand programs following the Input, Process, Output (IPO) pattern and be able to modify

A Quick Algebra Review

1. Simplifying Epressions. Solving Equations 3. Problem Solving 4. Inequalities 5. Absolute Values 6. Linear Equations 7. Systems of Equations 8. Laws of Eponents 9. Quadratics 10. Rationals 11. Radicals

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Chapter 6 Defining Functions Python Programming, 2/e 1 Objectives To understand why programmers divide programs up into sets of cooperating functions.

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1

QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For

Racket Style Guide Fall 2016

CS17 Integrated Introduction to Computer Science Hughes Racket Style Guide Fall 2016 Contents 1 Introduction 1 2 Naming 1 3 Formatting 1 4 Equality 4 5 Conditionals 4 5.1 Prefer Cond to If......................................

Introduction to Python

Caltech/LEAD Summer 2012 Computer Science Lecture 2: July 10, 2012 Introduction to Python The Python shell Outline Python as a calculator Arithmetic expressions Operator precedence Variables and assignment

Calculator. Introduction. Requirements. Design. The calculator control system. F. Wagner August 2009

F. Wagner August 2009 Calculator Introduction This case study is an introduction to making a specification with StateWORKS Studio that will be executed by an RTDB based application. The calculator known

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.

Visual Logic Instructions and Assignments

Visual Logic Instructions and Assignments Visual Logic can be installed from the CD that accompanies our textbook. It is a nifty tool for creating program flowcharts, but that is only half of the story.

CSC 221: Computer Programming I. Fall 2011

CSC 221: Computer Programming I Fall 2011 Python control statements operator precedence importing modules random, math conditional execution: if, if-else, if-elif-else counter-driven repetition: for conditional

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Introduction Welcome to our Python sessions. University of Hull Department of Computer Science Wrestling with Python Week 01 Playing with Python Vsn. 1.0 Rob Miles 2013 Please follow the instructions carefully.

Welcome to Math 19500 Video Lessons. Stanley Ocken. Department of Mathematics The City College of New York Fall 2013

Welcome to Math 19500 Video Lessons Prof. Department of Mathematics The City College of New York Fall 2013 An important feature of the following Beamer slide presentations is that you, the reader, move

Exercise 1: Python Language Basics

Exercise 1: Python Language Basics In this exercise we will cover the basic principles of the Python language. All languages have a standard set of functionality including the ability to comment code,

Math Review. for the Quantitative Reasoning Measure of the GRE revised General Test

Math Review for the Quantitative Reasoning Measure of the GRE revised General Test www.ets.org Overview This Math Review will familiarize you with the mathematical skills and concepts that are important

Reading Assignment. Main Program in C. K.N. King Chapter 2. K.N. King Chapter 3. K.N. King Chapter 4. K.N. King Chapter 7. Our first C program

Reading Assignment Main Program in C In C the main program is a function called main The body of the function is enclosed in left ( ) and right ( ) curly braces. K.N. King Chapter 2 K.N. King Chapter 3

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

VISUAL GUIDE to RX Scripting for Roulette Xtreme - System Designer 2.0 UX Software - 2009 TABLE OF CONTENTS INTRODUCTION... ii What is this book about?... iii How to use this book... iii Time to start...

Chapter 5. Selection 5-1

Chapter 5 Selection 5-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow

Subnetting on Exams: Another look at solving the math

Subnetting on Exams: Another look at solving the math A Guide for IT professionals preparing for any timed exams dealing with subnetting such as Cisco's CCNA and CompTIA's Network+. By: Robert H. Williams

Operation Stack [bottom top] Instantiate [ ] Push 1 [ 1 ] Push 2 [ 1, 2 ] Push 3 [ 1, 2, 3 ] Pop [ 1, 2 ] Push 4 [ 1, 2, 4 ] Pop [ 1, 2 ]

Debugging Ask a random sample of students enrolled in a computer science course what their favorite aspect of programming is, and very few will respond with debugging. Debugging programs in computer science

If A is divided by B the result is 2/3. If B is divided by C the result is 4/7. What is the result if A is divided by C?

Problem 3 If A is divided by B the result is 2/3. If B is divided by C the result is 4/7. What is the result if A is divided by C? Suggested Questions to ask students about Problem 3 The key to this question

Object Oriented Software Design

Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

Factoring Polynomials and Solving Quadratic Equations

Factoring Polynomials and Solving Quadratic Equations Math Tutorial Lab Special Topic Factoring Factoring Binomials Remember that a binomial is just a polynomial with two terms. Some examples include 2x+3

SOLVING QUADRATIC EQUATIONS - COMPARE THE FACTORING ac METHOD AND THE NEW DIAGONAL SUM METHOD By Nghi H. Nguyen

SOLVING QUADRATIC EQUATIONS - COMPARE THE FACTORING ac METHOD AND THE NEW DIAGONAL SUM METHOD By Nghi H. Nguyen A. GENERALITIES. When a given quadratic equation can be factored, there are 2 best methods

Selection Statements

Chapter 5 Selection Statements 1 Statements So far, we ve used return statements and expression ess statements. e ts. Most of C s remaining statements fall into three categories: Selection statements:

CS 2112 Spring 2014. 0 Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

CS 2112 Spring 2014 Assignment 3 Data Structures and Web Filtering Due: March 4, 2014 11:59 PM Implementing spam blacklists and web filters requires matching candidate domain names and URLs very rapidly

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero THEN the Average is Sum divided by Count Conditions

The design recipe. Programs as communication. Some goals for software design. Readings: HtDP, sections 1-5

The design recipe Readings: HtDP, sections 1-5 (ordering of topics is different in lectures, different examples will be used) Survival and Style Guides CS 135 Winter 2016 02: The design recipe 1 Programs

Object Oriented Software Design

Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

AppendixA1A1. Java Language Coding Guidelines. A1.1 Introduction

AppendixA1A1 Java Language Coding Guidelines A1.1 Introduction This coding style guide is a simplified version of one that has been used with good success both in industrial practice and for college courses.

Repetition and Loops. Additional Python constructs that allow us to effect the (1) order and (2) number of times that program statements are executed.

New Topic Repetition and Loops Additional Python constructs that allow us to effect the (1) order and (2) number of times that program statements are executed. These constructs are the 1. while loop and

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June 2014. Dr.-Ing.

Computers An Introduction to Programming with Python CCHSG Visit June 2014 Dr.-Ing. Norbert Völker Many computing devices are embedded Can you think of computers/ computing devices you may have in your

Selection: if Statement

: if Statement The simplest selection structure in C++ is the if statement. Syntactically: 1 if The Boolean expression must be enclosed in parentheses, and

Conditionals: (Coding with Cards)

10 LESSON NAME: Conditionals: (Coding with Cards) Lesson time: 45 60 Minutes : Prep time: 2 Minutes Main Goal: This lesson will introduce conditionals, especially as they pertain to loops and if statements.

Common Syntax and Semantic Errors

C H A P T E R 2 Common Syntax and Semantic Errors 2.1 CHAPTER OBJECTIVES To understand the fundamental characteristics of syntax and semantic errors To be able to identify specific common syntax and semantic

Copyrighted Material. Chapter 1 DEGREE OF A CURVE

Chapter 1 DEGREE OF A CURVE Road Map The idea of degree is a fundamental concept, which will take us several chapters to explore in depth. We begin by explaining what an algebraic curve is, and offer two

SECTION 0.6: POLYNOMIAL, RATIONAL, AND ALGEBRAIC EXPRESSIONS

(Section 0.6: Polynomial, Rational, and Algebraic Expressions) 0.6.1 SECTION 0.6: POLYNOMIAL, RATIONAL, AND ALGEBRAIC EXPRESSIONS LEARNING OBJECTIVES Be able to identify polynomial, rational, and algebraic

Welcome to Introduction to programming in Python

Welcome to Introduction to programming in Python Suffolk One, Ipswich, 4:30 to 6:00 Tuesday Jan 14, Jan 21, Jan 28, Feb 11 Welcome Fire exits Toilets Refreshments 1 Learning objectives of the course An

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

COMP209 Object Oriented Programming Designing Classes 2 Mark Hall Programming by Contract (adapted from slides by Mark Utting) Preconditions Postconditions Class invariants Programming by Contract An agreement

if and if-else: Part 1

if and if-else: Part 1 Objectives Write if statements (including blocks) Write if-else statements (including blocks) Write nested if-else statements We will now talk about writing statements that make

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control

Problem Solving Basics and Computer Programming

Problem Solving Basics and Computer Programming A programming language independent companion to Roberge/Bauer/Smith, "Engaged Learning for Programming in C++: A Laboratory Course", Jones and Bartlett Publishers,

Python Evaluation Rules

Python Evaluation Rules UW CSE 160 http://tinyurl.com/dataprogramming Michael Ernst and Isaac Reynolds mernst@cs.washington.edu August 2, 2016 Contents 1 Introduction 2 1.1 The Structure of a Python Program................................

1 Using a SQL Filter in Outlook 2002/2003 Views. 2 Defining the Problem The Task at Hand

1 Using a SQL Filter in Outlook 2002/2003 Views Those of you who have used Outlook for a while may have discovered the power of Outlook Views and use these on every folder to group, sort and filter your

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

Decision Logic: if, if else, switch, Boolean conditions and variables

CS 1044 roject 3 Fall 2009 Decision Logic: if, if else, switch, Boolean conditions and variables This programming assignment uses many of the ideas presented in sections 3 through 5 of the Dale/Weems text

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

Roots and Powers. Written by: Bette Kreuz Edited by: Science Learning Center Staff

Roots and Powers Written by: Bette Kreuz Edited by: Science Learning Center Staff The objectives for this module are to: 1. Raise exponential numbers to a power. 2. Extract the root of an exponential number.

WHAT ARE MATHEMATICAL PROOFS AND WHY THEY ARE IMPORTANT?

WHAT ARE MATHEMATICAL PROOFS AND WHY THEY ARE IMPORTANT? introduction Many students seem to have trouble with the notion of a mathematical proof. People that come to a course like Math 216, who certainly

COMP 110 Prasun Dewan 1

COMP 110 Prasun Dewan 1 12. Conditionals Real-life algorithms seldom do the same thing each time they are executed. For instance, our plan for studying this chapter may be to read it in the park, if it

Math 25 Activity 6: Factoring Advanced

Instructor! Math 25 Activity 6: Factoring Advanced Last week we looked at greatest common factors and the basics of factoring out the GCF. In this second activity, we will discuss factoring more difficult

Equations and Inequalities

Rational Equations Overview of Objectives, students should be able to: 1. Solve rational equations with variables in the denominators.. Recognize identities, conditional equations, and inconsistent equations.

CHAPTER 2. Logic. 1. Logic Definitions. Notation: Variables are used to represent propositions. The most common variables used are p, q, and r.

CHAPTER 2 Logic 1. Logic Definitions 1.1. Propositions. Definition 1.1.1. A proposition is a declarative sentence that is either true (denoted either T or 1) or false (denoted either F or 0). Notation:

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Chapter 1 Computers and Programs 1 Objectives To understand the respective roles of hardware and software in a computing system. To learn what computer

Beating Roulette? An analysis with probability and statistics.

The Mathematician s Wastebasket Volume 1, Issue 4 Stephen Devereaux April 28, 2013 Beating Roulette? An analysis with probability and statistics. Every time I watch the film 21, I feel like I ve made the

PGR Computing Programming Skills

PGR Computing Programming Skills Dr. I. Hawke 2008 1 Introduction The purpose of computing is to do something faster, more efficiently and more reliably than you could as a human do it. One obvious point

MBA Jump Start Program

MBA Jump Start Program Module 2: Mathematics Thomas Gilbert Mathematics Module Online Appendix: Basic Mathematical Concepts 2 1 The Number Spectrum Generally we depict numbers increasing from left to right

2. Methods of Proof Types of Proofs. Suppose we wish to prove an implication p q. Here are some strategies we have available to try.

2. METHODS OF PROOF 69 2. Methods of Proof 2.1. Types of Proofs. Suppose we wish to prove an implication p q. Here are some strategies we have available to try. Trivial Proof: If we know q is true then

Iteration CHAPTER 6. Topic Summary

CHAPTER 6 Iteration TOPIC OUTLINE 6.1 while Loops 6.2 for Loops 6.3 Nested Loops 6.4 Off-by-1 Errors 6.5 Random Numbers and Simulations 6.6 Loop Invariants (AB only) Topic Summary 6.1 while Loops Many

December 4, 2013 MATH 171 BASIC LINEAR ALGEBRA B. KITCHENS

December 4, 2013 MATH 171 BASIC LINEAR ALGEBRA B KITCHENS The equation 1 Lines in two-dimensional space (1) 2x y = 3 describes a line in two-dimensional space The coefficients of x and y in the equation

Chapter 8 Selection 8-1

Chapter 8 Selection 8-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow

An Innocent Investigation

An Innocent Investigation D. Joyce, Clark University January 2006 The beginning. Have you ever wondered why every number is either even or odd? I don t mean to ask if you ever wondered whether every number

A First Book of C++ Chapter 2 Data Types, Declarations, and Displays

A First Book of C++ Chapter 2 Data Types, Declarations, and Displays Objectives In this chapter, you will learn about: Data Types Arithmetic Operators Variables and Declarations Common Programming Errors

Python Basics. S.R. Doty. August 27, 2008. 1 Preliminaries 4 1.1 What is Python?... 4 1.2 Installation and documentation... 4

Python Basics S.R. Doty August 27, 2008 Contents 1 Preliminaries 4 1.1 What is Python?..................................... 4 1.2 Installation and documentation............................. 4 2 Getting

We now explore a third method of proof: proof by contradiction.

CHAPTER 6 Proof by Contradiction We now explore a third method of proof: proof by contradiction. This method is not limited to proving just conditional statements it can be used to prove any kind of statement

Appendix: Tutorial Introduction to MATLAB

Resampling Stats in MATLAB 1 This document is an excerpt from Resampling Stats in MATLAB Daniel T. Kaplan Copyright (c) 1999 by Daniel T. Kaplan, All Rights Reserved This document differs from the published

CHAPTER 7 GENERAL PROOF SYSTEMS

CHAPTER 7 GENERAL PROOF SYSTEMS 1 Introduction Proof systems are built to prove statements. They can be thought as an inference machine with special statements, called provable statements, or sometimes

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending

Flowcharting, pseudocoding, and process design

Systems Analysis Pseudocoding & Flowcharting 1 Flowcharting, pseudocoding, and process design The purpose of flowcharts is to represent graphically the logical decisions and progression of steps in the

Algebra Practice Problems for Precalculus and Calculus

Algebra Practice Problems for Precalculus and Calculus Solve the following equations for the unknown x: 1. 5 = 7x 16 2. 2x 3 = 5 x 3. 4. 1 2 (x 3) + x = 17 + 3(4 x) 5 x = 2 x 3 Multiply the indicated polynomials

6. Control Structures

- 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,

How to Study Mathematics Written by Paul Dawkins

How to Study Mathematics Written by Paul Dawkins Before I get into the tips for how to study math let me first say that everyone studies differently and there is no one right way to study for a math class.

11 Ideals. 11.1 Revisiting Z

11 Ideals The presentation here is somewhat different than the text. In particular, the sections do not match up. We have seen issues with the failure of unique factorization already, e.g., Z[ 5] = O Q(

VBScript: Condition Statement

C h a p t e r 4 VBScript: Condition Statement In this chapter, you will learn how to use the following VBScript functions to World Class standards: 1. Writing Math Equations in VBScripts 2. Beginning a

LEARNING TO PROGRAM WITH PYTHON. Richard L. Halterman

LEARNING TO PROGRAM WITH PYTHON Richard L. Halterman Copyright 2011 Richard L. Halterman. All rights reserved. i Contents 1 The Context of Software Development 1 1.1 Software............................................

River Dell Regional School District. Computer Programming with Python Curriculum

River Dell Regional School District Computer Programming with Python Curriculum 2015 Mr. Patrick Fletcher Superintendent River Dell Regional Schools Ms. Lorraine Brooks Principal River Dell High School

Thomas Jefferson High School for Science and Technology Program of Studies Accelerated Foundations of Computer Science as of April 2013

Thomas Jefferson High School for Science and Technology Program of Studies Accelerated Foundations of Computer Science as of April 2013 Unit of Study / Accelerated Foundations of Computer Science is offered

CS 111 Classes I 1. Software Organization View to this point:

CS 111 Classes I 1 Software Organization View to this point: Data Objects and primitive types Primitive types operators (+, /,,*, %). int, float, double, char, boolean Memory location holds the data Objects

Computing Cubic Fields in Quasi-Linear Time

Computing Cubic Fields in Quasi-Linear Time K. Belabas Département de mathématiques (A2X) Université Bordeaux I 351, cours de la Libération, 33405 Talence (France) belabas@math.u-bordeaux.fr Cubic fields

Computer Programming I

Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,

Chapter 2: Problem Solving Using C++

Chapter 2: Problem Solving Using C++ 1 Objectives In this chapter, you will learn about: Modular programs Programming style Data types Arithmetic operations Variables and declaration statements Common

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

High-Level Programming Languages Nell Dale & John Lewis (adaptation by Michael Goldwasser) Low-Level Languages What are disadvantages of low-level languages? (e.g., machine code or assembly code) Programming

Computer Science for San Francisco Youth

Python for Beginners Python for Beginners Lesson 0. A Short Intro Lesson 1. My First Python Program Lesson 2. Input from user Lesson 3. Variables Lesson 4. If Statements How If Statements Work Structure

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

PL/SQL Overview PL/SQL is Procedural Language extension to SQL. It is loosely based on Ada (a variant of Pascal developed for the US Dept of Defense). PL/SQL was first released in ١٩٩٢ as an optional extension

Mathematics for Computer Science/Software Engineering. Notes for the course MSM1F3 Dr. R. A. Wilson

Mathematics for Computer Science/Software Engineering Notes for the course MSM1F3 Dr. R. A. Wilson October 1996 Chapter 1 Logic Lecture no. 1. We introduce the concept of a proposition, which is a statement

Polynomials and Factoring. Unit Lesson Plan

Polynomials and Factoring Unit Lesson Plan By: David Harris University of North Carolina Chapel Hill Math 410 Dr. Thomas, M D. 2 Abstract This paper will discuss, and give, lesson plans for all the topics

CHAPTER 18 Programming Your App to Make Decisions: Conditional Blocks

CHAPTER 18 Programming Your App to Make Decisions: Conditional Blocks Figure 18-1. Computers, even small ones like the phone in your pocket, are good at performing millions of operations in a single second.

Interactive Applications (CLI) and Math

Interactive Applications (CLI) and Math Interactive Applications Command Line Interfaces The Math Class Example: Solving Quadratic Equations Example: Factoring the Solution Reading for this class: L&L,

UNDERSTANDING ALGEBRA JAMES BRENNAN Copyright 00, All Rights Reserved CONTENTS CHAPTER 1: THE NUMBERS OF ARITHMETIC 1 THE REAL NUMBER SYSTEM 1 ADDITION AND SUBTRACTION OF REAL NUMBERS 8 MULTIPLICATION

Factoring Polynomials

Factoring Polynomials Hoste, Miller, Murieka September 12, 2011 1 Factoring In the previous section, we discussed how to determine the product of two or more terms. Consider, for instance, the equations