PythonPython · Chapterبەش 8 · Lectureوانە 8.5

Modules and importمۆدیوڵەکان و import

Why programs are split into modules, what a module is, the course's GCD module in two files (with int(input()) instead of eval), the four forms of import, where Python looks for modules and the same-name trap, why a module runs once, if __name__ == "__main__", the standard library (math, random, statistics, secrets) and writing your own module.

بۆچی دابەش دەکرێن بۆ ، چییە، GCDـی وانەکە لە دوو فایلدا (بە ⁦int(input())⁩ لەبری eval)، چوار شێوەی import، Python لە کوێ بەدوای دەگەڕێت و تەڵەی ناوی هاوشێوە، بۆچی یەک جار جێبەجێ دەبێت، ⁦if __name__ == "__main__⁩"، (math، random، statistics، secrets) و نووسینی خۆت.

25 min read25 خولەک خوێندنەوە · 22 stepsهەنگاو

What you will learnچی فێر دەبیت

  • Explain why programs are split into modules, and that a module is a .py file.
  • Use import, from … import … and as, and choose the right one.
  • Say where Python looks for a module and avoid the same-name trap and ModuleNotFoundError.
  • Write your own module with a __name__ == "__main__" test, and use math, random, statistics and secrets from the standard library.
  • ڕوونی بکەیتەوە بۆچی دابەش دەکرێن بۆ و کە فایلێکی .pyـە.
  • import، from … import … و as بەکار بهێنیت و ڕاستەکەیان هەڵبژێریت.
  • بڵێیت Python لە کوێ بەدوای دەگەڕێت و خۆت لە تەڵەی ناوی هاوشێوە و ModuleNotFoundError بپارێزیت.
  • خۆت بە تاقیکردنەوەیەکی __name__ == "__main__" بنووسیت و math، random، statistics و secrets لە بەکار بهێنیت.

Why split a program into modules?بۆچی بەرنامەیەک دابەش دەکرێت بۆ مۆدیوڵەکان؟

Functions let you write a piece of code once and call it many times. Modules take the same idea one step further: you put functions into their own file and use them from other programs. Modularizing makes code easy to maintain and debug, because each file has one clear job, and it lets the code be reused in many programs without copying it.

ڕێگەت پێدەدەن پارچە کۆدێک یەک جار بنووسیت و چەندین جار بانگی بکەیت. هەمان بیرۆکە هەنگاوێک زیاتر دەبەن: دەخەیتە ناو خۆیانەوە و لە ترەوە بەکاریان دەهێنیت. دابەشکردنی کۆد بۆ و ئاسان دەکات، چونکە هەر فایلێک یەک کاری ڕوونی هەیە، هەروەها ڕێگە دەدات کۆدەکە بەبێ کۆپیکردن لە زۆر دووبارە بەکار بهێنرێتەوە.

A mechanic's toolboxسندوقی ئامرازی وەستایەکی ئۆتۆمبێل

A car mechanic in the industrial area does not forge a new spanner for every car. The tools were made once, they sit in a labelled toolbox, and he takes out the one he needs. A module is such a toolbox of functions; import opens it. Python even comes with a big box of ready-made tools — the standard library — and you can fill your own box too.

وەستایەکی ئۆتۆمبێل لە ناوچەی پیشەسازی بۆ هەر ئۆتۆمبێلێک سپانەیەکی نوێ دروست ناکات. ئامرازەکان یەک جار دروست کراون، لە سندوقێکی ناونووسکراودا دانراون و ئەوەی پێویستیەتی دەریدەهێنێت. سندوقێکی لەو جۆرەیە بۆ ؛ import دەیکاتەوە. Python تەنانەت سندوقێکی گەورەی ئامرازی ئامادەی لەگەڵدایە — — و دەتوانیت سندوقی خۆشت پڕ بکەیت.

Where the analogy stops workingسنووری ئەم نموونەیە

Importing does not copy the tools into your file. Python loads the module once and your program uses it by name, so if you change the module file, every program that imports it gets the change.

import ئامرازەکان کۆپی ناکاتە ناو فایلەکەت. Python یەک جار بار دەکات و بە ناو بەکاری دەهێنێت، بۆیە ئەگەر بگۆڕیت، هەموو کە هاوردەی دەکات گۆڕانکارییەکە وەردەگرێت.

Quick checkپشکنینی خێراWhich is not a reason to put functions into a module?کامیان هۆیەک نییە بۆ خستنە ناوی لە ؟

#45 Python Tutorial for Beginners | ModulesTelusko · Englishئینگلیزی · 717K viewsبینین · 16K likesلایک

Why a big program is split into modules: each file has one job, and functions are written once and imported where needed.

بۆچی گەورە دابەش دەکرێت بۆ : هەر یەک کاری هەیە و یەک جار دەنووسرێن و لە هەر شوێنێک پێویست بێت هاوردە دەکرێن.

Whole video (7:20): the problem with one big file (1:14), then modules (3:18).

هەموو ڤیدیۆکە ⁦(7:20)⁩: کێشەی تەنها گەورە ⁦(1:14)⁩، پاشان ⁦(3:18)⁩.

A module is a .py fileمۆدیوڵ فایلێکی .pyـە

In Python a module is simply a file with the .py. Its name is the file name without .py: the file gcd_function.py is the module gcd_function. You place function definitions in the module, and later import it into a program to reuse them.

لە Pythonـدا تەنها بە .py. ناوەکەی ناوی فایلەکەیە بەبێ .py: فایلی gcd_function.py gcd_functionـە. دەخەیتە ناو و دواتر بۆ دووبارە بەکارهێنانەوەیان لە هاوردەی دەکەیت (import).

  • A module can contain more than one function (and variables, and even code that runs). A module of geometry tools might hold square_area, rectangle_area and circle_area.
  • Each function in a module needs a different name. Python does not stop you from reusing a name, but the later def silently replaces the earlier one — see the program below.
  • The file name must be a valid Python name: letters, digits and _, not starting with a digit, no spaces or hyphens. gcd-function.py cannot be imported (import gcd-function is a syntax error). PEP 8 prefers short lowercase names.
  • دەتوانێت زیاتر لە تێدا بێت (هەروەها و تەنانەت کۆدێک کە جێبەجێ دەبێت). ئامرازی ئەندازە دەتوانێت square_area، rectangle_area و circle_area لەخۆ بگرێت.
  • هەر لە پێویستی بە ناوێکی جیاوازە. Python ڕێگری لە دووبارە بەکارهێنانی ناوێک ناکات، بەڵام defـی دواتر بە بێدەنگی شوێنی پێشووتر دەگرێتەوە — بڕوانە خوارەوە.
  • ناوی فایلەکە دەبێت ناوێکی دروستی Python بێت: پیت، ژمارە و _، بە ژمارە دەست پێنەکات، بێ و بێ داش. gcd-function.py هاوردە ناکرێت (import gcd-function ). ⁦PEP 8⁩ ناوی کورتی پیتی بچووکی پێ باشترە.
Two functions with one nameدوو کردار بە یەک ناوsame_name.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def greet():
    print("Hello")


def greet():              # same name: this one replaces the first
    print("Welcome")


greet()
Quick checkپشکنینی خێراWhat is the module name of the file tea_shop.py?ناوی فایلی tea_shop.py چییە؟

Example: a GCD module in two filesنموونە: مۆدیوڵێکی GCD لە دوو فایلدا

The course's example puts a function that finds the greatest common divisor into its own module, gcd_function.py. The module only defines the function; it prints nothing:

نموونەی وانەکە کە دەدۆزێتەوە دەخاتە ناو خۆیەوە، gcd_function.py. تەنها دەناسێنێت؛ هیچ شتێک چاپ ناکات:

The moduleمۆدیوڵەکەgcd_function.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
# Return the gcd of two integers
def gcd(n1, n2):
    result = 1   # Initial gcd is 1
    k = 2        # Possible gcd

    while k <= n1 and k <= n2:
        if n1 % k == 0 and n2 % k == 0:
            result = k   # Update gcd
        k += 1

    return result  # Return gcd
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3-4

result is the best answer so far; k is the next number to try.

result باشترین وەڵامە تا ئێستا؛ k ژمارەی داهاتووە بۆ تاقیکردنەوە.

Lineدێڕی 7

% gives the remainder: 0 means k divides the number exactly.

% دەدات: 0 واتە k ژمارەکە ڕێک دابەش دەکات.

