4.1 Python Asoslari — Nazariya
Hafta: 1 | Masalalar: 25 | Qiyinlik: ⭐⭐
Kirish
Python — robotika, ma'lumotlar tahlili va sun'iy intellekt uchun eng mashhur dasturlash tili. Oson sintaksis, kuchli kutubxonalar.
1. Ma'lumot Turlari
Asosiy turlar
# Butun son (int)
x = 42
sensor_count = 8
# Kasr son (float)
pi = 3.14159
voltage = 3.3
# Matn (str)
robot_name = "Dron-01"
status = 'active'
# Mantiqiy (bool)
is_flying = True
motor_error = False
# Tekshirish
print(type(x)) # <class 'int'>
print(type(pi)) # <class 'float'>
Ro'yxat (list)
# Yaratish
sensors = [0, 1, 2, 3, 4]
motors = ["M1", "M2", "M3", "M4"]
# Element olish
first = sensors[0] # 0
last = sensors[-1] # 4
# O'zgartirish
sensors[0] = 100
# Metodlar
sensors.append(5) # Oxiriga qo'shish
sensors.pop() # Oxirgini olib tashlash
len(sensors) # Uzunlik
Lug'at (dict)
# Robot konfiguratsiya
config = {
"name": "QuadX",
"motors": 4,
"max_speed": 20.5,
"sensors": ["IMU", "GPS", "Barometer"]
}
# Qiymat olish
name = config["name"]
motors = config.get("motors", 0) # Default qiymat
# Qo'shish/o'zgartirish
config["battery"] = 3.7
Tuple va Set
# Tuple (o'zgarmas)
position = (10.5, 20.3, 5.0) # x, y, z
x, y, z = position # Unpacking
# Set (takrorlanmas)
active_motors = {1, 2, 3, 4}
active_motors.add(5)
active_motors.remove(1)
2. Operatorlar
Arifmetik
a, b = 10, 3
a + b # 13 (qo'shish)
a - b # 7 (ayirish)
a * b # 30 (ko'paytirish)
a / b # 3.333... (bo'lish)
a // b # 3 (butun bo'lish)
a % b # 1 (qoldiq)
a ** b # 1000 (daraja)
Solishtirish
x, y = 5, 10
x == y # False (teng)
x != y # True (teng emas)
x < y # True (kichik)
x <= y # True (kichik yoki teng)
x > y # False (katta)
x >= y # False (katta yoki teng)
Mantiqiy
a, b = True, False
a and b # False
a or b # True
not a # False
3. Shart Operatorlari
if-elif-else
temperature = 75
if temperature > 80:
print("XAVF! Motor qizib ketdi!")
shutdown_motors()
elif temperature > 60:
print("Ogohlantirish: Harorat yuqori")
reduce_power()
else:
print("Normal holat")
# Qisqa yozuv
status = "OK" if temperature < 60 else "WARNING"
Ichki shartlar
altitude = 100
battery = 20
if altitude > 50:
if battery < 30:
print("Batareya kam — qo'nish kerak!")
land()
4. Sikllar
for loop
# Ro'yxat bo'ylab
motors = [1, 2, 3, 4]
for motor in motors:
print(f"Motor {motor} tekshirilmoqda...")
# range() bilan
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, 10, 2): # 1, 3, 5, 7, 9
print(i)
# enumerate bilan
sensors = ["IMU", "GPS", "Baro"]
for i, sensor in enumerate(sensors):
print(f"{i}: {sensor}")
while loop
# Dron balandlik kontroli
altitude = 0
target = 10
while altitude < target:
altitude += 0.5
print(f"Balandlik: {altitude}m")
# break va continue
while True:
data = read_sensor()
if data is None:
continue # Keyingisiga o'tish
if data == "STOP":
break # Sikldan chiqish
process(data)
5. Funksiyalar
Oddiy funksiya
def calculate_distance(x1, y1, x2, y2):
"""Ikki nuqta orasidagi masofa"""
dx = x2 - x1
dy = y2 - y1
return (dx**2 + dy**2) ** 0.5
distance = calculate_distance(0, 0, 3, 4)
print(distance) # 5.0
Default parametrlar
def motor_speed(motor_id, speed=50, direction="forward"):
"""Motor tezligini sozlash"""
print(f"Motor {motor_id}: {speed}% {direction}")
motor_speed(1) # Default
motor_speed(2, 75) # speed = 75
motor_speed(3, direction="back") # Nomlangan
*args va **kwargs
def log_data(*values):
"""Ixtiyoriy sonli qiymatlarni log qilish"""
for v in values:
print(f" {v}")
log_data(1, 2, 3, 4, 5)
def configure(**settings):
"""Kalit-qiymat juftliklari"""
for key, value in settings.items():
print(f"{key} = {value}")
configure(speed=100, mode="auto", debug=True)
Lambda
# Bir qatorli funksiya
square = lambda x: x ** 2
print(square(5)) # 25
# Tartiblashda
motors = [("M1", 80), ("M2", 45), ("M3", 92)]
motors.sort(key=lambda m: m[1]) # Tezlik bo'yicha
6. Klasslar
Asosiy klass
class Motor:
"""DC Motor klassi"""
def __init__(self, pin, max_speed=100):
self.pin = pin
self.max_speed = max_speed
self.current_speed = 0
self.is_running = False
def start(self, speed=50):
"""Motorni ishga tushirish"""
self.current_speed = min(speed, self.max_speed)
self.is_running = True
print(f"Motor {self.pin}: {self.current_speed}%")
def stop(self):
"""Motorni to'xtatish"""
self.current_speed = 0
self.is_running = False
print(f"Motor {self.pin}: STOP")
# Foydalanish
m1 = Motor(pin=9, max_speed=80)
m1.start(60)
m1.stop()
Meros olish
class ServoMotor(Motor):
"""Servo motor (Motor dan meros)"""
def __init__(self, pin, min_angle=0, max_angle=180):
super().__init__(pin)
self.min_angle = min_angle
self.max_angle = max_angle
self.current_angle = 90
def set_angle(self, angle):
"""Burchakni sozlash"""
self.current_angle = max(self.min_angle,
min(angle, self.max_angle))
print(f"Servo {self.pin}: {self.current_angle}°")
servo = ServoMotor(10)
servo.set_angle(45)
7. Xatoliklarni Boshqarish
def read_sensor(sensor_id):
try:
value = sensors[sensor_id].read()
return value
except IndexError:
print(f"Sensor {sensor_id} mavjud emas!")
return None
except Exception as e:
print(f"Xatolik: {e}")
return None
finally:
print("Sensor o'qish tugadi")
# raise bilan
def set_speed(speed):
if speed < 0 or speed > 100:
raise ValueError(f"Noto'g'ri tezlik: {speed}")
# ...
8. Fayllar bilan Ishlash
# Yozish
with open("log.txt", "w") as f:
f.write("Dron logi\n")
f.write(f"Vaqt: {time.time()}\n")
# O'qish
with open("config.txt", "r") as f:
lines = f.readlines()
for line in lines:
print(line.strip())
# JSON
import json
config = {"speed": 50, "mode": "auto"}
with open("config.json", "w") as f:
json.dump(config, f)
with open("config.json", "r") as f:
loaded = json.load(f)
9. NumPy Asoslari
import numpy as np
# Array yaratish
arr = np.array([1, 2, 3, 4, 5])
zeros = np.zeros((3, 3))
ones = np.ones((2, 4))
range_arr = np.arange(0, 10, 0.5)
# Vektor operatsiyalar
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(a + b) # [5, 7, 9]
print(a * 2) # [2, 4, 6]
print(np.dot(a, b)) # 32 (scalar product)
print(np.cross(a, b)) # cross product
# Statistika
data = np.array([10, 20, 30, 40, 50])
print(np.mean(data)) # 30
print(np.std(data)) # 14.14
print(np.max(data)) # 50
Xulosa
| Tushuncha | Misol |
|---|---|
| O'zgaruvchi | x = 10 |
| Ro'yxat | [1, 2, 3] |
| Lug'at | {"key": "value"} |
| Funksiya | def func(): |
| Klass | class Robot: |
| Shart | if x > 0: |
| Sikl | for i in range(10): |
Keyingi Qadam
📝 Masalalar — 25 ta masala yeching!