Python-Cheatsheet/less5.md

109 lines
2.6 KiB
Markdown
Raw Normal View History

2024-04-24 12:42:06 +09:00
[Ссылка на урок](https://youtu.be/OWgVyRgulkI?si=J-BtI0QqmxcCsx55)
2024-04-24 11:02:02 +09:00
2024-04-24 12:42:06 +09:00
### Области видимости в python ###
```python
2024-04-24 11:02:02 +09:00
x, y = 1, 2
print("Расчет глобальных переменных", x * y)
def func_1():
print("Расчет глобальных переменных внутри функции", x * y)
def func_2():
x, y = 2, 4
print("Расчет переменных определенных внутри функции", x * y)
func_1()
func_2()
2024-04-24 12:42:06 +09:00
print("Расчет глобальных переменных", x * y)
```
2024-04-24 11:02:02 +09:00
2024-04-24 12:42:06 +09:00
### Передача параметров в функции python ###
```python
2024-04-24 11:02:02 +09:00
def plus(a, b, c):
return a + b + c
# Позиционные
res = plus(1, 2, 3)
print(res)
# Именованные
res = plus(a=1, b=2, c=3)
print(res)
res = plus(c=3, a=1, b=2)
print(res)
# Позиционные + Именованные
res = plus(1, 2, c=3)
print(res)
# Явное указание, что параметры должны указываться как именованные
# Используется * и после нее именованные параметры
def plus_1(a, *, b, c):
return a + b + c
# Не правильно
res = plus_1(1, 2, c=3)
# Правильно
res = plus_1(1, b=2, c=3)
2024-04-24 12:42:06 +09:00
```
2024-04-24 11:02:02 +09:00
2024-04-24 12:42:06 +09:00
### Распаковка при передаче параметров в функции ###
```python
2024-04-24 11:02:02 +09:00
# Распаковка
2024-04-24 12:42:44 +09:00
my_list_1 = ['Стул', 'Шкаф', 'Стол']
price = {
2024-04-24 11:02:02 +09:00
'c': 200,
'a': 4500,
'b': 2300
}
def plus_2(a, b, c):
return a + b + c
res = plus_2(*my_list_1)
print(res)
res = plus_1(**price)
print(res)
def plus_3(x, y, z, a, b, c):
print(x + y + z)
print(a + b + c)
plus_3(*my_list_1, **price)
2024-04-24 12:42:06 +09:00
```
2024-04-24 11:02:02 +09:00
2024-04-24 12:42:06 +09:00
### Параметры по умолчанию ###
```python
2024-04-24 11:02:02 +09:00
# Параметры по умолчанию
def plus_4(a=0, b=0, c=0):
return a + b + c
print(plus_4())
print(plus_4(a=1))
print(plus_4(a=1, b=1))
2024-04-24 12:42:06 +09:00
```
### Произвольное число параметров ###
```python
2024-04-24 11:02:02 +09:00
# Произвольное число позиционных параметров
def plus_all_1(*args):
total_plus = 0
for arg in args:
total_plus += arg
return total_plus
print(plus_all_1(1, 2, 3, 4, 5))
print(plus_all_1(1, 2))
# Произвольное число именованных параметров
def plus_all_2(**kwargs):
for key, value in kwargs.items():
print(key, '=', value)
plus_all_2(a=1, b=2, c=3, d=4, z=5)
2024-04-24 12:42:06 +09:00
plus_all_2(a=1, b=2)
```
[Назад на главную](readme.md)