forked from ernestas-poskus/interactive-programming-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_tips2.py
More file actions
114 lines (81 loc) · 1.79 KB
/
code_tips2.py
File metadata and controls
114 lines (81 loc) · 1.79 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
##############
# Example of missing "global"
n1 = 0
def increment():
global n1
n1 = n1 + 1
increment()
increment()
increment()
print n1
##############
# Example of missing "global"
n2 = 0
def assign(x):
n2 = x
assign(2)
assign(15)
assign(7)
print n2
##############
# Example of missing "return"
n3 = 0
def decrement():
global n3
n3 = n3 - 1
x = decrement()
print "x = ", x
print "n = ", n3
##############
# Example of print debugging
import simplegui
x = 0
def f(n):
print "f: n,x = ", n, x
result = n ** x
print "f: result = ",result
return result
def button_handler():
global x
print "bh : x = ", x
x += 1
print "bh : x = ", x
def input_handler(text):
print "ih : text = ", text
print f(float(text))
frame = simplegui.create_frame("Example", 200, 200)
frame.add_button("Increment", button_handler)
frame.add_input("Number:", input_handler, 100)
frame.start()
##############
# Examples of simplifying conditionals
def f1(a, b):
"""Returns True exactly when a is False and b is True."""
if a == False and b == True:
return True
else:
return False
def f2(a, b):
"""Returns True exactly when a is False and b is True."""
if not a and b:
return True
else:
return False
def f3(a, b):
"""Returns True exactly when a is False and b is True."""
return not a and b
def g1(a, b):
"""Returns False eactly when a and b are both True."""
if a == True and b == True:
return False
else:
return True
def g2(a, b):
"""Returns False eactly when a and b are both True."""
if a and b:
return False
else:
return True
def g3(a, b):
"""Returns False eactly when a and b are both True."""
return not (a and b)