210 likes | 531 Views
Python Conditionals and recursion : chapter 5. From Think Python How to Think Like a Computer Scientist. Boolean Expression. A Boolean expression is an expression that results in either a True or False. We can test these in easily. For example
E N D
PythonConditionals and recursion : chapter 5 From Think Python How to Think Like a Computer Scientist
Boolean Expression • A Boolean expression is an expression that results in either a True or False. We can test these in easily. For example • >>> 5 == 2 #note the double == is used to test for equality • False • >>> 5 == 5 # Note that 5=5(or x=5) is really bad!! • True • # Other relational operators include • x != yx < yx <= yx>yx>=y • All of these return a True or False • Note that True and False are NOT strings
Logical Operators • There are three logical operators, and, or and not • These are used as we do in English • >>> True and True • True • >>> True and False if both true return true else false • # False • >>> True or False # if either is true return true • True • >>> not True • True • >>> True and not False • True
Further examples • >>> x=10 • >>> y = 0 • >>> x>5 and y == 0 • True • >>> x != 10 or not y== 3 • True • >>> x>5 and x<=20 # returns True if x is between 5 and 20 • True • >>> x%2==0 or x%3==0 # divisible by 2 or by 3 return True • True
Conditional execution • The first instruction that we will look at that uses conditions is the if statement. Here is the syntax • if <condition>: • statement • statement • more_statements • # an example • if x!=0: • y = 20.0/x #makes sure the we are not dividing by 0 • print y Execute these instruction only if <condition> Is True. Four space Indention is required!
Alternative example • if <condition>: • Instruction to execute if <condition> is True • else: • Instructions to execute if <condition> is False • # Example • if (x>0): • print ‘x is positive’ • else: • print ‘x is less than or equal to zero’
Chained Conditionals • If x<y: • print ‘x is less than y’ • elif x>y: • print ‘x is greater than y’ • else: • print ‘x is equal to y’ • #You can chain as many of these elif’s as you want • # Lets do an example with grades
Determine a Letter Grade from a number • grade= ? #Assign some value here • if grade>=90: • print ‘I made an A’ #Note: As soon as a true is found • elif grade>=80: # the remainder is skipped!! • print ‘I made a B’ • elif grade>=70: • print ‘I made a C’ • else: • print ‘I better get to studying’
We can also put an if within an if • Suppose we want to see if a is greater than b and c • if a>b : • if b>c: • print a, ‘is the largest’ • else: • if a>c: • print a, ‘is the largest’ • else: • print a, ‘is not the largest’ • else: • print a, ‘ is not the largest’ Note: This is a contrived example. There is a much easier way to do this! Think about using the and operator!!
Keyboard INPUThttp://docs.python.org/2/library/functions.html • Before we look at more if-else examples we need to see how to get input (keyboard) from the person running the python program. • raw_input([prompt]) If the prompt argument is present, it is written to screen without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. • When EOF is read, EOFError is raised. • Example: • x = raw_input(‘Enter a number:’) Prompt A string
Ok, Look at this • >>> x = raw_input('Enter a number:') • Enter a number:23 • >>> x+3 #What will be printed? • Traceback (most recent call last): • File "<pyshell#3>", line 1, in <module> • x+3 • TypeError: cannot concatenate 'str' and 'int' objects • WHY? So what can we do to fix it?
Convert it to an integer or float • #method 1 • >>> x = raw_input('Enter a number:') • Enter a number:12 • >>> x=int(x) #convert x to an integer • >>> x+4 • 16 • #method 2 • >>> x = int(raw_input('Enter a number:'))+4 • Enter a number:23 • 27 What if I typed in 3.45 instead of 12
Here is what happens • >>> x = raw_input('Enter a number:') • Enter a number:3.45 • >>> int(x) • Traceback (most recent call last): • File "<pyshell#12>", line 1, in <module> • int(x) • ValueError: invalid literal for int() with base 10: '3.45' • Note: float(x) will work!
Some problems to contemplate • Evaluate a polynomial where a,b and c are entered from the keyboard. Here is a script a=float(raw_input(‘Enter a:’)) b=float(raw_input(‘Enter b:’)) c=float(raw_input(‘Enter c:’)) x=float(raw_input(‘Enter x:’)) y = a*x**2+b*x+c print ‘The answer is’,y Enter a:2 Enter b:3 Enter c:4 Enter x:5 The answer is 69.0 >>>
Back to Turtle_World • One of the problems we noticed with a random walking turtle was that it often off the screen. Let solve this problem and create a fence that the turtle is kept within. We will start by creating a simple move function • from swampy.TurtleWorld import * • from random import * • #Moves turtle to new location • #without modifing its heading • defMoveTo(t,x,y): • “”” t is the turtle, and x,y is the location we want to move to””” • t.x=x • t.y=y
Draw the fence (0,0) • #Draws the electric fence • #with a different turtle and then removes it • defDrawFence(s): • “”” s is the width of the square fence “”” • t=Turtle() # Create a turtle to draw the fence • t.delay=.001 #Draw it real fast • set_pen_color(t, 'blue') • MoveTo(t,-s/2,s/2) # Go to upper left hand corner of the fence • for i in range(4): • fd(t,s) • rt(t,90) • die(t) s
Bounce off fence • #Changes the heading if the turtle tries to • #move outside the fence. w is the width of the fence • defBounce_off_fence(t,w): • b=w/2-3 • if t.x>b: #going off • t.x =b • t.heading=180 • if t.x <-b: #going off • t.x=-b • t.heading=0 • if t.y>b: #going off top • t.y=b • t.heading=270 • if t.y<-b: #going off bottom • t.y=-b • t.heading=90 headings 90 b (0,0) 180 0 270
The Main programRun turtle around in fence • world = TurtleWorld() • fenceSize=200 • DrawFence(fenceSize) • bob = Turtle() • set_color(bob, 'red') • bob.delay=.01 • pu(bob) #Turn off the drawing of the path • for i in range(1000): # Take 1000 random steps • Bounce_off_fence(bob,fenceSize) #remember, this changes its heading • fd( bob,3) • # the following creates a random number from -45 to +45 • # It is used to create the directional wandering movement we see • angle = random()*90-45 • rt(bob,angle) • wait_for_user()
Homework • Rewrite the turtle-fence program so that the fence is now a circle that the turtle must stay inside of. • You first need to modify the DrawFence(s) to draw a circle of radius r • When is above is working modify Bounce_off_fence(t,r) to work with the circle. HINT: remember the distance formula you learned in algebra? Might need • http://www.mathsisfun.com/polar-cartesian-coordinates.html • 3. The remainder of the code aught to work as is.