-
Notifications
You must be signed in to change notification settings - Fork 278
/
Copy pathlogical_operators.rst
102 lines (73 loc) · 2.38 KB
/
logical_operators.rst
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
Logical operators
*****************
Introduction
============
Conditionals are a nice way to make decisions by asking if something equals
*True* 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 to
make a decision upon ``turtle.xcor()`` and ``turtle.ycor()`` we have to combine
them. This can be done with logical operators.
Negation of a statement
=======================
If we want something to be *False* we can use ``not``. It is a logical
operator::
x = False
if not x :
print("condition met")
else:
print("condition not met")
Exercise
--------
The turtle gives us a useful function to know if it is drawing or not:
``turtle.isdown()``. This function returns *True* if the turtle is drawing. As
we have seen earlier, the function ``turtle.penup()`` and ``turtle.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?
.. rst-class:: solution
Solution
--------
::
def stealthed_forward(distance):
if not turtle.isdown():
turtle.forward(distance)
This and that or something else
===============================
Two easy to understand operators are ``and`` and ``or``. They do exactly what
they sound like:::
if 1 < 2 and 4 > 2:
print("condition met")
if 1 > 2 and 4 < 10:
print("condition not met")
if 4 < 10 or 1 < 2:
print("condition met")
You are not restricted to one logical operator. You can combine as may as you
want.
Exercise
--------
Earlier we put the turtle in a circular prison. This time let's make
it a box. If the turtle goes more than 100 in the X *or* Y axis then
we turn the turtle back around to the center.
.. rst-class:: solution
Solution
--------
::
def forward(distance):
while distance > 0:
if (turtle.xcor() > 100
or turtle.xcor() < -100
or turtle.ycor() > 100
or turtle.ycor() < -100):
turtle.setheading(turtle.towards(0,0))
turtle.forward(1)
distance = distance - 1
__________
We can also get the XOR logic ooeration using cap Sysmbol (^).
Example :
If we take XOR operation of 4 and 3 then we can write in python as below:
num1 = 4
num2 = 3
xor = num1 ^ num2
print(f"{num1} XOR {num2}" : ,xor)
__________
OUTPUT :
4 XOR 3 : 7