Conditionals are a nice way to make decisions by asking if something equalsTrue or not. But often one condition is not enough.We may want to take the opposite of our result. Or for instance if we want tomake a decision uponturtle.xcor() andturtle.ycor() we have to combinethem. This can be done with logical operators.
If we want something to beFalse we can usenot. It is a logicaloperator:
x=Falseifnotx:print("condition met")else:print("condition not met")
The turtle gives us a useful function to know if it is drawing or not:turtle.isdown(). This function returnsTrue if the turtle is drawing. Aswe have seen earlier, the functionturtle.penup() andturtle.pendown()toggle between drawing while moving, or just moving without a trace.
Can we write a function that only goes forward if the pen is up?
defstealthed_forward(distance):ifnotturtle.isdown():turtle.forward(distance)
Two easy to understand operators areand andor. They do exactly whatthey sound like::
if1<2and4>2:print("condition met")if1>2and4<10:print("condition not met")if4<10or1<2:print("condition met")
You are not restricted to one logical operator. You can combine as may as youwant.
Earlier we put the turtle in a circular prison. This time let’s makeit a box. If the turtle goes more than 100 in the Xor Y axis thenwe turn the turtle back around to the center.
defforward(distance):whiledistance>0:if(turtle.xcor()>100orturtle.xcor()<-100orturtle.ycor()>100orturtle.ycor()<-100):turtle.setheading(turtle.towards(0,0))turtle.forward(1)distance=distance-1