-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpython_5.py
622 lines (394 loc) · 16.1 KB
/
python_5.py
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
# -*- coding: utf-8 -*-
"""Python_5.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1zpy2suVlllrRqnjxhjJUZjp9SBnpT_9m
# **Python Functions**
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
## **Creating a Function**
In Python a function is defined using the def keyword:
"""
def my_function():
print("Hello from a function")
"""## **Calling a Function**
To call a function, use the function name followed by parenthesis:
"""
def my_function():
print("Hello from a function")
my_function()
"""## **Arguments**
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:
"""
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
"""**Note:** Arguments are often shortened to args in Python documentations.
### Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are passed into a function.
From a function's perspective:
* A parameter is the variable listed inside the parentheses in the function definition.
* An argument is the value that is sent to the function when it is called.
## **Number of Arguments**
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.
"""
# This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
"""If you try to call the function with 1 or 3 arguments, you will get an error:"""
# This function expects 2 arguments, but gets only 1:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
print("-------------------------------")
# my_function("Emil")
my_function("Emil", "Tobias", "Refsnes")
"""## **Arbitrary Arguments, *args**
If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items accordingly:
"""
# If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[-1])
# for i in kids:
# print(i)
my_function("Emil", "Tobias", "Linus")
"""**Note:** Arbitrary Arguments are often shortened to *args in Python documentations.
## **Keyword Arguments**
You can also send arguments with the `key = value` syntax.
This way the order of the arguments does not matter.
"""
def my_function(c3, c2, c1):
print("The youngest child is " + c3)
# c1 = "Emil",
# c2 = "Tobias",
# c3 = "Linus"
# my_function(c1, c2, c3)
my_function(c1 = "Emil", c2 = "Tobias", c3 = "Linus")
"""**Note:** The phrase Keyword Arguments are often shortened to kwargs in Python documentations.
## **Arbitrary Keyword Arguments, **kwargs**
If you do not know how many keyword arguments will be passed into your function, add two asterisk: `**` before the parameter name in the function definition.
This way the function will receive a dictionary of arguments, and can access the items accordingly:
"""
# If the number of keyword arguments is unknown, add a double ** before the parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
"""**Note:** Arbitrary Kword Arguments are often shortened to **kwargs in Python documentations.
## **Default Parameter Value**
If we call the function without argument, it uses the default value:
"""
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
"""## **Passing a List as an Argument**
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
"""
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
"""## **Return Values**"""
# int main() {
# return 0; # success
# }
# 0: success
# 1: Variable not created
# 2: Files could not accessed
# 3: Files cannot be opened
# 4: ....
"""To let a function return a value, use the return statement:"""
def my_function(x):
myval = 5 * x
return myval
print(my_function(3))
print(my_function(5))
print(my_function(9))
"""### Returning multiple values
To return multiple values is very easy, you just use tuples (either explicitly or implicitly).
"""
# return.multiple.py
def moddiv(a, b):
return (a // b, a % b)
print(moddiv(20, 7)) # prints (2, 6)
"""We could have wrapped the return part in the preceding code in brackets, making it an explicit tuple, but there's no need for that.
The preceding function returns both the quoteint and the remainder of the division, at the same time.
## **The pass Statement**
Function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error.
"""
def myfunction():
pass
"""## **Practice Example**"""
def checkIfPrime (numberToCheck):
for i in range(2, numberToCheck):
if (numberToCheck % i == 0):
return False
return True
userNum = int(input("Please enter an integer: "))
if (checkIfPrime(userNum)):
print(f"{userNum} is a Prime number")
else:
print(f"{userNum} is not a Prime number")
"""# **Recursion**
Python also accepts function recursion, which means a defined function can call itself.
* Recursion is a common mathematical and programming concept.
* It means that a function calls itself.
* This has the benefit of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power.
* However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.
"""
# Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
# tri_recursion(6):
# result = 6 + tri_recursion(5)
# tri_recursion(5):
# result = 5 + tri_recursion(4)
# tri_recursion(4):
# result = 4 + tri_recursion(3)
# tri_recursion(3):
# result = 3 + tri_recursion(2)
# tri_recursion(2):
# result = 2 + tri_recursion(1)
# tri_recursion(1):
# result = 1 + tri_recursion(0)
# tri_recursion(0):
# if (k>0) : False
# else:
# result = 0
# result = 1 + 0 = 1
# print(result)
# return 1
# result = 2 + 1
# print(result)
# return 3
# result = 3 + 3 = 6
# print(result)
# return 6
# result = 4 + 6 = 10
# print(result)
# ......
print("Recursion Example Results")
tri_recursion(6)
"""**Note:**
* In this example, `tri_recursion()` is a function that we have defined to call itself ("recurse").
* We use the k variable as the data, which decrements (-1) every time we recurse.
* The recursion ends when the condition is not greater than 0 (i.e. when it is 0).
To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and modifying it.
# **Variable Scope**
## **Local vs Global variables**
* A variable declared inside a function is only accessible within the function and thus is called **local variables**
* Any variable declared outside a function is known as a **global variable** and is accessible anywhere in the program.
To understand this, try the code below:
"""
message1 = "Global Variable"
def myFunction():
print("\nINSIDE THE FUNCTION")
#Global variables are accessible inside a function
print (message1)
#Declaring a local variable
message2 = "Local Variable"
print (message2)
#Calling the function
myFunction()
print("\nOUTSIDE THE FUNCTION")
#Global variables are accessible outside function
print (message1)
#Local variables are NOT accessible outside function.
print (message2)
"""* Both the local and global variables are accessible within the function
* Outside the function, the local variable message2 is no longer accessible.
## **Names sharing variables**
If a local variable shares the same name as a global variable, then the code inside the function will access the local variable only.
While code outside the function will access the global variable.
"""
# Sample code
message1 = "Global Variable (shares same name as a local variable)"
def myFunction():
message1 = "Local Variable (shares same name as a global variable)"
print("\nINSIDE THE FUNCTION")
print (message1)
# Calling the function
myFunction()
# # Printing message1 OUTSIDE the function
print ("\nOUTSIDE THE FUNCTION")
print (message1)
"""## **The global Keyword**
* Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.
* To create a global variable inside a function, you can use the global keyword.
"""
# If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print(f"Python is {x}")
"""Also, use the global keyword if you want to change a global variable inside a function."""
# To change the value of a global variable inside a function, refer to the variable by using the global keyword:
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
"""# **Python Lambda**
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
### Syntax:
`lambda arguments : expression`
The expression is executed and the result is returned:
"""
# A lambda function that adds 10 to the number passed in as an argument, and print the result:
x = lambda a : a + 10
print(x(5))
"""Lambda functions can take any number of arguments:"""
# A lambda function that multiplies argument a with argument b and print the result:
x = lambda a, b : a * b
print(x(5, 6))
# A lambda function that sums argument a, b, and c and print the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
"""## **Why Use Lambda Functions?**
The power of lambda is better shown when you use them as an anonymous function inside another function.
Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:
"""
def myfunc(n):
return lambda a : a * n
"""Use that function definition to make a function that always doubles the number you send in:"""
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2) #= lambda a : a * 2
# x = lambda a : a * 2
print(mydoubler(11))
print(mydoubler(20))
print(mydoubler(30))
print(mydoubler(40))
"""Visualize the following to udnerstand what is happening.
> `mydoubler = myfunc(2)`
However, the return value of `myfunc(n)` is `lambda a : a * n`
So replacing the right hand side makes the expression:
> `mydoubler = lambda a : a * n`, where `n = 2`
So above can be converted to:
> `mydoubler = lambda a : a * 2`
Now as per the proper definition of lambda functions,
> `mydoubler = lambda a : a * 2`
`mydoubler` can take argument `a` and perform the calculations
Thus, we can use the same function definition to make a function that always triples the number you send in:
"""
def myfunc(n):
return lambda a : a * n
# mytripler = lambda a : a * 3
# print(mytripler(11))
mytripler = myfunc(3)
print(mytripler(50))
"""Or, use the same function definition to make both functions, in the same program:"""
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
"""**Note:** *Use lambda functions when an anonymous function is required for a short period of time.*"""
# x = lambda a : a + 10
# mydoubler = lambda a : a * 2
# def myfunc(n):
# return lambda a : a * n
"""# **Python Modules**
## **What is a Module?**
* Consider a module to be the same as a code library.
* A file containing a set of functions you want to include in your application.
* Python comes with a large number of built-in functions.
* These functions are saved in files known as modules.
## **Create a Module**
To create a module just save the code you want in a file with the file extension .py:
"""
# Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
"""## **Use a Module**
Now we can use the module we just created, by using the import statement:
"""
# Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Muneendra")
"""Suppose you want to use the `checkIfPrime()` function defined earlier in another Python script. Here’s how you do it.
First save the code above as `prime.py` in the current folder.
`prime.py` should have the following code.
"""
def checkIfPrime (numberToCheck):
for x in range(2, numberToCheck):
if (numberToCheck%x == 0):
return False
return True
"""Next, create another Python file and name it `useCheckIfPrime.py`.
Save it in the current directory as well.
`useCheckIfPrime.py` should have the following code.
"""
import prime
answer = prime.checkIfPrime(10)
print (answer)
"""### Storing modules in different folder
Suppose you created a folder named `myModules` in your `D drive` at address: `D:\Muneendra\PyProgs\myModules` to store prime.py.
You need to add the following code to the top of your `useCheckIfPrime.py` file (before the line `import prime`).
`import sys`
`if 'C:\\MyPythonModules' not in sys.path:`
>`sys.path.append('C:\\MyPythonModules')`
`sys.path` refers to your Python’s system path.
This is the list of directories that Python goes through to search for modules and files. The code above appends the folder `D:\Muneendra\PyProgs\myModules` to your system path.
Now you can put `prime.py` in `D:\Muneendra\PyProgs\myModules` and `checkIfPrime.py` in any other folder of your choice.
**Note:** When using a function from a module, use the syntax: module_name.function_name.
## **Built-in Modules**
There are several built-in modules in Python, which you can import whenever you like.
"""
# Import and use the platform module:
import platform
x = platform.system()
print(x)
"""## **Using the dir() Function**
There is a built-in function to list all the function names (or variable names) in a module.
>* The dir() function:
"""
# List all the defined names belonging to the platform module:
import platform as p
import math as m
import numpy as np
x = dir(p)
print(x)
print(dir(m))
print(dir(np))
"""**Note:** The `dir()` function can be used on all modules, also the ones you create yourself.
# **Import From Module**
You can choose to import only parts from a module, by using the `from` keyword.
The module named mymodule has one function and one dictionary:
`def greeting(name):`
`print("Hello, " + name)`
`person1 = {`
`"name": "John",`
`"age": 36,`
`"country": "Norway"`
`}`
"""
# Import only the person1 dictionary from the module:
from mymodule import greeting
greeting("Muneendra")
"""**Note:** When importing using the from keyword, do not use the module name when referring to elements in the module.
* **Example:**
> `person1["age"]`, not ~`mymodule.person1["age"]`~
"""