-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths05_functions.py
More file actions
215 lines (154 loc) · 6.07 KB
/
s05_functions.py
File metadata and controls
215 lines (154 loc) · 6.07 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
# -*- coding: utf-8 -*-
"""S05 - Functions.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1uw4ETd5JTkOYG3Q8goslw0-Yj7zaAfMs
# 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.
"""
def my_function():
print("Hello from a function")
"""as you can see, the above code dose *not* print anything, as it is not yet *called*."""
my_function() # name of the function + () to call it
for i in range(1,11):
my_function()
"""**Arguments** (args/Parameters)
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.
"""
def say_hi(name):
print("Hi "+name+"!")
say_hi("Ali")
say_hi("Saeed")
say_hi("Zahra")
say_hi()
def say_hi(name="You"):
print("Hi "+name+"!")
say_hi()
def say_hello(fname, lname):
print("Hello "+fname + " " + lname+"!")
say_hello("Majid", "Einian")
say_hello("Jacob")
# Modify say_hello so the last name is optional
def say_hello(fname, lname=""):
print("Hello "+fname + " " + lname+"!")
say_hello("Majid", "Einian")
say_hello("Jacob")
def say_hi_new(name):
print("Hello "+name+"!")
str1 = input("What is your name? :")
say_hi_new(str1)
"""If the number of arguments is unknown, add a * before the parameter name.
You can also send arguments with the key = value syntax. This way the order of the arguments does not matter.
for more info see https://www.w3schools.com/python/python_functions.asp
You can also use `list`, `touple`, `set` & `dict`:
"""
# Sending parameters in a dict
def my_function(kids):
k = min(kids, key=kids.get)
n = min(kids.values())
print("The youngest child is " + k +" who is ", end='')
print(n)
my_function({"Emil":12, "Tobias":14, "Linus":8,"Bob":19})
"""**Return Values** To let a function return a value, use the return statement:"""
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
# Returning more than one value
def my_function(x):
return [(5 * x, 10 * x),(3 * x, 6 * x)]
print(my_function(3))
a = my_function(3)
b = my_function(4)
c = my_function(5)
print((a,b,c))
"""**Recursive Functions**"""
def fct(x):
if x<0:
return np.nan
if x==0:
return 1
return fct(x-1)*x
print(fct(4))
print(fct(-4))
"""## Using Other peoples' code: modules, packages, libraries, and frameworks
**Module** is a file which contains various Python functions and global variables. It is simply just .py extension file which has python executable code.
**Package** is a collection of modules. It must contain an init.py file as a flag so that the python interpreter processes it as such. The init.py could be an empty file without causing issues.
**Library** is a collection of packages.
**Framework** is a collection of libraries. This is the architecture of the program.
"""
import math
print(math.sin(1.45))
import math as m
print(m.sin(3.14))
from math import sin, pi
print(sin(pi/6))
print(cos(pi/6))
from math import * # not recommended
print(sin(pi/6))
print(cos(pi/6))
print(trunc(-3.14))
print(floor(-3.14))
"""**Functions**
| Function | Description |
|--------|-------------|
| `acos()`| arc cosine |
| `acosh()`| inverse hyperbolic cosine |
| `asin()`| arc sine |
| `asinh()`| inverse hyperbolic sine |
| `atan()`| arc tangent |
| `atan2()`| arc tangent of y/x |
| `atanh()`| inverse hyperbolic tangent |
| `ceil()`| Rounds a number up to the nearest integer |
| `comb()`| number of ways to choose k items from n items without repetition and order |
| `copysign()`| Returns a float consisting of the value of the first parameter and the sign of the second parameter |
| `cos()`| cosine |
| `cosh()`| hyperbolic cosine |
| `degrees()` | Converts an angle from radians to degrees |
| `dist()` | Returns the Euclidean distance between two points (p and q), where p and q are the coordinates of that point |
| `exp()` | Returns E raised to the power of x |
| `expm1()` | `exp()-1` |
|`fabs()` | absolute value of a number|
|`factorial()` | the factorial of a number|
|`floor()` | Rounds a number down to the nearest integer|
|`fmod()` | remainder of x/y|
|`frexp()` | Returns the mantissa and the exponent, of a specified number|
|`fsum()` | sum of all items in any iterable (tuples, arrays, lists, etc.)|
|`gamma()` | gamma function at x|
|`gcd()` | greatest common divisor of two integers|
|`hypot()` | Euclidean norm|
|`isclose()` | Checks whether two values are close to each other, or not|
|`isfinite()` | Checks whether a number is finite or not|
|`isinf()` | Checks whether a number is infinite or not|
|`isnan()` | Checks whether a value is NaN (not a number) or not|
|`isqrt()` | Rounds a square root number downwards to the nearest integer|
|`ldexp()` | inverse of `frexp()` which is `x * (2**i)` of the given numbers x and i|
|`lgamma()` | log gamma value of x|
|`log()` | natural logarithm of a number, or the logarithm of number to base|
|`log10()` | base-10 logarithm of x|
|`log1p()` | natural logarithm of 1+x|
|`log2()` | base-2 logarithm of x|
|`perm()` | number of ways to choose k items from n items with order and without repetition|
|`pow() `| value of x to the power of y|
|`prod()`| product of all the elements in an iterable|
|`radians() `| Converts a degree value into radians|
|`remainder()`| closest value that can make numerator completely divisible by the denominator|
|`sin()` | sine of a number|
|`sinh()` | hyperbolic sine of a number|
|`sqrt()` | square root of a number|
|`tan()` | tangent of a number|
|`tanh()` | hyperbolic tangent of a number|
|`trunc()` | truncated integer parts of a number |
**Constants**
| Constant | Description |
|----------|-------------|
| `e` | Euler's number (2.7182...) |
| `inf` | floating-point positive infinity |
| `nan` |floating-point NaN (Not a Number) value |
| `pi` | $\pi$ (3.1415...) |
| `tau` | $\pi \times 2$ |
"""