A second file, in the same folder, imports the function and uses it. Running test_gcd.py with the inputs 45 and 75:

فایلێکی دووەم، لە هەمان ، هاوردە دەکات و بەکاری دەهێنێت. جێبەجێکردنی test_gcd.py بە ⁦45⁩ و ⁦75⁩:

The program that uses itئەو بەرنامەیەی بەکاری دەهێنێتtest_gcd.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
from gcd_function import gcd   # Import the gcd function

# Prompt the user to enter two integers
n1 = int(input("Enter the first integer: "))
n2 = int(input("Enter the second integer: "))

print("The greatest common divisor for", n1,
      "and", n2, "is", gcd(n1, n2))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

Import the gcd function from the module gcd_function (the file gcd_function.py).

gcd لە gcd_function (فایلی gcd_function.py) هاوردە بکە.

Lineدێڕی 4-5

int(input()) turns the typed text into a whole number.

int(input()) دەقە نووسراوەکە دەکاتە .

A second run: 16 and 24جێبەجێکردنی دووەم: ⁦16⁩ و ⁦24⁩
Enter the first integer: 16
Enter the second integer: 24
The greatest common divisor for 16 and 24 is 8
A folder called my_project holds two files. Left, gcd_function.py with def gcd(n1, n2): and return result. Right, test_gcd.py with from gcd_function import gcd and a call gcd(n1, n2). An arrow from test_gcd.py to gcd_function.py is labelled 'import'. Below: run test_gcd.py; Python finds gcd_function.py in the same folder.فۆڵدەرێک بە ناوی my_project دوو فایلی تێدایە. لای چەپ gcd_function.py لەگەڵ def gcd(n1, n2): و return result. لای ڕاست test_gcd.py لەگەڵ from gcd_function import gcd و بانگکردنی gcd(n1, n2). تیرێک لە test_gcd.py ـەوە بۆ gcd_function.py بە نووسینی «import». لە خوارەوە: test_gcd.py جێبەجێ بکە؛ Python فایلی gcd_function.py لە هەمان فۆڵدەردا دەدۆزێتەوە.
One file defines, the other imports and uses.فایلێک دەناسێنێت، ئەوی تر هاوردە دەکات و بەکاری دەهێنێت.CêIT
Quick checkپشکنینی خێراWhy can test_gcd.py use gcd although it never writes def gcd?بۆچی test_gcd.py دەتوانێت gcd بەکار بهێنێت هەرچەندە هەرگیز def gcd نانووسێت؟

Example: a GCD module in two filesنموونە: مۆدیوڵێکی GCD لە دوو فایلدا

How gcd() finds the answergcd() چۆن وەڵامەکە دەدۆزێتەوە

The (GCD) of two whole numbers is the largest number that divides both with no remainder. gcd() tries every candidate k = 2, 3, 4, … up to the smaller number. When both remainders n1 % k and n2 % k are 0, k divides both, so it becomes the best answer so far. Watch it for 45 and 75:

بۆ دوو گەورەترین ژمارەیە کە هەردووکیان بەبێ دابەش دەکات. gcd() هەموو ژمارەیەکی پێشنیارکراو k = 2, 3, 4, … تا ژمارە بچووکترەکە تاقی دەکاتەوە. کاتێک هەردوو n1 % k و n2 % k سفر بن، k هەردووکیان دابەش دەکات، بۆیە دەبێتە باشترین وەڵام تا ئەو کاتە. بۆ ⁦45⁩ و ⁦75⁩ سەیری بکە:

Animation of gcd(45, 75). Boxes show n1 = 45, n2 = 75, k and result. result starts at 1. k = 2: 45 % 2 is 1, no. k = 3: both remainders are 0, result becomes 3. k = 4: no. k = 5: yes, result becomes 5. k = 6 to 14: no number divides both (9 divides 45 but not 75). k = 15: yes, result becomes 15. k = 16 to 45: no more common divisors; the loop stops when k reaches 46 and gcd returns 15.
Animation of gcd(45, 75). Boxes show n1 = 45, n2 = 75, k and result. result starts at 1. k = 2: 45 % 2 is 1, no. k = 3: both remainders are 0, result becomes 3. k = 4: no. k = 5: yes, result becomes 5. k = 6 to 14: no number divides both (9 divides 45 but not 75). k = 15: yes, result becomes 15. k = 16 to 45: no more common divisors; the loop stops when k reaches 46 and gcd returns 15.
result is updated at 3, 5 and 15; the last update is the GCD.result لە 3، 5 و ⁦15⁩دا نوێ دەکرێتەوە؛ دوایین نرخ .CêIT
Quick checkپشکنینی خێراWhich values does result take during gcd(45, 75)?لە کاتی gcd(45, 75)ـدا result چ نرخێک وەردەگرێت؟

Four ways to importچوار ڕێگای هاوردەکردن

There are four common forms of the . They differ in which name your program gets:

چوار شێوەی باوی هەن. جیاوازییان لەوەدایە کە کام ناو وەردەگرێت:

import, from … import, asimport، from … import، asimport_forms.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import math                      # 1. the whole module
print(math.sqrt(16))

from math import sqrt, pi        # 2. only some names
print(sqrt(25), pi)

import math as m                 # 3. the module under a short name
print(m.floor(7.8))

from math import gcd as math_gcd # 4. one name under a new name
print(math_gcd(45, 75))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1-2

import math adds only the name math. Each tool is reached with a dot: math.sqrt.

import math تەنها ناوی math زیاد دەکات. هەر ئامرازێک بە خاڵێک دەگەیەنرێت: math.sqrt.

Lineدێڕی 4-5

from … import … copies the chosen names straight into your file: sqrt, not math.sqrt.

from … import … ناوە هەڵبژێردراوەکان ڕاستەوخۆ دەخاتە ناو فایلەکەت: sqrt، نەک math.sqrt.

Lineدێڕی 7-8

as gives the module a shorter name.

as ناوێکی کورتتر دەداتە .

Lineدێڕی 10-11

as can also rename one imported name, for example to avoid a clash with your own gcd.

as دەتوانێت ناوی یەک ناوی هاوردەکراویش بگۆڕێت، بۆ نموونە بۆ ئەوەی لەگەڵ gcdـی خۆت تێکنەچێت.

You writeدەنووسیتName you getئەو ناوەی وەریدەگریتYou callبانگ دەکەیت
import mathmathmath.sqrt(16)
from math import sqrtsqrtsqrt(16)
import math as mmm.sqrt(16)
from math import sqrt as rootrootroot(16)

A common mistake is to import the module and then call the function without the module name:

هەڵەیەکی باو ئەوەیە کە هاوردە بکەیت و پاشان بەبێ ناوی بانگ بکەیت:

import math, then sqrt alone⁦import math⁩، پاشان sqrt بە تەنهاno_prefix.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import math

print(sqrt(16))     # sqrt alone is not known: only the name math was added
Quick checkپشکنینی خێراWhich line makes sqrt(25) work on its own, without math.?کام دێڕ وا دەکات sqrt(25) بە تەنها کار بکات، بەبێ math.؟

Four ways to importچوار ڕێگای هاوردەکردن

Why not from module import *?بۆچی from module import * نا؟

from math import * brings in every public name of math at once. That looks handy, but you cannot see which names arrived, and they can silently replace your own:

from math import * هەموو ناوە گشتییەکانی math بە یەکجار دەهێنێت. ئاسان دیارە، بەڵام ناتوانیت ببینیت کام ناوانە هاتوون و دەتوانن بە بێدەنگی شوێنی ناوەکانی خۆت بگرنەوە:

Your e is gonee ـەکەی خۆت نەماstar_import.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
e = 5                     # your own variable called e
from math import *        # brings in EVERY public name of math, e too
print(e)                  # your 5 has been replaced
Quick checkپشکنینی خێراAfter pi = 3 and then from math import *, what is pi?دوای pi = 3 و پاشان from math import *، pi چییە؟

Where Python looks for a modulePython لە کوێ بەدوای مۆدیوڵێکدا دەگەڕێت

When Python meets import gcd_function, it searches in this order and takes the first match: (1) the modules built into Python itself, such as sys; (2) the folder of the script you run; (3) the folders of the standard library; (4) site-packages, where installed packages live. This list of folders is kept in sys.path. If the module is in none of them, Python stops with ModuleNotFoundError:

