4-dars: Funksiyalar
Dars
Davomiyligi: 90 daqiqa Maqsad: Python funksiyalari, parameter, return, default values, *args, **kwargs.
1. Funksiya yaratish
def greet(name):
print(f"Salom, {name}!")
greet("Akmal")C bilan farqi:
defso'zi- Tur belgilash yo'q
{}o'rniga indentatsiya- Return type yo'q
2. Return
def square(n):
return n * n
result = square(5) # 25
print(result)return — funksiyani tugatadi.
3. Bir nechta qiymat
def divide(a, b):
return a // b, a % b # tuple
quotient, remainder = divide(17, 5)
print(quotient, remainder) # 3 2C'da pointer kerak edi. Python — tuple.
4. Default parameters
def greet(name, greeting="Salom"):
print(f"{greeting}, {name}!")
greet("Akmal") # Salom, Akmal!
greet("Akmal", "Hello") # Hello, Akmal!C'da default — yo'q. Python — default values.
5. Keyword arguments
def create_user(name, age, city="Toshkent"):
print(f"{name}, {age}, {city}")
# Pozitsion
create_user("Akmal", 22)
# Keyword
create_user(name="Aziza", age=19)
create_user(age=25, name="Botir") # tartib muhim emas6. *args — istalgancha pozitsion
def sum_all(*numbers):
total = 0
for n in numbers:
total += n
return total
print(sum_all(1, 2, 3)) # 6
print(sum_all(1, 2, 3, 4, 5)) # 15
print(sum_all()) # 0*numbers — tuple.
7. **kwargs — istalgancha keyword
def print_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
print_info(name="Akmal", age=22, city="Toshkent")
# name: Akmal
# age: 22
# city: Toshkent**info — dict.
8. Type hints (Python 3.5+)
def add(a: int, b: int) -> int:
return a + b
def greet(name: str) -> None:
print(f"Salom, {name}!")Faqat dokumentatsiya — Python ishlashga ta'sir qilmaydi.
Hint foydasi
- IDE auto-complete
- Boshqalar tushunadi
- mypy bilan tekshirish
Lekin type bermay ham ishlaydi.
9. Docstring
def factorial(n):
"""Faktorial hisoblash.
Args:
n: Musbat butun raqam
Returns:
n! qiymati
"""
if n <= 1:
return 1
return n * factorial(n - 1)help(factorial) — yordamni ko'rsatadi.
10. Local va Global
x = 10 # global
def func():
x = 20 # local (yangi)
print(x) # 20
func()
print(x) # 10 (global o'zgarmadi)global keyword
x = 10
def func():
global x
x = 20
func()
print(x) # 20global'dan ehtiyot
Iloji boricha local ishlating, parameter orqali uzating.
11. Lambda (anonymous function)
square = lambda x: x ** 2
print(square(5)) # 25
# Bir qatorli
add = lambda a, b: a + b
print(add(3, 4)) # 7Lambda — bitta ifoda.
Foydasi — boshqa funksiyaga uzatish (map, filter, sorted).
12. map, filter, reduce
numbers = [1, 2, 3, 4, 5]
# map — har elementga funksiya
squares = list(map(lambda x: x ** 2, numbers))
# [1, 4, 9, 16, 25]
# filter — shartga mos
evens = list(filter(lambda x: x % 2 == 0, numbers))
# [2, 4]
# reduce — yig'ish
from functools import reduce
total = reduce(lambda a, b: a + b, numbers)
# 15Pythonic yo'l — list comprehension:
squares = [x ** 2 for x in numbers]
evens = [x for x in numbers if x % 2 == 0]
total = sum(numbers)13. Recursive funksiya
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)C bilan bir xil tushuncha.
14. Funksiya — birinchi sinf
Funksiya — o'zgaruvchi kabi:
def greet(name):
return f"Salom, {name}!"
# O'zgaruvchiga
f = greet
print(f("Akmal")) # Salom, Akmal!
# List ichida
funcs = [greet, str.upper, str.lower]
for f in funcs:
print(f("Akmal"))
# Parameter sifatida
def apply(func, value):
return func(value)
print(apply(greet, "Akmal"))15. Closure (yopilma)
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
c = make_counter()
print(c()) # 1
print(c()) # 2
print(c()) # 3Ichki funksiya — tashqi o'zgaruvchini eslab qoladi.
16. Decorator (kirish)
def timer(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"Vaqt: {time.time() - start:.4f}")
return result
return wrapper
@timer
def slow_function():
import time
time.sleep(1)
slow_function()@timer — slow_function = timer(slow_function).
Decorators — keyingi kurs uchun, lekin asosiy.
17. Generator
def count_up_to(n):
i = 0
while i < n:
yield i
i += 1
for num in count_up_to(5):
print(num)
# 0 1 2 3 4yield — har chaqirishda bittadan beradi. Memory tejaydi.
18. To'liq misol
# math_utils.py
def is_prime(n: int) -> bool:
"""n tub sonmi?"""
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def primes_up_to(n: int) -> list:
"""n gacha barcha tub sonlar."""
return [i for i in range(2, n + 1) if is_prime(i)]
def factorial(n: int) -> int:
"""n!"""
if n <= 1:
return 1
return n * factorial(n - 1)
def fibonacci(n: int) -> list:
"""Birinchi n ta Fibonacci raqami."""
if n <= 0:
return []
if n == 1:
return [0]
fibs = [0, 1]
for _ in range(2, n):
fibs.append(fibs[-1] + fibs[-2])
return fibs
def gcd(a: int, b: int) -> int:
"""Eng katta umumiy bo'luvchi."""
while b:
a, b = b, a % b
return a
def lcm(a: int, b: int) -> int:
"""Eng kichik umumiy ko'paytuvchi."""
return a * b // gcd(a, b)
if __name__ == "__main__":
print(primes_up_to(50))
print(factorial(10))
print(fibonacci(10))
print(gcd(48, 18))
print(lcm(4, 6))19. __name__ == "__main__"
if __name__ == "__main__":
# faqat shu fayl ishga tushganda ishlaydi
main()Modulni import qilsa — main() ishlamaydi. Faqat to'g'ridan-to'g'ri ishga tushganda.
Topshiriqlar
1 — Asosiy
functions.py:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return None
return a / b
print(add(5, 3))
print(subtract(10, 4))
print(multiply(6, 7))
print(divide(20, 4))
print(divide(10, 0))2 — Default va keyword
defaults.py:
def create_user(name, age=18, city="Toshkent", country="O'zbekiston"):
print(f"{name}, {age}, {city}, {country}")
create_user("Akmal")
create_user("Aziza", 22)
create_user("Botir", city="Samarqand")
create_user(name="Dilshod", country="Qozog'iston")3 — *args va **kwargs
args_kwargs.py:
def sum_all(*numbers):
return sum(numbers)
def print_info(**info):
for k, v in info.items():
print(f"{k}: {v}")
def combined(*args, **kwargs):
print(f"Pozitsion: {args}")
print(f"Keyword: {kwargs}")
print(sum_all(1, 2, 3, 4, 5))
print_info(name="Akmal", age=22)
combined(1, 2, 3, name="Akmal", age=22)4 — Recursive
recursive.py — factorial, fibonacci, gcd, sum_to_n.
5 — Lambda
lambda_demo.py:
# Sort with lambda
students = [("Akmal", 85), ("Aziza", 92), ("Botir", 78)]
# Ball bo'yicha
sorted_students = sorted(students, key=lambda s: s[1], reverse=True)
print(sorted_students)
# Ism bo'yicha
sorted_by_name = sorted(students, key=lambda s: s[0])
print(sorted_by_name)6 — map, filter
map_filter.py:
numbers = list(range(1, 11))
# Kvadrat
squares = list(map(lambda x: x ** 2, numbers))
# Faqat tub
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
primes = list(filter(is_prime, range(2, 50)))
print(squares)
print(primes)7 — Calculator (funksiyalar bilan)
calc.py:
def calculator(a, b, op):
operations = {
"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"*": lambda x, y: x * y,
"/": lambda x, y: x / y if y != 0 else None,
}
if op in operations:
return operations[op](a, b)
return None
print(calculator(10, 5, "+"))
print(calculator(10, 5, "*"))
print(calculator(10, 0, "/"))8 — Math utils
math_utils.py — Dars matnidagi to'liq modul.
Bonus: is_perfect, count_divisors, is_palindrome ham qo'shing.
9 — Closure counter
counter.py:
def make_counter(start=0, step=1):
count = start
def counter():
nonlocal count
result = count
count += step
return result
return counter
c1 = make_counter()
c2 = make_counter(100, 5)
print(c1(), c1(), c1()) # 0 1 2
print(c2(), c2(), c2()) # 100 105 11010 — GitHub
$ mkdir 6-oy-dars-4
$ git add . && git commit -m "feat: dars 4 - functions"
$ git pushLug'at
| Termin | Izoh |
|---|---|
| def | Funksiya yaratish |
| return | Qiymat qaytarish |
| Default parameter | Standart (oldindan belgilangan) qiymat |
| Keyword argument | Nom bilan |
*args | Istalgancha pozitsion |
**kwargs | Istalgancha keyword |
| Type hints | int, str (faqat hujjat) |
| Docstring | """...""" |
| Lambda | Anonymous function |
| Closure | Yopilma |
| Decorator | @func |
| Generator | yield |
__name__ | Modul nomi |