summaryrefslogtreecommitdiff
path: root/PYTHON/ФУНКЦИИ.md
blob: 73d132cf2cddcc94cbabca7a3f44e20ea57c482e (plain)
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
```python
def foo() -> int :
	return x ** 2


x = foo( 2 )
print(x) # 5


def foo( x : str, y : int ) -> str :
    ...........


name = input('Ведите имя:') # - всегда строка!
print(dir(name)) # - вывод атрибутов

# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
#
```

```python
# собираем все параметры в кортеж:

def sum_nums(*args):
	print(args)
	print(type(args))
	print(args[0])
	return sum(args)


print(sum_nums(2, 3, 7))
``` 

```python
# аргументы с ключевыми словами - порядок не важен:

def get_post_info(name, post_qty):
	info = f"{name} wrote {post_qty} posts"
	return info
  

info = get_post_info(name='Vlapa', post_qty=50)
print(info)
```

```python
# объединение аргументов в DICT (только именованные):

def get_post_info(**person):
	print(person)
	print(type(person))
	info = (
	f"{person['name']} wrote "
	f"{person['post_qty']} posts"
	)
	return info

info = get_post_info(name='Vlapa', post_qty=50)
print(info)
```

```python
# значение по умолчанию:

def mult_by(value, multiplier=1):
	return value * multiplier

print(mult_by(10, 2))
print(mult_by(5))

```

```python
# 

from datetime import date

  
def get_weekday():
	return date.today().strftime('%A')

  
def create_new_post(post, weekday=get_weekday()):
	post_copy = post.copy()
	post_copy['created_on_weekday'] = weekday
	return post_copy


initial_post = {
	'id': 234,
	'author': 'Vlapa',
}

post_with_weekday = create_new_post(initial_post)
```

```python
# callback function

def print_number_info(num):
	"""
	Print num information
	Args:
		num (int): Integer number
	"""
	if (num % 2) == 0:
	print("Число четное")
else:
	print("Число НЕ четное")


def print_square_num(num):
	print("Square of the num is", num * num)


def process_number(num, callback_fn):
	callback_fn(num)

  
entered_num = int(input("Введите любое целое число: "))

process_number(entered_num, print_number_info)
process_number(entered_num, print_square_num)
```

```python
print(dir()) # все переменные области
```

```python
def greeting(greet):
	return lambda name: f"{greet}, {name}!"
	
	# def info(name):
	#	 return f"{greet}, {name}!"
	# return info

morning_greeting = greeting("Good Morning")

print(morning_greeting('Vlapa'))

evening_greeting = greeting("Good Evening")

print(evening_greeting('Vlapa'))
```
======================================================
### Голобурдин:

```python
def chain_sum0(number):
	result = number
	def wrapper(number2=None):
		nonlocal result
		if number2 is None:
			return result
		result += number2
		return wrapper
	return wrapper
	

def chain_sum00(number):
	result = number
	def wrapper(number2=None):
		nonlocal result
		try:
			number2 = int(number2)
		except TypeError:
			return result
		result += number2
		return wrapper
	return wrapper
	

def chain_sum(number):
	def wrapper(number2=None):
		def inner():
			wrapper.result += number2
		return wrapper
		logic = {
			type(None): lambda: wrapper.result,
			int: inner
		}
		return logic[type(number2)]()
	wrapper.result = number
	return wrapper


print(chain_sum(5)())
print(chain_sum(5)(2)())
print(chain_sum(5)(100)(-10)())
```