کاتێک Python بە import gcd_function دەگات، بەم ڕیزبەندییە دەگەڕێت و یەکەم دۆزینەوە وەردەگرێت: ⁦(1)⁩ ئەو لەناو خودی Pythonـدان، وەک sys؛ ⁦(2)⁩ ئەو جێبەجێی دەکەیت؛ ⁦(3)⁩ ؛ ⁦(4)⁩ site-packages، کە پاکێجە جێگیرکراوەکانی تێدایە. ئەم لیستەی لە sys.pathـدا هەڵگیراوە. ئەگەر لە هیچیاندا نەبێت، Python بە ModuleNotFoundError دەوەستێت:

A typo in the module nameهەڵەی نووسین لە ناوی مۆدیوڵداtypo.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
from gcd_functions import gcd   # a typo in the module name
A search ladder for import random. Step 1, modules built into Python (sys …). Step 2, the folder of the script you run (your own .py files). Step 3, the standard library (random.py, statistics.py …). Step 4, site-packages (packages installed with pip). An arrow goes down the steps; the first match wins. At the bottom: not found anywhere, ModuleNotFoundError. A warning note: a file random.py in your own folder is found at step 2, before the real random module at step 3.پەیژەی گەڕان بۆ import random. هەنگاوی 1، ئەو مۆدیوڵانەی لەناو Pythonـدان (sys …). هەنگاوی 2، فۆڵدەری ئەو دەسنووسەی جێبەجێی دەکەیت (فایلە .py ـەکانی خۆت). هەنگاوی 3، کتێبخانەی ستاندارد (random.py، statistics.py …). هەنگاوی 4، site-packages (ئەو پاکێجانەی بە pip جێگیر کراون). تیرێک بە هەنگاوەکاندا دادەبەزێت؛ یەکەم دۆزینەوە دەباتەوە. لە خوارەوە: لە هیچ شوێنێک نەدۆزرایەوە، ModuleNotFoundError. تێبینییەکی ئاگادارکەرەوە: فایلێکی random.py لە فۆڵدەری خۆتدا لە هەنگاوی 2 دەدۆزرێتەوە، پێش مۆدیوڵی ڕاستەقینەی random لە هەنگاوی 3.
The search order of import: the first match wins.ڕیزبەندیی گەڕانی import: یەکەم دۆزینەوە دەباتەوە.CêIT

Because your own folder comes before the standard library, a file of yours with the same name as a standard module hides the real one. Here a practice file was saved as random.py, next to a dice program:

لەبەر ئەوەی خۆت پێش دێت، فایلێکی خۆت کە هەمان ناوی ستانداردی هەیە دەشارێتەوە. لێرەدا فایلێکی ڕاهێنان بە ناوی random.py پاشەکەوت کراوە، لە تەنیشت زارەوە:

import random finds the wrong file⁦import random⁩ فایلە هەڵەکە دەدۆزێتەوەdice.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import random

print(random.randint(1, 6))
Quick checkپشکنینی خێراA folder holds statistics.py (your homework) and marks.py, which says import statistics and calls statistics.mean(...). What happens? statistics.py (ئەرکی ماڵەوەی خۆت) و marks.pyـی تێدایە، کە دەڵێت import statistics و statistics.mean(...) بانگ دەکات. چی ڕوو دەدات؟

A module runs onceمۆدیوڵ یەک جار جێبەجێ دەبێت

Importing a module runs its file from top to bottom — that is how its def lines create the functions. Python does this only the first time; a second import of the same module in the same program just reuses it:

هاوردەکردنی فایلەکەی جێبەجێ دەکات لە سەرەوە بۆ خوارەوە — بەم شێوەیە دێڕەکانی defـی دروست دەکەن. Python ئەمە تەنها یەکەم جار دەکات؛ importـی دووەمی هەمان لە هەمان تەنها دووبارە بەکاری دەهێنێتەوە:

A module with a print at the topمۆدیوڵێک کە printـێکی لە سەرەوەیەgreetings.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
print("greetings is loading ...")


def hello(name):
    print("Hello,", name)
Imported twice, loaded onceدوو جار هاوردە کراوە، یەک جار بار کراوەmain.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import greetings
import greetings          # a second import does not run the file again

greetings.hello("Rezan")
greetings.hello("Lana")
Quick checkپشکنینی خێراWhy does greetings is loading ... appear only once?بۆچی greetings is loading ... تەنها یەک جار دەردەکەوێت؟

if __name__ == "__main__":⁦if __name__ == "__main__⁩": کۆدێک کە هاوردەکردن جێیدەهێڵێت

While you write a module, you often add a quick test at the bottom. But because importing runs the whole file, that test also runs in every program that imports the module:

کاتێک دەنووسیت، زۆرجار تاقیکردنەوەیەکی خێرا لە خوارەوە زیاد دەکەیت. بەڵام لەبەر ئەوەی هاوردەکردن هەموو فایلەکە جێبەجێ دەکات، ئەو تاقیکردنەوەیە لە هەموو کە هاوردە دەکاتیش جێبەجێ دەبێت:

A module with a test lineمۆدیوڵێک بە دێڕێکی تاقیکردنەوەtea_tools.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def bill(glasses, price=500):
    return glasses * price


# a quick test of the function
print("Test:", bill(3))
The test output appears in the shop programدەرخستەی تاقیکردنەوەکە لە بەرنامەی دوکانەکەدا دەردەکەوێتshop.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import tea_tools

print("Customer pays", tea_tools.bill(4))

Every module has a variable __name__. When you run a file directly, Python sets its __name__ to "__main__"; when the file is imported, __name__ is the module's name:

هەموو __name__ـی هەیە. کاتێک فایلێک ڕاستەوخۆ جێبەجێ دەکەیت، Python __name__ـەکەی دەکاتە "__main__"؛ کاتێک فایلەکە هاوردە دەکرێت، __name__ ناوی :

show_name.py holds one line: print("__name__ is", __name__)⁦show_name.py⁩ یەک دێڕی تێدایە: ⁦print("__name__ is", __name__)⁩use_show_name.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import show_name

print("This file's __name__ is", __name__)

So put the test (or a call of main()) under if __name__ == "__main__":. It runs when you run the module itself and is skipped when another program imports it:

بۆیە تاقیکردنەوەکە (یان بانگکردنی main()) لە ژێر if __name__ == "__main__": دابنێ. کاتێک خودی جێبەجێ دەکەیت کار دەکات و کاتێک تر هاوردەی دەکات جێدەهێڵرێت:

The guarded version, run directlyوەشانە پارێزراوەکە، ڕاستەوخۆ جێبەجێکراوtea_tools.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def bill(glasses, price=500):
    return glasses * price


if __name__ == "__main__":       # True only when this file is run directly
    print("Test:", bill(3))
… and imported: no test output… و هاوردەکراو: هیچ دەرخستەیەکی تاقیکردنەوە نییەshop.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import tea_tools

print("Customer pays", tea_tools.bill(4))
Quick checkپشکنینی خێراA file tools.py is imported by app.py. Inside tools.py, what is __name__?فایلی tools.py لەلایەن app.pyـەوە هاوردە دەکرێت. لەناو tools.pyـدا __name__ چییە؟

Python if __name__ == '__main__': Visually ExplainedVisually Explained · Englishئینگلیزی · 643K viewsبینین · 28K likesلایک

What __name__ is, when it equals "__main__", and why test code goes under if __name__ == "__main__" so it does not run on import.

__name__ چییە، کەی دەبێتە "__main__" و بۆچی کۆدی دەخرێتە ژێر if __name__ == "__main__": تا لە کاتی هاوردەکردندا جێبەجێ نەبێت.

Whole video (6:06): what __name__ is (0:13), when it is '__main__' (1:01), using it for test code (3:05).

هەموو ڤیدیۆکە ⁦(6:06)⁩: __name__ چییە ⁦(0:13)⁩، کەی دەبێتە '__main__' ⁦(1:01)⁩ و بەکارهێنانی بۆ کۆدی ⁦(3:05)⁩.

The standard library: modules that come with Pythonکتێبخانەی ستاندارد: ئەو مۆدیوڵانەی لەگەڵ Python دێن

Python is installed together with a large : hundreds of ready-made modules for maths, random numbers, dates, files, the internet and much more. You import them exactly like your own modules. First math; the next screens show random, secrets and statistics:

کاتێک Python جێگیر دەکەیت، گەورەشی لەگەڵدا دێت: سەدان ئامادە بۆ بیرکاری، ، بەروار، فایل، ئینتەرنێت و زۆری تر. وەک خۆت هاوردەیان دەکەیت. سەرەتا math؛ پەڕەکانی دواتر random، secrets و statistics پیشان دەدەن:

