2-dars: O'zgaruvchilar va ma'lumot turlari
Dars
Davomiyligi: 90 daqiqa Maqsad: Python turlari va o'zgaruvchilar bilan ishlash.
1. O'zgaruvchi yaratish
name = "Akmal"
age = 22
height = 1.75
is_student = TrueTur belgilash kerak emas — Python avtomatik.
2. Asosiy turlar
| Tur | Misol |
|---|---|
int | 42, -10, 0 |
float | 3.14, -0.5 |
str | "Akmal", 'Hello' |
bool | True, False |
None | None |
list | [1, 2, 3] |
dict | {"key": "value"} |
tuple | (1, 2, 3) |
set | {1, 2, 3} |
3. int va float
x = 42 # int
y = 3.14 # float
z = -5 # int
w = 1.5e10 # float (scientific)Cheksiz katta: Python int — chegarasiz.
big = 10 ** 100 # OK!C'da int 4 byte, lekin Python — istalgancha katta.
4. str (string)
a = "Salom"
b = 'World'
c = """Bir nechta
qatorli matn"""
# F-string
name = "Akmal"
greeting = f"Salom, {name}!"Apostrof yoki qo'shtirnoq — bir xil.
String operatorlar
s = "Hello"
print(len(s)) # 5
print(s + " World") # konkatenatsiya
print(s * 3) # "HelloHelloHello"
print(s[0]) # 'H'
print(s[-1]) # 'o'
print(s[1:4]) # 'ell' (slice)
print("ello" in s) # True5. bool
a = True
b = False
# 0, "", [], None — Falsy
# Boshqalari — Truthy
if 0:
print("0 truthy") # Bu ishlamaydi
if "":
print("'' truthy") # Bu ham
if [1, 2]:
print("list truthy") # Ishlaydi6. None
x = None
if x is None:
print("Bo'sh")C: NULL. JavaScript: null. Python: None.
== o'rniga is ishlatish tavsiya etiladi.
7. type() — turni tekshirish
x = 42
print(type(x)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("Akmal")) # <class 'str'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>
print(type([1, 2])) # <class 'list'>isinstance() — yaxshiroq
x = 42
if isinstance(x, int):
print("int")8. Tur o'zgartirish
# String → int
n = int("42") # 42
n = int("3.14") # XATO!
n = int(3.14) # 3
# String → float
f = float("3.14") # 3.14
# Int/float → string
s = str(42) # "42"
s = str(3.14) # "3.14"
# Bool
b = bool(0) # False
b = bool(1) # True
b = bool("") # False
b = bool("hello") # True
# Int → bool
b = bool(0) # False
b = bool(-5) # True (har 0 dan boshqasi True)9. Bir nechta o'zgaruvchi
# Bir vaqtda
a, b, c = 1, 2, 3
# Bir xil qiymat
x = y = z = 0
# Swap
a, b = b, a # C'da temp kerak edi!Swap Python'da — bir qator!
10. Constants (konstantalar)
Python'da rasmiy const yo'q. Konventsiya — KATTA HARF:
PI = 3.14159
MAX_USERS = 100
DATABASE_URL = "..."Texnik jihatdan o'zgartirilishi mumkin, lekin uslub bo'yicha — yo'q.
11. Naming conventions
# Yaxshi
user_name = "Akmal" # snake_case (o'zgaruvchi, funksiya)
MAX_VALUE = 100 # SCREAMING_SNAKE_CASE (konstanta)
# Class — keyingi darslarda
class Student: # PascalCase
passReserved keywords:
False, None, True, and, as, assert, async, await,
break, class, continue, def, del, elif, else, except,
finally, for, from, global, if, import, in, is, lambda,
nonlocal, not, or, pass, raise, return, try, while, with, yield12. f-string formatlash
name = "Akmal"
age = 22
pi = 3.14159
# Asosiy
print(f"Salom, {name}!")
# Aniqlik
print(f"Pi: {pi:.2f}") # 3.14
print(f"Pi: {pi:.5f}") # 3.14159
# Maydon kengligi
print(f"|{name:10}|") # |Akmal |
print(f"|{name:>10}|") # | Akmal|
print(f"|{name:^10}|") # | Akmal |
# Raqamlar
print(f"|{age:5d}|") # | 22|
print(f"|{age:05d}|") # |00022|
# Ifoda
print(f"{2 + 3}") # 5
print(f"{name.upper()}") # AKMAL
print(f"{age * 2}") # 44
# Debug (Python 3.8+)
print(f"{age=}") # age=2213. Maxsus belgilar (escape)
print("Birinchi\nIkkinchi") # \n yangi qator
print("Tab\tafter") # \t tab
print("Quote: \"text\"") # \" qo'shtirnoq
print("Backslash: \\") # \\ backslash
# Raw string (escape ishlamaydi)
print(r"C:\Users\Akmal") # \U va boshqalar e'tiborsiz14. Math amallar
+ - * /
** # daraja: 2 ** 10 = 1024
// # butun bo'lish: 7 // 2 = 3
% # qoldiq: 7 % 2 = 1
# Boshqa funksiyalar
abs(-5) # 5
round(3.7) # 4
round(3.14159, 2) # 3.14
min(1, 2, 3) # 1
max(1, 2, 3) # 3
sum([1, 2, 3]) # 6math moduli
import math
math.pi # 3.141592...
math.e # 2.718...
math.sqrt(25) # 5.0
math.pow(2, 10) # 1024.0
math.log(10) # 2.302... (ln)
math.log2(8) # 3.0
math.log10(100) # 2.0
math.sin(math.pi / 2) # 1.0
math.factorial(5) # 12015. random moduli
import random
random.random() # 0.0 - 1.0
random.randint(1, 10) # 1-10 (inclusive)
random.choice(["a","b","c"]) # birini tanlash
random.shuffle([1,2,3]) # aralashtirish16. To'liq misol
# personal_info.py
name = input("Ism: ")
age = int(input("Yosh: "))
height = float(input("Bo'y (m): "))
city = input("Shahar: ")
# Calculations
birth_year = 2026 - age
height_cm = height * 100
age_in_days = age * 365
# Type check
print(f"\n=== Ma'lumotlar ===")
print(f"Ism: {name} ({type(name).__name__})")
print(f"Yosh: {age} ({type(age).__name__})")
print(f"Bo'y: {height} m = {height_cm:.0f} cm")
print(f"Shahar: {city}")
print(f"Tug'ilgan: {birth_year} yil")
print(f"Yashagan kunlar: {age_in_days}")
# Bool
is_adult = age >= 18
is_tall = height > 1.80
print(f"\nKattalar: {is_adult}")
print(f"Bo'yli: {is_tall}")Topshiriqlar
1 — Turlar
turlar.py:
a = 42
b = 3.14
c = "Python"
d = True
e = None
print(a, type(a))
print(b, type(b))
print(c, type(c))
print(d, type(d))
print(e, type(e))2 — Aylantirish
convert.py:
# String → int
s = "100"
n = int(s)
print(n + 5) # 105
# Float → int (kasr tashlanadi)
f = 3.9
print(int(f)) # 3
# Int → string
n = 42
s = str(n)
print(s + " yosh") # "42 yosh"
# String → float
s = "3.14"
f = float(s)
print(f * 2) # 6.283 — Math
math_demo.py:
import math
r = float(input("Doira radiusi: "))
print(f"Yuza: {math.pi * r ** 2:.2f}")
print(f"Perimetri: {2 * math.pi * r:.2f}")
print(f"Sirti (shar): {4 * math.pi * r ** 2:.2f}")
print(f"Hajmi (shar): {(4/3) * math.pi * r ** 3:.2f}")4 — Random
random_demo.py:
import random
print(random.random())
print(random.randint(1, 100))
print(random.choice(["Akmal", "Aziza", "Botir"]))
# Dice
print(f"Olti yoq tashlash: {random.randint(1, 6)}")
# Lottery
numbers = []
for _ in range(6):
numbers.append(random.randint(1, 49))
print(f"Lotereya: {numbers}")5 — F-string
format.py — Dars matnidagi barcha format misollarini sinab ko'ring.
6 — Swap
swap.py:
a = 5
b = 10
# C'da temp kerak edi
# Python — bir qator
a, b = b, a
print(a, b) # 10 5
# 3 ta o'zgaruvchi
x, y, z = 1, 2, 3
x, y, z = z, x, y
print(x, y, z) # 3 1 27 — BMI kuchli
bmi_full.py:
weight = float(input("Vazn (kg): "))
height = float(input("Bo'y (m): "))
age = int(input("Yosh: "))
bmi = weight / (height ** 2)
ideal_weight = (height ** 2) * 22
# F-string bilan jadval
print(f"\n{'-' * 30}")
print(f"|{'Vazn':<10}|{weight:>15.2f} kg|")
print(f"|{'Bo\'y':<10}|{height:>15.2f} m |")
print(f"|{'Yosh':<10}|{age:>15} |")
print(f"|{'BMI':<10}|{bmi:>15.2f} |")
print(f"|{'Ideal':<10}|{ideal_weight:>15.2f} kg|")
print(f"{'-' * 30}")
if bmi < 18.5:
cat = "Yetishmovchilik"
elif bmi < 25:
cat = "Normal"
elif bmi < 30:
cat = "Ortiqcha"
else:
cat = "Semizlik"
print(f"Kategoriya: {cat}")8 — Kvadrat tenglama
quadratic.py:
import math
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
d = b ** 2 - 4 * a * c
if d < 0:
print("Haqiqiy ildiz yo'q")
elif d == 0:
x = -b / (2 * a)
print(f"x = {x}")
else:
x1 = (-b + math.sqrt(d)) / (2 * a)
x2 = (-b - math.sqrt(d)) / (2 * a)
print(f"x1 = {x1}, x2 = {x2}")9 — String operatsiyalari
string_ops.py:
s = "Python dasturlash"
print(len(s))
print(s.upper())
print(s.lower())
print(s.title())
print(s.replace("Python", "C"))
print(s.split())
print(s[0:6])
print(s[-9:])
print("Python" in s)10 — GitHub
$ mkdir 6-oy-dars-2
$ # fayllar
$ git add . && git commit -m "feat: dars 2 - variables and types"
$ git pushLug'at
| Termin | Izoh |
|---|---|
| int / float / str / bool | Asosiy turlar |
| None | Python NULL |
| type() | Tur tekshirish |
| isinstance() | Tur tekshirish (yaxshiroq) |
| Type conversion | int(), float(), str() |
| f-string | f"{name}" |
| Constants | SCREAMING_SNAKE_CASE |
| snake_case | o'zgaruvchi nomlash |
| math / random | Standart kutubxonalar |
| Truthy / Falsy | 0, "", [], None — false |