Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Computer Science

Similar presentations


Presentation on theme: "Introduction to Computer Science"— Presentation transcript:

1 Introduction to Computer Science
Programming with Python

2 Loops & Iteration Chapter 5: Loop Idioms

3 Counting in a Loop The point of this is to keep track of the iterations To count how many times we execute a loop, we introduce a counter variable that starts at 0 and we add one to it each time through the loop

4 Summing in a Loop To add up a value we encounter in a loop, we introduce a sum variable that start at 0 and we add the value to the sum each time through the loop

5 Finding the Average in a Loop
An average just combines the counting and sum patterns and divides when the loop is done

6 Filtering in a Loop if statement is used in the loop to catch/filter the values we are looking for

7 Search Using a Boolean Variable
If we just want to search and know if a value was found, we use a variable that starts at False and is set to True as soon as we find what we are looking for

8 Search Using a Boolean Variable
If we just want to search and know if a value was found, we use a variable that starts at False and is set to True as soon as we find what we are looking for break

9 Finding Smallest Value with Negative Numbers
What do we do in this case? Will the following solution work? -1 is like a flag/indicator

10 Unknown Value - None smallest = None
None is a value that we can distinctly detect different (empty) than numbers

11 Finding the Smallest Value
We still have a variable that is the smallest so far. The first time through the loop smallest is None, so we take the first value to be the smallest

12 None/Null Values in Other Programming Languages
In Python, the null object is the singleton None The best way to check things for Noneness is to use the identity operator is Example, if smallest is None The Pythonic way to assign a variable with an unknown value or nothing is to use the keywork None In most programming languages such as Java, C#, etc, the None is null

13 The “is” and “is not” Operators
Python has an is operator that can be used in logical expressions Implies “is the same as” Similar to, but stronger than == is not also is a logical operator They are usually used for True, False, or None Do not use them to compare values. is is much stronger thing than comparing mathematical values


Download ppt "Introduction to Computer Science"

Similar presentations


Ads by Google