Definitionپێناسە

The set of ready-made that comes with a programming language, so you can use them without installing anything. Python's includes math, random, datetime and many more.

کۆمەڵێک ئامادەیە کە لەگەڵ دێت، بۆیە بەبێ هیچ شتێک دەتوانیت بەکاریان بهێنیت. ئەوەی Python math، random، datetime و زۆری تر لەخۆ دەگرێت.

math: the GCD is already theremath: گەورەترین بەشدراوی هاوبەش پێشتر هەیەstd_math.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import math

print(math.sqrt(81))
print(math.pi)
print(math.gcd(45, 75))     # the GCD is already in the standard library
print(math.factorial(5))
print(math.ceil(4.2))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5

The same answer as our gcd_function module — writing it ourselves taught how it works.

هەمان وەڵامی gcd_functionـی خۆمان — نووسینی بە دەستی خۆمان فێری کردین چۆن کار دەکات.

Lineدێڕی 6

: 5!=5×4×3×2×1=1205! = 5 \times 4 \times 3 \times 2 \times 1 = 120.

: 5!=5×4×3×2×1=1205! = 5 \times 4 \times 3 \times 2 \times 1 = 120.

More math tools, such as floor, ceil, sin and cos, are in The math toolbox.

ئامرازی زیاتری math، وەک floor، ceil، sin و cos، لە ئامرازەکانی mathدان.

Quick checkپشکنینی خێراWhich line lists all the names inside the math module?کام دێڕ هەموو ناوەکانی ناو math ڕیز دەکات؟

The standard library: modules that come with Pythonکتێبخانەی ستاندارد: ئەو مۆدیوڵانەی لەگەڵ Python دێن

The random moduleمۆدیوڵی random

random makes numbers that look random: for games, dice, quizzes and simulations. Five tools cover most needs. With random.seed(7) at the start, every run gives the same results, which makes a program easy to test:

random ژمارەی وا دروست دەکات کە هەڕەمەکی دیارن: بۆ یاری، زار، پرسیار و لاساییکردنەوە. پێنج ئامراز زۆربەی پێویستییەکان پڕ دەکەنەوە. بە random.seed(7) لە سەرەتادا، هەموو جێبەجێکردنێک هەمان ئەنجام دەدات، ئەمەش تاقیکردنەوەی ئاسان دەکات:

random: five tools, made repeatable with a seedrandom: پێنج ئامراز، کە بە تۆوی هەڕەمەکی دووبارە دەکرێنەوەstd_random.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import random

random.seed(7)                         # a fixed start, so this run can be repeated
print(random.random())                 # a float from 0.0 up to, but not including, 1.0
print(random.randint(1, 6))            # 1 to 6, both ends included
print(random.randrange(0, 101, 25))    # 0, 25, 50, 75 or 100: like range(), 101 is left out
print(random.choice(["tea", "coffee", "juice"]))
names = ["Aram", "Shilan", "Karwan", "Dilan"]
random.shuffle(names)                  # mixes the list in place
print(names)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

random() can give 0.0 but never 1.0.

random() دەتوانێت ⁦0.0⁩ بدات، بەڵام هەرگیز ⁦1.0⁩ نادات.

Lineدێڕی 5

randint(1, 6) includes both ends: 1 and 6 are both possible.

randint(1, 6) هەردوو سەر لەخۆ دەگرێت: 1 و 6 هەردووکیان دەکرێن.

Lineدێڕی 6

randrange(start, stop, step) picks from range(start, stop, step), so the stop itself is never chosen.

randrange(start, stop, step) لە range(start, stop, step) هەڵدەبژێرێت، بۆیە خودی stop هەرگیز هەڵنابژێردرێت.

Lineدێڕی 9

shuffle changes the list itself and returns None.

shuffle خودی دەگۆڕێت و None دەگەڕێنێتەوە.

ToolئامرازGivesچی دەداتPossible resultsئەنجامە گونجاوەکان
random.random()a floatfrom 0.0 up to, not including, 1.0لە ⁦0.0⁩ تا ⁦1.0⁩، بێ خودی ⁦1.0⁩
random.randint(1, 6)a whole number1 to 6, both ends included1 تا 6، هەردوو سەرەکەوە
random.randrange(0, 101, 25)a number from a rangeژمارەیەک لە rangeـێک0, 25, 50, 75, 100
random.choice(items)one itemیەک دانەany item of a list or stringهەر دانەیەکی یان
random.shuffle(items)nothing (None)هیچ (None)the list itself is mixedخودی تێکەڵ دەکرێت

You first used random for dice in Lab 1, Task 3.

یەکەم جار randomـت بۆ زار لە تاقیگەی 1، ئەرکی 3 بەکار هێنا.

Quick checkپشکنینی خێراWhich call can give the number 6?کام بانگکردن دەتوانێت ژمارە 6 بدات؟

Generate random numbers in Python 🎲Bro Code · Englishئینگلیزی · 148K viewsبینین · 3.4K likesلایک · Partبەشی 0:00–4:32 (ofلە 8:02)

The random module's main tools: random(), randint(), choice() and shuffle(), shown with dice, rock-paper-scissors and a deck of cards.

ئامرازە سەرەکییەکانی random: random()، randint()، choice() و shuffle()، بە نموونەی بەردەزار، بەرد-کاغەز-مقەست و دەستەیەک کارتی یاری.

Watch 0:00–4:32, the random module; the number-guessing game after it is optional.

لە ⁦0:00⁩ تا ⁦4:32⁩ سەیر بکە: random؛ یاریی مەزەندەکردنی ژمارە کە دوای ئەوە دێت ئارەزوومەندانەیە.

The standard library: modules that come with Pythonکتێبخانەی ستاندارد: ئەو مۆدیوڵانەی لەگەڵ Python دێن

random is not for passwords: secretsrandom بۆ تێپەڕەوشە نییە: secrets

The numbers from random are pseudo-random: a formula produces them from a starting value, the . That is why random.seed(7) repeats the same "random" results — useful for testing games and simulations. But anyone who learns the seed or enough outputs can predict the next numbers. For passwords, reset codes and security tokens, Python's documentation says to use the secrets module instead:

ئەو ژمارانەی random دەیاندات وەک هەڕەمەکین: هاوکێشەیەک لە سەرەتاییەوە دروستیان دەکات، کە . بۆیە random.seed(7) هەمان ئەنجامی «هەڕەمەکی» دووبارە دەکاتەوە — بۆ تاقیکردنەوەی یاری و لاساییکردنەوە بەسوودە. بەڵام هەر کەسێک یان ژمارەیەکی زۆر لە ئەنجامەکان بزانێت دەتوانێت ژمارەکانی داهاتوو پێشبینی بکات. بۆ ، کۆدی گۆڕینەوە و نیشانەی ئاسایش، بەڵگەنامەکانی Python دەڵێن لەبری ئەوە secrets بەکار بهێنە:

Unpredictable values for securityنرخی پێشبینینەکراو بۆ ئاسایشsecrets_demo.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import secrets

print(secrets.token_hex(8))          # 16 hex digits, e.g. for a reset link
print(secrets.randbelow(1000000))    # a 6-digit-or-less code
print(secrets.choice("ABCDEFGHJKLMNPQRSTUVWXYZ23456789"))
ModuleGood forباشە بۆNot forنەک بۆ
randomGames, dice, simulations, shuffling a quiz; repeatable with a seedیاری، زار، لاساییکردنەوە، تێکەڵکردنی پرسیارەکان؛ بە دووبارە دەبێتەوەPasswords, codes, tokens، کۆد، نیشانەی ئاسایش
secretsPasswords, one-time passwords, reset links, tokens، ، بەستەری گۆڕینەوە، نیشانەی ئاسایشResults you want to repeat exactlyئەنجامێک کە دەتەوێت ڕێک دووبارە ببێتەوە

Why a seed that can be guessed is dangerous, with a worked attack on a login code, is shown in When chance must stay secret. And shuffling a few known characters does not make a password strong either: see Shuffling is not enough.

بۆچی کە بتوانرێت مەزەندە بکرێت مەترسیدارە، لەگەڵ نموونەیەکی هێرش بۆ سەر کۆدێکی ، لە کاتێک ڕێکەوت دەبێت نهێنی بمێنێتەوە پیشان دراوە. هەروەها تێکدانی ڕیزبەندیی چەند ناسراو بەهێز دروست ناکات: بڕوانە تێکدانی ڕیزبەندی بەس نییە.

