Monday 10/23¶
Reminders¶
- Readiness Quiz for PA 1 is posted.
- PA1 Part A is due 10/24, TOMORROW!
- PA1 Part B is due 10/31
- Quiz this week is on while loops and modules.
While Loop Patterns and break
¶
A common pattern for while loops is to process input until some condition is met. For example, imagine we need to add up numbers until the user enters an empty line:
Option 1:¶
total = 0
user_entered = input("Enter a number: ")
while user_entered != "":
num = int(user_entered)
total += num
user_entered = input("Enter a number: ")
Pros: Loop condition reveals the purpose of the loop.
Cons: We hate the code repetition.
Option 2:¶
total = 0
while True:
user_entered = input("Enter a number: ")
if user_entered == "":
break
total += int(user_entered)
Pros: Code repetition is gone.
Cons: Loop condition is meaningless. We need to dig through the body of the loop to understand the flow of control.
Warning
break
statements should be used sparingly and with
caution. They can make it more difficult for the reader to follow
the control flow in your loop.
Option 3:¶
total = 0
user_entered = "0"
while user_entered != "":
num = int(user_entered)
total += num
user_entered = input("Enter a number: ")
Note: Many other languages include a do-while loop construct specifically to make logic of this sort less awkward.
continue
¶
Let's assume we only want to include the even numbers in the total:
total = 0
while True:
user_entered = input("Enter a number: ")
if user_entered == "":
break
num = int(user_entered)
if num % 2 == 1: # odd
continue # Jump to the top and re-check loop condition
total += int(user_entered)
Warning
continue
statements should be used sparingly and with
caution. They can make it more difficult for the reader to follow
the control flow in your loop.
Exercise:¶
What will be printed by the following loop?
x = 10
while x < 1000:
print(x)
x *= 2
if x < 50:
continue
if x % 2 == 0:
x += 1
if x == 163:
break
local, global, build-in namespaces and scope¶
scope: The area of code where a name is visible. This is a concept, not a part of the Python language.
namespace: A mapping from names to objects. Namespaces are actual entities in a Python program:
GRAVITY = 9.81 # Global constants should in all-caps.
def cool_function(some_param):
some_local = some_param * 10
print(f"Locals in function:\n {locals()}\n\n")
print(f"Globals in function:\n {globals()}\n\n")
return some_local
result = cool_function(2)
print(f"Locals:\n {locals()}\n\n")
print(f"Globals:\n {globals()}\n\n")
print(f"Built-ins:\n{dir(__builtins__)}\n\n")
globals()
and locals()
are dictionaries. __builtins__
is a
module.
Work Time for PA¶
- If you haven't taken the readiness quiz: Go ahead and make an attempt. You have unlimited submissions.
- If you haven't finished Part 1: Write
roll_dice
and test it against the tests from last monday. - If you have already finished Part 1: work on tests for Part 2.
- If you have already finished Part 2: show me or the TA your tests for feedback.