-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNote5_Learn Python_functions.py
More file actions
249 lines (165 loc) · 5.98 KB
/
Note5_Learn Python_functions.py
File metadata and controls
249 lines (165 loc) · 5.98 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# ---------- FUNCTION BASICS ----------
# Functions allow use to reuse code and make the code easier
# to understand
# To create a function type def (define) the function name
# and then in parentheses a comma separated list of values
# to pass if needed
def add_numbers(num_1, num2):
# Return returns a value if needed
return num_1 + num2
# You call the function by name followed by passing comma
# separated values if needed and a value may or may not be
# returned
print("5 + 4 =", add_numbers(5, 4))
# ---------- FUNCTION LOCAL VARIABLES ----------
# Any variable defined inside of a function is available only
# in that function
# ---------- EXAMPLE 1 ----------
# Variables created in a function can't be accessed outside
# of it
def assign_name():
name = "Doug"
assign_name()
# Throws a NameError
# print(name)
# ---------- EXAMPLE 2 ----------
# You can't change a global variable even if it is passed
# into a function
def change_name(name):
# Trying to change the global
name = "Mark"
# A variable defined outside of a function can't be changed
# in the function using the above way
name = "Tom"
# Try to change the value
change_name(name)
# Prints Tom even though the function tries to change it
print(name)
# ---------- EXAMPLE 3 ----------
# If you want to change the value pass it back
def change_name_2():
return "Mark"
name = change_name_2()
print(name)
# ---------- EXAMPLE 4 ----------
# You can also use the global statement to change it
gbl_name = "Sally"
def change_name_3():
global gbl_name
gbl_name = "Sammy"
change_name_3()
print(gbl_name)
# ---------- RETURNING NONE ----------
# If you don't return a value a function will return None
def get_sum(num1, num2):
sum = num1 + num2
print(get_sum(5, 4))
# ---------- PROBLEM : SOLVE FOR X ----------
# Make a function that receives an algebraic equation like
# x + 4 = 9 and solve for x
# x will always be the 1st value received and you only
# will deal with addition
# Receive the string and split the string into variables
def solve_eq(equation):
x, add, num1, equal, num2 = equation.split()
# Convert the strings into ints
num1, num2 = int(num1), int(num2)
# Convert the result into a string and join (concatenate)
# it to the string "x = "
return "x = " + str(num2 - num1)
print(solve_eq("x + 4 = 9"))
# ---------- RETURN MULTIPLE VALUES ----------
# You can return multiple values with the return statement
def mult_divide(num1, num2):
return (num1 * num2), (num1 / num2)
mult, divide = mult_divide(5, 4)
print("5 * 4 =", mult)
print("5 / 4 =", divide)
# ---------- RETURN A LIST OF PRIMES ----------
# A prime can only be divided by 1 and itself
# 5 is prime because 1 and 5 are its only positive factors
# 6 is a composite because it is divisible by 1, 2, 3 and 6
# We'll receive a request for primes up to the input value
# We'll then use a for loop and check if modulus == 0 for
# every value up to the number to check
# If modulus == 0 that means the number isn't prime
def isprime(num):
# This for loop cycles through primes from 2 to
# the value to check
for i in range(2, num):
# If any division has no remainder we know it
# isn't a prime number
if (num % i) == 0:
return False
return True
def getPrimes(max_number):
# Create a list to hold primes
list_of_primes = []
# This for loop cycles through primes from 2 to
# the maximum value requested
for num1 in range(2, max_number):
if isprime(num1):
list_of_primes.append(num1)
return list_of_primes
max_num_to_check = int(input("Search for Primes up to : "))
list_of_primes = getPrimes(max_num_to_check)
for prime in list_of_primes:
print(prime)
# ---------- UNKNOWN NUMBER OF ARGUMENTS ----------
# We can receive an unknown number of arguments using
# the splat (*) operator
def sumAll(*args):
sum = 0
for i in args:
sum += i
return sum
print("Sum :", sumAll(1,2,3,4))
# ---------- pythontut2.py ----------
# We need this module for our program
import math
# Functions allow us to avoid duplicate code in our programs
# Aside from having to type code twice duplicate code is bad
# because it requires us to change multiple blocks of code
# if we need to make a change
# ---------- OUR FUNCTIONS ----------
# This routes to the correct area function
# The name of the value passed doesn't have to match
def get_area(shape):
# Switch to lowercase for easy comparison
shape = shape.lower()
if shape == "rectangle":
rectangle_area()
elif shape == "circle":
circle_area()
else:
print("Please enter rectangle or circle")
# Create function that calculates the rectangle area
def rectangle_area():
length = float(input("Enter the length : "))
width = float(input("Enter the width : "))
area = length * width
print("The area of the rectangle is", area)
# Create function that calculates the circle area
def circle_area():
radius = float(input("Enter the radius : "))
area = math.pi * (math.pow(radius, 2))
# Format the output to 2 decimal places
print("The area of the circle is {:.2f}".format(area))
# ---------- END OF OUR FUNCTIONS ----------
# We often place our main programming logic in a function called main
# We create it this way
def main():
# Our program will calculate the area for rectangles or circles
# Without functions we'd have to create a giant list of ifs, elifs
# Ask the user what shape they have
shape_type = input("Get area for what shape : ")
# Call a function that will route to the correct function
get_area(shape_type)
# Because of functions it is very easy to see what is happening
# For more detail just refer to the very short specific functions
# All of the function definitions are ignored and this calls for main()
# to execute when the program starts
main()
# ---------- HOMEWORK ----------
# Add the ability to calculate the area for parallelograms,
# rhombus, triangles, and trapezoids