Quick checkپشکنینی خێراA login page must send a 6-digit code by SMS. Which module should make the code?پەڕەیەکی دەبێت کۆدێکی 6 ژمارەیی بە بنێرێت. کام دەبێت کۆدەکە دروست بکات؟

The standard library: modules that come with Pythonکتێبخانەی ستاندارد: ئەو مۆدیوڵانەی لەگەڵ Python دێن

The statistics moduleمۆدیوڵی statistics

statistics works out averages for you, so you need not write the loop yourself. What the , the and the are, and when to use which, is taught in the Statistics course (Median and mode in Python). Here are the Python calls:

statistics ناوەندەکان بۆت دەژمێرێت، بۆیە پێویست ناکات خۆت بنووسیت. ، و چین و کەی کامیان بەکار دێت، لە کۆرسی ئاماردا فێر دەکرێت (ناوەڕاستە و باو لە Pythonـدا). لێرەدا بانگکردنەکانی Python دەبینیت:

statistics: averages ready-madestatistics: ناوەندی ئامادەstd_statistics.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import statistics

marks = [12, 46, 38]
print(statistics.mean(marks))               # Lab 2's average, ready-made
print(statistics.median([3, 9, 4, 7, 5]))
print(statistics.mode([3, 5, 5, 7, 5, 9]))  # the value that appears most often
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

The of Lab 2's numbers 12, 46 and 38 is 32.

ژمارەکانی تاقیگەی 2، واتە ⁦12⁩، ⁦46⁩ و ⁦38⁩، ⁦32⁩ـە.

Lineدێڕی 6

The is the most common value: 5 appears three times.

بەربڵاوترین نرخە: 5 سێ جار هاتووە.

Quick checkپشکنینی خێراWhich line gives the mean of a list of marks without writing your own loop?کام دێڕ لیستێکی نمرە دەدات بەبێ ئەوەی خۆت بنووسیت؟

Writing your own moduleنووسینی مۆدیوڵی خۆت

  1. Create the fileفایلەکە دروست بکە

    Make a new file with a valid lowercase name ending in .py, for example shapes.py, in the same folder as your program.

    فایلێکی نوێ بە ناوێکی دروستی پیتی بچووک کە بە .py کۆتایی دێت دروست بکە، بۆ نموونە shapes.py، لە هەمان کە تێدایە.

  2. Put definitions in itناساندنەکانی کردار تێ بخە

    Write the functions (with docstrings). Avoid code that runs on import; put tests under if __name__ == "__main__":.

    بنووسە (لەگەڵ ). خۆت لە کۆدێک بپارێزە کە لە کاتی هاوردەکردندا جێبەجێ دەبێت؛ تاقیکردنەوەکان لە ژێر if __name__ == "__main__": دابنێ.

  3. Import and use itهاوردەی بکە و بەکاری بهێنە

    In your program write import shapes and call shapes.square_area(4) — or from shapes import square_area.

    لە بنووسە import shapes و shapes.square_area(4) بانگ بکە — یان from shapes import square_area.

A module with three functions — and its own importمۆدیوڵێک بە سێ کردار — و importـی خۆیshapes.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
"""Area functions for simple shapes."""
import math


def square_area(side):
    return side * side


def rectangle_area(width, height):
    return width * height


def circle_area(radius):
    return math.pi * radius ** 2
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

A module can start with a docstring that says what it is for.

دەتوانێت بە دەست پێبکات کە دەڵێت بۆ چییە.

Lineدێڕی 2

A module may import other modules: shapes uses math.pi.

دەتوانێت تر هاوردە بکات: shapes لە math.pi سوود وەردەگرێت.

Using the moduleبەکارهێنانی مۆدیوڵەکەmain.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import shapes

print(shapes.__doc__)
print(shapes.square_area(4))
print(shapes.rectangle_area(3, 5))
print(round(shapes.circle_area(2), 2))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

A module's docstring is kept in __doc__, just like a function's (docstrings); help(shapes) shows it too.

لە __doc__ـدا هەڵدەگیرێت، هەر وەک هی (زنجیرەنووسەی بەڵگەنامە)؛ help(shapes)ـیش پیشانی دەدات.

Quick checkپشکنینی خێراshapes.py and main.py are in the same folder. Which line in main.py lets it call circle_area(2) without a prefix?shapes.py و main.py لە هەمان . کام دێڕ لە main.pyـدا ڕێگە دەدات circle_area(2) بەبێ پێشگر بانگ بکات؟

Common mistakesهەڵە باوەکان

MistakeهەڵەWhat happensچی ڕوو دەداتFixچارەسەر
Writing .py in the import: import shapes.pyنووسینی .py لە import: import shapes.pyModuleNotFoundError: No module named 'shapes.py'; 'shapes' is not a packageimport shapes
A typo, or the module is in another folderهەڵەی نووسین، یان لە تردایەModuleNotFoundErrorCheck the spelling; keep the module next to your scriptنووسینەکە بپشکنە؛ لە تەنیشت دابنێ
import math, then sqrt(16)import math، پاشان sqrt(16)NameError: name 'sqrt' is not definedmath.sqrt(16), or from math import sqrtmath.sqrt(16)، یان from math import sqrt
Naming your file like a standard module (random.py)ناونانی فایلەکەت وەک ستاندارد (random.py)AttributeError: module 'random' has no attribute 'randint'Rename your fileناوی فایلەکەت بگۆڕە
A hyphen or space in a module name (my-tools.py)داش یان لە ناوی (my-tools.py)Cannot be importedهاوردە ناکرێتmy_tools.py
Test code at the bottom of a moduleکۆدی تاقیکردنەوە لە خوارەوەی It runs in every program that imports the moduleلە هەموو کە هاوردە دەکات جێبەجێ دەبێتif __name__ == "__main__":
from module import *from module import *Unknown names arrive and may replace yoursناوی نەناسراو دێن و لەوانەیە شوێنی ناوەکانی تۆ بگرنەوەImport the module or the names you need یان ئەو ناوانەی پێویستن هاوردە بکە
Using random for passwords or codesبەکارهێنانی random بۆ یان کۆدPredictable valuesژمارەی پێشبینیکراوsecrets

Exercisesڕاهێنانەکان

ExerciseڕاهێنانA converter moduleمۆدیوڵێکی گۆڕین

Write a module converter.py with two functions: km_to_miles(km) (1 km is 0.621371 miles) and celsius_to_fahrenheit(c) (F=C×9/5+32F = C \times 9 / 5 + 32). Add a test under if __name__ == "__main__":. Then write trip.py in the same folder that imports both functions and prints the miles for 85 km (rounded to 1 decimal) and the Fahrenheit value of 45 °C.

بە ناوی converter.py بنووسە بە دوو : km_to_miles(km) (⁦1 km⁩ دەکاتە ⁦0.621371⁩ میل) و celsius_to_fahrenheit(c) (F=C×9/5+32F = C \times 9 / 5 + 32). تاقیکردنەوەیەک لە ژێر if __name__ == "__main__": زیاد بکە. پاشان trip.py لە هەمان بنووسە کە هەردوو هاوردە بکات و میلی ⁦85 km⁩ (بە یەک ژمارەی دوای خاڵ) و نرخی فەهرەنهایتی ⁦45 °C⁩ چاپ بکات.

Show answerوەڵامەکە پیشان بدە
Run directly, the test runsڕاستەوخۆ جێبەجێکراو، تاقیکردنەوەکە کار دەکاتconverter.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
"""Small unit converters."""


def km_to_miles(km):
    return km * 0.621371


def celsius_to_fahrenheit(c):
    return c * 9 / 5 + 32


if __name__ == "__main__":
    print(km_to_miles(10))
    print(celsius_to_fahrenheit(40))
Imported: only trip.py's lines appearهاوردەکراو: تەنها دێڕەکانی ⁦trip.py⁩ دەردەکەونtrip.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
from converter import km_to_miles, celsius_to_fahrenheit

distance = 85        # kilometres
print(round(km_to_miles(distance), 1), "miles")
print(celsius_to_fahrenheit(45), "F")
ExerciseڕاهێنانPredict the outputدەرخستەکە پێشبینی بکە

greetings.py starts with print("greetings is loading ...") and defines hello(name). What does this main.py print, and how many times does the loading line appear?

