Upload
debra-ray
View
215
Download
0
Embed Size (px)
Citation preview
Iteration“for ??? in range(min,max,interval):”
What if we do not know the number of repetitions ?“while (???):”
(p.49)problem = input(“Enter a math problem, or ‘q’ to quit: “)while (problem != “q”): print(“Answer to “ , problem, “ is: “, eval(problem)) problem = input(“Enter a math problem, or ‘q’ to quit: “)
Chap. 5 Conditional Expressions
Can test equality with == Can also test <, >, >=, <=, != (not equals) In general, 0 is false, 1 is true
So you can have a function return a “true” or “false” value.
Alert!= means “make them equal!”== means “are they equal?”
Multiple conditionals (Boolean) A and B A or B
True only when both True when either A and B are true A or B is true
B\A False True B\A False True
False False False False False True
True False True True True True
not A
Boolean Operators
and, or, not 6<10 and 3<7 4!=4 or 5<8 not 6<10
If..else Conditional
def posSum(list): psum = 0 for v in range(0, len(list)): if list[v] > 0: psum = psum+list[v] return psum
Add all values in a list
Add only positive values
def sum(list): psum = 0 for v in range(0, len(list)): psum = psum + list[v] return psum
How an if works
if is the command name Next comes an
expression: Some kind of true or false comparison
Then a colon
Then the body of the if—the things that will happen ONLY WHEN the expression is true
if list[v] > 0:
psum = psum+list[v]
if (expression):
next indented block
else: Statements
false
Pictorial view of how if works
true
ConditionalDrunken turtle
Random walk or Brownian motionA turtle
From the current positionTake an arbitrary direction and distance
Random packageimport random
random.random() returns a random fraction
between 0 and 1
How to get a random number between (0,100)?
A random number between (-50, 50) ?
Drunken Turtle
Present location of turtle: curX, curY
Next random location ?nextX = curX -50 + 100* random.random()nextY = curY -50 + 100* random.random()
Random Walk
import random
## function randNext(curX, curY)# Given coordinate (curX, curY), generate next
random coordinate#def randNext(curX, curY): nextX = curX -50 + 100*random.random() nextY = curY -50 + 100*random.random() return nextX, nextY
How to write a function for repetitive operations ? Repeated set of instructions
(curX, curY) = (nextX, nextY) (nextX, nextY) = randWalk.randNext(curX, curY) tt.goto(nextX, nextY)
Write a function, called drawRandom(), that performs the repeated set of instructions
What is a potential problem ?
May run out of the display window How can we make it sure that turtle stays in bound
?
Lab
Write a Python function of a drunken turtle which stays in bound
wn = turtle.getscreen()
wWid = wn.window_width()
wHgt = wn.window_height()Make it sure that you halve the window sizes for +- coordinates
Email your Python program [email protected]