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) و نووسینی خۆت.
What you will learnچی فێر دەبیت
- Explain why programs are split into modules, and that a module is a
.pyfile. - Use
import,from … import …andas, 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 usemath,random,statisticsandsecretsfrom 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 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 یەک جار بار دەکات و بە ناو بەکاری دەهێنێت، بۆیە ئەگەر بگۆڕیت، هەموو کە هاوردەی دەکات گۆڕانکارییەکە وەردەگرێت.
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_areaandcircle_area. - Each function in a module needs a different name. Python does not stop you from reusing a name, but the later
defsilently 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.pycannot be imported (import gcd-functionis 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 ناوی کورتی پیتی بچووکی پێ باشترە.
def greet():
print("Hello")
def greet(): # same name: this one replaces the first
print("Welcome")
greet()Welcome
No error: only the second greet is left.
هیچ نییە: تەنها greetـی دووەم دەمێنێتەوە.
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. تەنها دەناسێنێت؛ هیچ شتێک چاپ ناکات:
# 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 gcdExplain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3-4
resultis the best answer so far;kis the next number to try.resultباشترین وەڵامە تا ئێستا؛kژمارەی داهاتووە بۆ تاقیکردنەوە.- Lineدێڕی 7
%gives the remainder: 0 meanskdivides 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:
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))Enter the first integer: 45 Enter the second integer: 75 The greatest common divisor for 45 and 75 is 15
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Import the
gcdfunction from the modulegcd_function(the filegcd_function.py).gcdلەgcd_function(فایلیgcd_function.py) هاوردە بکە.- Lineدێڕی 4-5
int(input())turns the typed text into a whole number.int(input())دەقە نووسراوەکە دەکاتە .
Enter the first integer: 16 Enter the second integer: 24 The greatest common divisor for 16 and 24 is 8
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 سەیری بکە:


result is updated at 3, 5 and 15; the last update is the GCD.result لە 3، 5 و 15دا نوێ دەکرێتەوە؛ دوایین نرخ .CêITFour ways to importچوار ڕێگای هاوردەکردن
There are four common forms of the . They differ in which name your program gets:
چوار شێوەی باوی هەن. جیاوازییان لەوەدایە کە کام ناو وەردەگرێت:
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))4.0 5.0 3.141592653589793 7 15
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-2
import mathadds only the namemath. 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, notmath.sqrt.from … import …ناوە هەڵبژێردراوەکان ڕاستەوخۆ دەخاتە ناو فایلەکەت:sqrt، نەکmath.sqrt.- Lineدێڕی 7-8
asgives the module a shorter name.asناوێکی کورتتر دەداتە .- Lineدێڕی 10-11
ascan also rename one imported name, for example to avoid a clash with your owngcd.asدەتوانێت ناوی یەک ناوی هاوردەکراویش بگۆڕێت، بۆ نموونە بۆ ئەوەی لەگەڵgcdـی خۆت تێکنەچێت.
| You writeدەنووسیت | Name you getئەو ناوەی وەریدەگریت | You callبانگ دەکەیت |
|---|---|---|
import math | math | math.sqrt(16) |
from math import sqrt | sqrt | sqrt(16) |
import math as m | m | m.sqrt(16) |
from math import sqrt as root | root | root(16) |
A common mistake is to import the module and then call the function without the module name:
هەڵەیەکی باو ئەوەیە کە هاوردە بکەیت و پاشان بەبێ ناوی بانگ بکەیت:
import math
print(sqrt(16)) # sqrt alone is not known: only the name math was addedTraceback (most recent call last):
File "no_prefix.py", line 3, in <module>
print(sqrt(16)) # sqrt alone is not known: only the name math was added
^^^^
NameError: name 'sqrt' is not definedFour 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 بە یەکجار دەهێنێت. ئاسان دیارە، بەڵام ناتوانیت ببینیت کام ناوانە هاتوون و دەتوانن بە بێدەنگی شوێنی ناوەکانی خۆت بگرنەوە:
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 replaced2.718281828459045
math.e (2.718…) replaced the 5.
math.e (2.718…) شوێنی 5ـەکەی گرتەوە.
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 دەوەستێت:
from gcd_functions import gcd # a typo in the module nameTraceback (most recent call last):
File "typo.py", line 1, in <module>
from gcd_functions import gcd # a typo in the module name
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ModuleNotFoundError: No module named 'gcd_functions'import: the first match wins.ڕیزبەندیی گەڕانی import: یەکەم دۆزینەوە دەباتەوە.CêITBecause 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
print(random.randint(1, 6))This is my practice file, not Python's random module!
Traceback (most recent call last):
File "dice.py", line 3, in <module>
print(random.randint(1, 6))
^^^^^^^^^^^^^^
AttributeError: module 'random' has no attribute 'randint'The first line comes from the practice file random.py. Fix: rename that file, for example to random_practice.py. (An old copy in the __pycache__ folder does no harm: Python ignores it once the .py file is gone.) From Python 3.13 the last line itself gives this advice: it ends with (consider renaming '…/random.py' since it has the same name as the standard library module named 'random' …).
یەکەم دێڕ لە فایلی ڕاهێنانەکە، random.py، دێت. چارەسەر: ناوی ئەو فایلە بگۆڕە، بۆ نموونە بۆ random_practice.py. (کۆپییە کۆنەکەی ناو __pycache__ زیانی نییە: Python کاتێک فایلی .pyـەکە نەما پشتگوێی دەخات.) لە Python 3.13ـەوە خودی دوایین دێڕی پەیامەکە ئەم ئامۆژگارییە دەدات: بەم دەقە کۆتایی دێت (consider renaming '…/random.py' since it has the same name as the standard library module named 'random' …).
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ـی دووەمی هەمان لە هەمان تەنها دووبارە بەکاری دەهێنێتەوە:
printـێکی لە سەرەوەیەgreetings.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسەprint("greetings is loading ...")
def hello(name):
print("Hello,", name)import greetings
import greetings # a second import does not run the file again
greetings.hello("Rezan")
greetings.hello("Lana")greetings is loading ... Hello, Rezan Hello, Lana
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:
کاتێک دەنووسیت، زۆرجار تاقیکردنەوەیەکی خێرا لە خوارەوە زیاد دەکەیت. بەڵام لەبەر ئەوەی هاوردەکردن هەموو فایلەکە جێبەجێ دەکات، ئەو تاقیکردنەوەیە لە هەموو کە هاوردە دەکاتیش جێبەجێ دەبێت:
def bill(glasses, price=500):
return glasses * price
# a quick test of the function
print("Test:", bill(3))import tea_tools
print("Customer pays", tea_tools.bill(4))Test: 1500 Customer pays 2000
Test: 1500 does not belong here.
Test: 1500 شوێنی لێرە نییە.
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__ ناوی :
import show_name
print("This file's __name__ is", __name__)__name__ is show_name This file's __name__ is __main__
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__": دابنێ. کاتێک خودی جێبەجێ دەکەیت کار دەکات و کاتێک تر هاوردەی دەکات جێدەهێڵرێت:
def bill(glasses, price=500):
return glasses * price
if __name__ == "__main__": # True only when this file is run directly
print("Test:", bill(3))Test: 1500
import tea_tools
print("Customer pays", tea_tools.bill(4))Customer pays 2000
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 پیشان دەدەن:
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 و زۆری تر لەخۆ دەگرێت.
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))9.0 3.141592653589793 15 120 5
From Python 3.15 the whole-number tools gcd, factorial, comb, perm, isqrt and lcm also live in the new module math.integer (math.integer.gcd(45, 75)). The math.gcd names used here keep working; the documentation only recommends the new names for new code.
لە Python 3.15ـەوە ئامرازەکانی ، واتە gcd، factorial، comb، perm، isqrt و lcm، لە نوێی math.integerـیشدان (math.integer.gcd(45, 75)). ناوەکانی وەک math.gcd کە لێرە بەکار هاتوون هەر کار دەکەن؛ بەڵگەنامەکان تەنها بۆ کۆدی نوێ ناوە نوێکان پێشنیار دەکەن.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5
The same answer as our
gcd_functionmodule — writing it ourselves taught how it works.هەمان وەڵامی
gcd_functionـی خۆمان — نووسینی بە دەستی خۆمان فێری کردین چۆن کار دەکات.- Lineدێڕی 6
: .
: .
More math tools, such as floor, ceil, sin and cos, are in The math toolbox.
ئامرازی زیاتری math، وەک floor، ceil، sin و cos، لە ئامرازەکانی 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) لە سەرەتادا، هەموو جێبەجێکردنێک هەمان ئەنجام دەدات، ئەمەش تاقیکردنەوەی ئاسان دەکات:
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)0.32383276483316237 2 75 juice ['Shilan', 'Karwan', 'Dilan', 'Aram']
With random.seed(7) you get exactly these lines (Python 3.12 and 3.13); remove the seed and they change on every run.
بە random.seed(7) ڕێک ئەم دێڕانە وەردەگریت (Python 3.12 و 3.13)؛ لاببە و لە هەر جێبەجێکردنێکدا دەگۆڕێن.
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 fromrange(start, stop, step), so the stop itself is never chosen.randrange(start, stop, step)لەrange(start, stop, step)هەڵدەبژێرێت، بۆیە خودی stop هەرگیز هەڵنابژێردرێت.- Lineدێڕی 9
shufflechanges the list itself and returnsNone.shuffleخودی دەگۆڕێت وNoneدەگەڕێنێتەوە.
| Toolئامراز | Givesچی دەدات | Possible resultsئەنجامە گونجاوەکان |
|---|---|---|
random.random() | a float | from 0.0 up to, not including, 1.0لە 0.0 تا 1.0، بێ خودی 1.0 |
random.randint(1, 6) | a whole number | 1 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 بەکار هێنا.
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 بەکار بهێنە:
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"))4789c1051429ccec 649585 5
Your output is different on every run — that is the point.
لە هەر جێبەجێکردنێکدا جیاوازە — مەبەست هەر ئەوەیە.
| Module | Good forباشە بۆ | Not forنەک بۆ |
|---|---|---|
random | Games, dice, simulations, shuffling a quiz; repeatable with a seedیاری، زار، لاساییکردنەوە، تێکەڵکردنی پرسیارەکان؛ بە دووبارە دەبێتەوە | Passwords, codes, tokens، کۆد، نیشانەی ئاسایش |
secrets | Passwords, 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.
بۆچی کە بتوانرێت مەزەندە بکرێت مەترسیدارە، لەگەڵ نموونەیەکی هێرش بۆ سەر کۆدێکی ، لە کاتێک ڕێکەوت دەبێت نهێنی بمێنێتەوە پیشان دراوە. هەروەها تێکدانی ڕیزبەندیی چەند ناسراو بەهێز دروست ناکات: بڕوانە تێکدانی ڕیزبەندی بەس نییە.
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 دەبینیت:
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 often32 5 5
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 سێ جار هاتووە.
Writing your own moduleنووسینی مۆدیوڵی خۆت
- Create the fileفایلەکە دروست بکە
Make a new file with a valid lowercase name ending in
.py, for exampleshapes.py, in the same folder as your program.فایلێکی نوێ بە ناوێکی دروستی پیتی بچووک کە بە
.pyکۆتایی دێت دروست بکە، بۆ نموونەshapes.py، لە هەمان کە تێدایە. - Put definitions in itناساندنەکانی کردار تێ بخە
Write the functions (with docstrings). Avoid code that runs on import; put tests under
if __name__ == "__main__":.بنووسە (لەگەڵ ). خۆت لە کۆدێک بپارێزە کە لە کاتی هاوردەکردندا جێبەجێ دەبێت؛ تاقیکردنەوەکان لە ژێر
if __name__ == "__main__":دابنێ. - Import and use itهاوردەی بکە و بەکاری بهێنە
In your program write
import shapesand callshapes.square_area(4)— orfrom shapes import square_area.لە بنووسە
import shapesوshapes.square_area(4)بانگ بکە — یانfrom shapes import square_area.
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 ** 2Explain 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:
shapesusesmath.pi.دەتوانێت تر هاوردە بکات:
shapesلەmath.piسوود وەردەگرێت.
import shapes
print(shapes.__doc__)
print(shapes.square_area(4))
print(shapes.rectangle_area(3, 5))
print(round(shapes.circle_area(2), 2))Area functions for simple shapes. 16 15 12.57
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)ـیش پیشانی دەدات.
Common mistakesهەڵە باوەکان
| Mistakeهەڵە | What happensچی ڕوو دەدات | Fixچارەسەر |
|---|---|---|
Writing .py in the import: import shapes.pyنووسینی .py لە import: import shapes.py | ModuleNotFoundError: No module named 'shapes.py'; 'shapes' is not a package | import shapes |
| A typo, or the module is in another folderهەڵەی نووسین، یان لە تردایە | ModuleNotFoundError | Check the spelling; keep the module next to your scriptنووسینەکە بپشکنە؛ لە تەنیشت دابنێ |
import math, then sqrt(16)import math، پاشان sqrt(16) | NameError: name 'sqrt' is not defined | math.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ڕاهێنانەکان
Write a module converter.py with two functions: km_to_miles(km) (1 km is 0.621371 miles) and celsius_to_fahrenheit(c) (). 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) (). تاقیکردنەوەیەک لە ژێر if __name__ == "__main__": زیاد بکە. پاشان trip.py لە هەمان بنووسە کە هەردوو هاوردە بکات و میلی 85 km (بە یەک ژمارەی دوای خاڵ) و نرخی فەهرەنهایتی 45 °C چاپ بکات.
Show answerوەڵامەکە پیشان بدە
"""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))6.21371 104.0
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")52.8 miles 113.0 F
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ـیە چی چاپ دەکات و دێڕی بارکردنەکە چەند جار دەردەکەوێت؟
import greetings
import greetings # a second import does not run the file again
greetings.hello("Rezan")
greetings.hello("Lana")Show answerوەڵامەکە پیشان بدە
greetings is loading ... Hello, Rezan Hello, Lana
Once: the second import finds the module already loaded.
یەک جار: importـی دووەم بە بارکراوی دەدۆزێتەوە.
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 دەدات.
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 و دواتر تەنانەت لە پەیامی گۆڕینی ناوەکە پێشنیار دەکەن.)
Exercisesڕاهێنانەکان
Exercises: tools from the standard libraryڕاهێنان: ئامرازەکانی کتێبخانەی ستاندارد
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وەڵامەکە پیشان بدە
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 51024 1024.0 24 12157665459056928801 1.2157665459056929e+19 0.6229016948897019 3
- (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, sopow(2, 10, 1000)is(2 ** 10) % 1000, which is 24.math.pow()always turns its numbers into floats, so it answers1024.0; and a big float is rounded, asmath.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.
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وەڵامەکە پیشان بدە
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 onceThe first prize goes to ticket 122 The second prize goes to ticket 328 The third prize goes to ticket 515 [525, 106, 229]
These numbers come from random.seed(2026) (Python 3.12 and 3.13).
ئەم ژمارانە لە random.seed(2026)ـەوە دێن (Python 3.12 و 3.13).
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 بۆ تێپەڕەوشە نییە).
Exercisesڕاهێنانەکان
Exercise: a menu calculatorڕاهێنان: حاسیبەیەک بە مێنیو
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وەڵامەکە پیشان بدە
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()1 add 2 subtract 3 multiply 4 divide 5 log10 6 sin 7 cos 0 quit Choice: 3 First number: 7 Second number: 5 Answer: 35.0 Choice: 4 First number: 9 Second number: 0 You cannot divide by 0. Choice: 5 A number above 0: 1000 Answer: 3.0 Choice: 6 Angle in degrees: 30 Answer: 0.5 Choice: 7 Angle in degrees: 60 Answer: 0.5 Choice: 0 Goodbye!
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ـی هەڵبژارد.
Exercisesڕاهێنانەکان
Exercise: a bigger shapes moduleڕاهێنان: مۆدیوڵێکی گەورەتری shapes
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, ); 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ـی نووسینی مۆدیوڵی خۆت فراوان بکە: بۆ چوارگۆشە، لاکێشە، سێگۆشە و بازنە ڕووبەر و چێوە بنووسە (چێوەی بازنە بریتییە لە )؛ بۆ ئەستوانەیەک، وەک تانکی ئاو، قەبارە و ڕووبەری ڕووکارەکەی بنووسە. پاشان 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وەڵامەکە پیشان بدە
"""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))4 8
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 37-42
Functions of the same module call each other by their plain names.
هەمان بە ناوی ئاسایی خۆیان بانگی یەکتر دەکەن.
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))Square, side 5: 25 20 Rectangle 4 by 6: 24 20 Triangle 3, 4, 5: 6.0 12 Circle, radius 3: 28.27 18.85 Tank, radius 2, height 10: 125.66 150.8
Exercisesڕاهێنانەکان
Find the errors (2)هەڵەکان بدۆزەرەوە (2)
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: هەڵەکان بدۆزەرەوە.
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وەڵامەکە پیشان بدە
| Stepهەنگاو | Python reportsPython دەڵێت |
|---|---|
| First runیەکەم جێبەجێکردن | NameError: name 'cos' is not defined |
After adding cos to the importدوای زیادکردنی cos بۆ import | UnboundLocalError: cannot access local variable 'checks' where it is not associated with a value |
- Only
sinandradianswere imported frommath, socosis unknown. Import it too:from math import sin, cos, radians. checks = checks + 1assigns tochecks, sochecksis a local variable ofladder(), 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. با تەنها بپێوێت و بژمێرێت.
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)(4.33, 2.5) Ladders checked: 1
Summaryپوختە
- Modules make code easier to maintain, debug and reuse. A module is a
.pyfile; its name is the file name without.py. import mgives youm(callm.f());from m import fgives youf;asrenames. Avoidimport *.- 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()andhelp()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()پیشان دەدەن چی تێدایە.
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 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زاراوە سەرەکییەکان
Recursionخۆبانگکردنەوە
Related lecturesوانە پەیوەندیدارەکان
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- Python tutorial 6: Modules (import forms, executing modules as scripts, the module search path, standard modules)
- Python library: sys (sys.path)
- Python library: random — Generate pseudo-random numbers (warning: not for security)
- Python library: secrets — Generate secure random numbers for managing secrets
- Python library: math (gcd, factorial, sqrt)
- Python programming FAQ: best practices for using import in a module
- Harvard CS50P, lecture 4 notes: Libraries (random, statistics, packages, your own library)
- Python library: statistics — mean, median, mode
- Python library: built-in functions (pow with a modulus, dir, help)
- Python library: math.integer (new in 3.15; math.gcd and math.factorial become soft-deprecated aliases)
- What's New in Python 3.13: better error messages (a script with the name of a standard module)
- PEP 3147 — PYC Repository Directories (a .pyc in __pycache__ is ignored when its .py file is gone)
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.