greetings.py بە print("greetings is loading ...") دەست پێدەکات و hello(name) دەناسێنێت. ئەم main.pyـیە چی چاپ دەکات و دێڕی بارکردنەکە چەند جار دەردەکەوێت؟

main.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import greetings
import greetings          # a second import does not run the file again

greetings.hello("Rezan")
greetings.hello("Lana")
Show answerوەڵامەکە پیشان بدە
Outputدەرئەنجام
greetings is loading ...
Hello, Rezan
Hello, Lana

Once: the second import finds the module already loaded.

یەک جار: importـی دووەم بە بارکراوی دەدۆزێتەوە.

ExerciseڕاهێنانGCD by hand, then by the libraryگەورەترین بەشدراوی هاوبەش بە دەست، پاشان بە کتێبخانە

Follow gcd(36, 60) by hand: list the values of k for which result changes. Then check your answer with math.gcd(36, 60).

بە دەست بەدوای gcd(36, 60)ـدا بچۆ: ئەو نرخانەی k بنووسە کە تێیاندا result دەگۆڕێت. پاشان وەڵامەکەت بە math.gcd(36, 60) بپشکنە.

Show answerوەڵامەکە پیشان بدە

result changes when k is 2, 3, 4, 6 and 12 (the common divisors of 36 and 60 after 1). The loop goes on until k is 36 and finds nothing larger, so the answer is 12, and math.gcd(36, 60) also gives 12.

result کاتێک دەگۆڕێت کە k دەبێتە 2، 3، 4، 6 و ⁦12⁩ (بەشکەرە هاوبەشەکانی ⁦36⁩ و ⁦60⁩ دوای ⁦1⁩). تا k دەبێتە ⁦36⁩ بەردەوام دەبێت و هیچ ژمارەیەکی گەورەتر نادۆزێتەوە، بۆیە وەڵامەکە ⁦12⁩ـە و math.gcd(36, 60)ـیش ⁦12⁩ دەدات.

ExerciseڕاهێنانWhy does the dice program fail?بۆچی بەرنامەی زارەکە شکست دەهێنێت؟

Dilan's folder contains random.py (her notes on randomness) and dice.py with import random and print(random.randint(1, 6)). Running dice.py prints her notes' text and then AttributeError: module 'random' has no attribute 'randint'. Explain and fix.

دیلان random.py (تێبینییەکانی دەربارەی هەڕەمەکی) و dice.pyـی تێدایە کە import random و print(random.randint(1, 6))ـی تێدایە. جێبەجێکردنی dice.py دەقی تێبینییەکانی چاپ دەکات و پاشان AttributeError: module 'random' has no attribute 'randint'. ڕوونی بکەرەوە و چاکی بکەرەوە.

Show answerوەڵامەکە پیشان بدە

Python searches the script's folder before the standard library, so import random loads her own random.py, which has no randint. Rename her file (for example random_notes.py) and run dice.py again; the old copy in __pycache__ is ignored once random.py is gone. (Python 3.13 and later even suggest the rename in the error message.)

Python پێش لە دەگەڕێت، بۆیە import random فایلی random.pyـی خۆی بار دەکات، کە randintـی تێدا نییە. ناوی فایلەکەی بگۆڕە (بۆ نموونە random_notes.py) و دیسان dice.py جێبەجێ بکە؛ کۆپییە کۆنەکەی ناو __pycache__ کاتێک random.py نەما پشتگوێ دەخرێت. (⁦Python 3.13⁩ و دواتر تەنانەت لە پەیامی گۆڕینی ناوەکە پێشنیار دەکەن.)

Quick checkپشکنینی خێراWhich statement about modules is true?کام ڕستە دەربارەی ڕاستە؟

Exercisesڕاهێنانەکان

Exercises: tools from the standard libraryڕاهێنان: ئامرازەکانی کتێبخانەی ستاندارد

Exerciseڕاهێنانpow() or math.pow()? random() or randint()?pow() یان math.pow()؟ random() یان randint()؟

Answer first, then run the program to check. (1) What do pow(2, 10), math.pow(2, 10) and pow(2, 10, 1000) give, and why is only one of the first two a float? (2) A program needs a whole number from 1 to 5. Should it use random.random() or random.randint(1, 5), and why?

سەرەتا وەڵام بدەرەوە، پاشان جێبەجێ بکە بۆ پشکنین. ⁦(1)⁩ pow(2, 10)، math.pow(2, 10) و pow(2, 10, 1000) چی دەدەن و بۆچی تەنها یەکێک لە دوو یەکەمەکە ؟ ⁦(2)⁩ پێویستی بە هەیە لە 1 تا 5. random.random() بەکار بهێنێت یان random.randint(1, 5)؟ بۆچی؟

Show answerوەڵامەکە پیشان بدە
pow_question.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import math
import random

print(pow(2, 10), math.pow(2, 10))   # an int and a float
print(pow(2, 10, 1000))              # (2 ** 10) % 1000
print(pow(3, 40))                    # an int stays exact
print(math.pow(3, 40))               # a float is rounded

random.seed(5)
print(random.random())               # a float, never a whole number from 1 to 5
print(random.randint(1, 5))          # 1, 2, 3, 4 or 5
  • (1) The built-in pow() works like **: with whole numbers it gives an exact whole number, and with a third argument it gives the remainder, so pow(2, 10, 1000) is (2 ** 10) % 1000, which is 24. math.pow() always turns its numbers into floats, so it answers 1024.0; and a big float is rounded, as math.pow(3, 40) shows. More in Python's built-in toolbox and The math toolbox.
  • (2) random.randint(1, 5): it gives exactly one of the whole numbers 1, 2, 3, 4 and 5. random.random() gives a float from 0 up to 1, which you would first have to stretch and cut, int(random.random() * 5) + 1.
  • ⁦(1)⁩ pow()ـی ئامادە وەک ** کار دەکات: لەگەڵ ئەنجامێکی تەواو و ورد دەدات و بە سێیەم دەدات، بۆیە pow(2, 10, 1000) هەمان (2 ** 10) % 1000ـە، واتە ⁦24⁩. math.pow() هەمیشە ژمارەکانی دەکاتە ، بۆیە وەڵامەکەی 1024.0ـە؛ هەروەها گەورە خڕ دەکرێتەوە، وەک math.pow(3, 40) پیشانی دەدات. زیاتر لە سندوقی ئامرازی کردارە ئامادەکان و ئامرازەکانی math.
  • ⁦(2)⁩ random.randint(1, 5): ڕێک یەکێک لە 1، 2، 3، 4 و 5 دەدات. random.random() لە 0 تا 1 دەدات، کە دەبوو سەرەتا گەورەی بکەیت و بیبڕیت: int(random.random() * 5) + 1.
ExerciseڕاهێنانA lucky drawتیروپشک

A school festival sells 600 numbered raffle tickets. Write draw_ticket(tickets) that returns a random ticket number from 1 to tickets, then draw the first, second and third prize. Use a seed while you test. Can the same ticket win twice?

ئاهەنگێکی قوتابخانە ⁦600⁩ بلیتی ژمارەدار بۆ تیروپشک دەفرۆشێت. draw_ticket(tickets) بنووسە کە ژمارەی بلیتێکی هەڕەمەکی لە 1 تا tickets بگەڕێنێتەوە، پاشان خەڵاتی یەکەم، دووەم و سێیەم دیاری بکە. لە کاتی تاقیکردنەوەدا بەکار بهێنە. ئایا هەمان بلیت دەتوانێت دوو جار ببات؟

Hintئاماژە

random.randint(1, tickets) includes both ends.

random.randint(1, tickets) هەردوو سەر لەخۆ دەگرێت.

Show answerوەڵامەکە پیشان بدە
lucky_draw.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import random


def draw_ticket(tickets):
    """Return one winning ticket number from 1 to tickets."""
    return random.randint(1, tickets)


random.seed(2026)               # only for testing: remove it on the festival day
for prize in ["first", "second", "third"]:
    print("The", prize, "prize goes to ticket", draw_ticket(600))

print(random.sample(range(1, 601), 3))   # three different tickets at once

Yes: every call is independent, so a ticket can come out twice. random.sample(range(1, 601), 3) picks three different tickets at once (the last line). Remove the seed on the festival day: with it, anyone who has the program knows the winners in advance. For a draw with real money, use secrets (see random is not for passwords).

بەڵێ: هەموو بانگکردنێک سەربەخۆیە، بۆیە بلیتێک دەتوانێت دوو جار دەربچێت. random.sample(range(1, 601), 3) سێ بلیتی جیاواز پێکەوە هەڵدەبژێرێت (دوایین دێڕ). لە ڕۆژی ئاهەنگەکەدا لاببە: بە بوونی ئەو، هەر کەسێک لا بێت پێشوەختە براوەکان دەزانێت. بۆ تیروپشکێک کە پارەی ڕاستەقینەی تێدایە، secrets بەکار بهێنە (بڕوانە random بۆ تێپەڕەوشە نییە).

Quick checkپشکنینی خێراWhat does pow(5, 2, 7) give?pow(5, 2, 7) چی دەدات؟

Exercisesڕاهێنانەکان

Exercise: a menu calculatorڕاهێنان: حاسیبەیەک بە مێنیو

ExerciseڕاهێنانA calculator built from functionsحاسیبەیەک کە لە کردارەکان دروست کراوە

Show a menu once: 1 add, 2 subtract, 3 multiply, 4 divide, 5 log10, 6 sin, 7 cos, 0 quit. Then keep asking for a choice until the user types 0. Write one small function for each job. sin and cos take an angle in degrees, and dividing by 0 must not crash the program.

یەک جار پیشان بدە: 1 کۆکردنەوە، 2 لێدەرکردن، 3 لێکدان، 4 دابەشکردن، ⁦5 log10⁩، ⁦6 sin⁩، ⁦7 cos⁩، 0 دەرچوون. پاشان داوای هەڵبژاردن بکە تا 0 دەنووسێت. بۆ هەر کارێک بچووک بنووسە. sin و cos گۆشەیەک بە وەردەگرن و دابەشکردن بەسەر 0دا نابێت بوەستێنێت.

Hintئاماژە

math.sin() and math.cos() expect radians: convert with math.radians(), and round to 4 decimals, because math.sin(math.radians(30)) is 0.49999999999999994. read_two() can return two numbers at once (several values).

math.sin() و math.cos() گۆشە بە وەردەگرن: بە math.radians() بیگۆڕە و تا 4 ژمارەی دوای خاڵ خڕی بکەرەوە، چونکە math.sin(math.radians(30)) دەکاتە ⁦0.49999999999999994⁩. read_two() دەتوانێت دوو ژمارە پێکەوە بگەڕێنێتەوە (چەند نرخێک).

Show answerوەڵامەکە پیشان بدە
calculator.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import math


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):
    return a / b


def log10_of(x):
    return math.log10(x)


def sin_of(degrees):
    return round(math.sin(math.radians(degrees)), 4)


def cos_of(degrees):
    return round(math.cos(math.radians(degrees)), 4)


def read_two():
    a = float(input("First number: "))
    b = float(input("Second number: "))
    return a, b


def main():
    print("1 add  2 subtract  3 multiply  4 divide  5 log10  6 sin  7 cos  0 quit")
    choice = ""
    while choice != "0":
        choice = input("Choice: ")
        if choice == "1":
            a, b = read_two()
            print("Answer:", add(a, b))
        elif choice == "2":
            a, b = read_two()
            print("Answer:", subtract(a, b))
        elif choice == "3":
            a, b = read_two()
            print("Answer:", multiply(a, b))
        elif choice == "4":
            a, b = read_two()
            if b == 0:
                print("You cannot divide by 0.")
            else:
                print("Answer:", divide(a, b))
        elif choice == "5":
            x = float(input("A number above 0: "))
            print("Answer:", log10_of(x))
        elif choice == "6":
            print("Answer:", sin_of(float(input("Angle in degrees: "))))
        elif choice == "7":
            print("Answer:", cos_of(float(input("Angle in degrees: "))))
        elif choice != "0":
            print("Please choose 0 to 7.")
    print("Goodbye!")


main()
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4-21

One small function per operation: each is easy to test alone.

بۆ هەر کارێک بچووک: هەر یەکەیان بە تەنها ئاسان تاقی دەکرێتەوە.

Lineدێڕی 24-29

Degrees are turned into radians first; round(…, 4) hides the tiny float error.

سەرەتا دەکرێنە ؛ round(…, 4) هەڵە بچووکەکەی دەشارێتەوە.

Lineدێڕی 32-35

Returns two values; the caller unpacks them with a, b = read_two().

دوو نرخ دەگەڕێنێتەوە؛ بە a, b = read_two() لێکیان دەکاتەوە.

Lineدێڕی 54-57

Check for 0 before dividing.

پێش دابەشکردن 0 بپشکنە.

A sample run: the user chose 3 (7 and 5), 4 (9 and 0), 5 (1000), 6 (30 degrees), 7 (60 degrees) and finally 0.

نموونەیەکی جێبەجێکردن: ⁦3 (7⁩ و ⁦5⁩)، ⁦4 (9⁩ و ⁦0⁩)، ⁦5 (1000)⁩، ⁦6 (30⁩ )، ⁦7 (60⁩ ) و لە کۆتاییدا 0ـی هەڵبژارد.

Quick checkپشکنینی خێراWhy does math.sin(90) not give 1?بۆچی math.sin(90) ژمارە 1 نادات؟

Exercisesڕاهێنانەکان

Exercise: a bigger shapes moduleڕاهێنان: مۆدیوڵێکی گەورەتری shapes

ExerciseڕاهێنانFive shapes in one moduleپێنج شێوە لە یەک مۆدیوڵدا

Extend shapes.py from Writing your own module: for the square, the rectangle, the triangle and the circle write an area and a perimeter function (the perimeter of a circle is its circumference, 2πr2 \pi r); for a cylinder, such as a water tank, write its volume and its surface area. Then write garden.py in the same folder. It imports the module and prints the measures of a square of side 5, a 4 by 6 rectangle, a 3-4-5 triangle, a circle of radius 3 and a tank of radius 2 and height 10.

shapes.pyـی نووسینی مۆدیوڵی خۆت فراوان بکە: بۆ چوارگۆشە، لاکێشە، سێگۆشە و بازنە ڕووبەر و چێوە بنووسە (چێوەی بازنە بریتییە لە 2πr2 \pi r)؛ بۆ ئەستوانەیەک، وەک تانکی ئاو، قەبارە و ڕووبەری ڕووکارەکەی بنووسە. پاشان garden.py لە هەمان بنووسە. هاوردە دەکات و پێوانەکانی چوارگۆشەیەک بە لای 5، لاکێشەیەکی 4 لە 6، سێگۆشەیەکی ⁦3-4-5⁩، بازنەیەک بە نیوەتیرەی 3 و تانکێک بە نیوەتیرەی 2 و بەرزیی ⁦10⁩ چاپ دەکات.

Hintئاماژە

Reuse functions inside the module: a cylinder's volume is circle_area(radius) * height, and its surface is two circles plus the side, circle_perimeter(radius) * height.

لەناو دووبارە بەکار بهێنەوە: قەبارەی ئەستوانە circle_area(radius) * heightـە و ڕووکارەکەی دوو بازنەیە لەگەڵ لاتەنیشتەکەی، circle_perimeter(radius) * height.

Show answerوەڵامەکە پیشان بدە
The module (run directly, its test runs)مۆدیوڵەکە (ڕاستەوخۆ جێبەجێکراو، تاقیکردنەوەکەی کار دەکات)shapes.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
"""Area, perimeter and volume functions for simple shapes."""
import math


def square_area(side):
    return side * side


def square_perimeter(side):
    return 4 * side


def rectangle_area(width, height):
    return width * height


def rectangle_perimeter(width, height):
    return 2 * (width + height)


def triangle_area(base, height):
    return base * height / 2


def triangle_perimeter(a, b, c):
    return a + b + c


def circle_area(radius):
    return math.pi * radius ** 2


def circle_perimeter(radius):          # the circumference
    return 2 * math.pi * radius


def cylinder_volume(radius, height):
    return circle_area(radius) * height


def cylinder_surface(radius, height):  # two circles + the side
    return 2 * circle_area(radius) + circle_perimeter(radius) * height


if __name__ == "__main__":
    print(square_area(2), square_perimeter(2))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 37-42

Functions of the same module call each other by their plain names.

هەمان بە ناوی ئاسایی خۆیان بانگی یەکتر دەکەن.

The program that uses itئەو بەرنامەیەی بەکاری دەهێنێتgarden.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import shapes

print("Square, side 5:", shapes.square_area(5), shapes.square_perimeter(5))
print("Rectangle 4 by 6:", shapes.rectangle_area(4, 6), shapes.rectangle_perimeter(4, 6))
print("Triangle 3, 4, 5:", shapes.triangle_area(4, 3), shapes.triangle_perimeter(3, 4, 5))
print("Circle, radius 3:", round(shapes.circle_area(3), 2), round(shapes.circle_perimeter(3), 2))
print("Tank, radius 2, height 10:", round(shapes.cylinder_volume(2, 10), 2),
      round(shapes.cylinder_surface(2, 10), 2))
Quick checkپشکنینی خێراInside shapes.py, cylinder_volume calls circle_area(radius) with no shapes. in front. Why does that work?لەناو shapes.pyـدا، cylinder_volume بەبێ shapes. لە پێشەوە circle_area(radius) بانگ دەکات. بۆچی کار دەکات؟

Exercisesڕاهێنانەکان

Find the errors (2)هەڵەکان بدۆزەرەوە ⁦(2)⁩

ExerciseڕاهێنانThe ladder programبەرنامەی پەیژەکە

This program should print how high a 5 m ladder leaning at 60° reaches up a wall and how far its foot stands from the wall, then how many ladders were checked. It has two mistakes. Find them one at a time (Python shows the second only after you fix the first) and fix them without global. Part 1 is Find the errors.

ئەم دەبێت چاپ بکات پەیژەیەکی 5 مەتری کە بە گۆشەی ⁦60°⁩ پاڵ دراوەتەوە تا چەند بەرز بە دیوارەکەدا دەگات و بنەکەی چەند لە دیوارەکە دوورە، پاشان چەند پەیژە پشکنراون. دوو هەڵەی تێدایە. یەک یەک بیاندۆزەرەوە (Python هەڵەی دووەم تەنها دوای چاککردنی یەکەم پیشان دەدات) و بەبێ global چاکیان بکەرەوە. بەشی 1: هەڵەکان بدۆزەرەوە.

ladder.pyPYTHON
from math import sin, radians

checks = 0


def ladder(length, angle):
    """Return how high a ladder reaches and how far its foot is from the wall."""
    height = length * sin(radians(angle))
    distance = length * cos(radians(angle))
    checks = checks + 1
    return round(height, 2), round(distance, 2)


print(ladder(5, 60))
print("Ladders checked:", checks)
Hintئاماژە

Look at the import line, and at every name the function assigns to.

سەیری دێڕی import بکە، هەروەها هەموو ئەو ناوانەی نرخیان بۆ دادەنێت.

Show answerوەڵامەکە پیشان بدە
The last line of each message (Python 3.12)دوایین دێڕی هەر پەیامێک ⁦(Python 3.12)⁩
StepهەنگاوPython reportsPython دەڵێت
First runیەکەم جێبەجێکردنNameError: name 'cos' is not defined
After adding cos to the importدوای زیادکردنی cos بۆ importUnboundLocalError: cannot access local variable 'checks' where it is not associated with a value
  • Only sin and radians were imported from math, so cos is unknown. Import it too: from math import sin, cos, radians.
  • checks = checks + 1 assigns to checks, so checks is a local variable of ladder(), and it is read before it has a value — see Without global: UnboundLocalError. Let the function only measure, and let the caller count.
  • تەنها sin و radians لە math هاوردە کراون، بۆیە cos نەناسراوە. ئەویش هاوردە بکە: from math import sin, cos, radians.
  • checks = checks + 1 نرخ بۆ checks دادەنێت، بۆیە checks لەناو ladder()ـدا و پێش ئەوەی نرخی هەبێت دەخوێنرێتەوە — بڕوانە بەبێ ⁦global: UnboundLocalError⁩. با تەنها بپێوێت و بژمێرێت.
Both mistakes fixedهەردوو هەڵەکە چاککراونladder_fixed.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
from math import sin, cos, radians

checks = 0


def ladder(length, angle):
    """Return how high a ladder reaches and how far its foot is from the wall."""
    height = length * sin(radians(angle))
    distance = length * cos(radians(angle))
    return round(height, 2), round(distance, 2)


print(ladder(5, 60))
checks = checks + 1          # the caller counts; the function only measures
print("Ladders checked:", checks)
Quick checkپشکنینی خێراA file starts with from math import sqrt. Which line then fails?فایلێک بە from math import sqrt دەست پێدەکات. کام دێڕ دواتر شکست دەهێنێت؟

Summaryپوختە

  • Modules make code easier to maintain, debug and reuse. A module is a .py file; its name is the file name without .py.
  • import m gives you m (call m.f()); from m import f gives you f; as renames. Avoid import *.
  • Python looks for modules in built-in modules, the script's folder, the standard library and site-packages (sys.path) — first match wins, so never name a file like a standard module.
  • A module runs once, on its first import. Put test code under if __name__ == "__main__":.
  • The standard library comes with Python: math (gcd, sqrt, factorial), random (random, randint, randrange, choice, shuffle; repeatable with a seed), statistics (mean, median, mode), secrets (passwords and tokens). dir() and help() show what a module holds.
  • ، و دووبارە بەکارهێنانی کۆد ئاسانتر دەکەن. فایلێکی .pyـە؛ ناوەکەی ناوی فایلەکەیە بەبێ .py.
  • import m ناوی m دەدات (بانگکردن: m.f())؛ from m import f ناوی f دەدات؛ as ناو دەگۆڕێت. خۆت لە import * بپارێزە.
  • Python لە ، ، و site-packages (sys.path) بەدوای دەگەڕێت — یەکەم دۆزینەوە دەباتەوە، بۆیە هەرگیز ناوی فایلێک وەک ستاندارد دامەنێ.
  • یەک جار جێبەجێ دەبێت، لە یەکەم هاوردەکردنیدا. کۆدی تاقیکردنەوە لە ژێر if __name__ == "__main__": دابنێ.
  • لەگەڵ Python دێت: math (gcd، sqrt، factorial)، random (random، randint، randrange، choice، shuffle؛ بە دووبارە دەبێتەوە)، statistics (mean، median، mode)، secrets ( و نیشانەی ئاسایش). dir() و help() پیشان دەدەن چی تێدایە.
Review questionsپرسیارەکانی پێداچوونەوە
What is the difference between import math and from math import sqrt?جیاوازیی نێوان import math و from math import sqrt چییە؟

The first gives you the name math (you write math.sqrt); the second gives you sqrt directly.

یەکەمیان ناوی math دەدات (دەنووسیت math.sqrt)؛ دووەمیان ڕاستەوخۆ sqrt دەدات.

Why do we write if __name__ == "__main__":?بۆچی دەنووسین if __name__ == "__main__":؟

So that code under it runs only when the file itself is run, not when another program imports it.

بۆ ئەوەی ئەو کۆدەی لە ژێریدایە تەنها کاتێک جێبەجێ ببێت کە خودی فایلەکە جێبەجێ دەکرێت، نەک کاتێک تر هاوردەی دەکات.

Where must a module of yours be so that import finds it?مۆدیوڵێکی خۆت دەبێت لە کوێ بێت بۆ ئەوەی import بیدۆزێتەوە؟

On the search path; most simply in the same folder as the script you run.

لەسەر ڕێگای گەڕان؛ سادەترین شوێن هەمان کە جێبەجێی دەکەیت تێدایە.

Next: Recursion — a function that calls itself.

دواتر: خۆبانگکردنەوە — کە بانگی خۆی دەکاتەوە.

Videoڤیدیۆ

Watch a videoسەیری ڤیدیۆیەک بکە

A video that viewers liked a lot and praised in their comments, chosen for this lesson.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.

What are Python modules? 📨Bro Code · Englishئینگلیزی · 166K viewsبینین · 4.4K likesلایک

What a module is, the import forms import x, import x as y and from x import y, and how to write your own module.

چییە، شێوەکانی : import x، import x as y و from x import y، هەروەها چۆن خۆت دەنووسیت.

Chapters: 0:19 help("modules"), 1:01 import x, 1:28 import x as y, 1:55 from x import y, 3:51 create your own module.

بەشەکان: ⁦0:19⁩ help("modules")، ⁦1:01⁩ import x، ⁦1:28⁩ import x as y، ⁦1:55⁩ from x import y، ⁦3:51⁩ دروستکردنی خۆت.

Lesson complete!وانەکە تەواو بوو!

Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.

Key termsزاراوە سەرەکییەکان

Next lessonوانەی داهاتوو

Recursionخۆبانگکردنەوە

References and further readingسەرچاوەکان و خوێندنەوەی زیاتر

This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.