PythonPython · Chapterبەش 12 · Lectureوانە 12.1

Project: Binary to Decimal Converterپڕۆژیلە: گۆڕینی دووانی بۆ دەیی

A real first-year mini project worked through from plan to code: the scenario, the flowchart, the algorithm, the final Python code and its first version, testing, the bugs (including a crash on words), and an improved converter that handles any length with a loop, int(x, 2) and input validation.

ڕاستەقینەی ساڵی یەکەم لە پلانەوە تا کۆد: ، ، ، کۆدی کۆتایی و یەکەم وەشانەکەی، تاقیکردنەوە، (لەوانە کەوتن بە وشە) و گۆڕەرێکی باشترکراو کە بە ، int(x, 2) و هەر درێژییەک وەردەگرێت.

31 min read29 خولەک خوێندنەوە · 28 stepsهەنگاو

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

  • Follow a mini project through its plan: scenario, flowchart, algorithm, code and examples.
  • Explain how the program validates the choice, the length and every digit with loops.
  • Test a program systematically and find bugs such as a missing space and a crash on non-numbers.
  • Convert binary of any length with a loop or int(text, 2), and the other way with bin().
  • Improve a working program: functions, snake_case names, try/except and automatic tests.
  • بە پلانەکەیدا بەدوادا بچیت: ، ، ، کۆد و نموونەکان.
  • ڕوونی بکەیتەوە چۆن بە هەڵبژاردن، درێژی و هەموو پشتڕاست دەکاتەوە.
  • بە ڕێکوپێکی تاقی بکەیتەوە و بدۆزیتەوە، وەک نەبوونی و کەوتن بە نووسینی ناژمارە.
  • هەر درێژییەک بە یان int(text, 2) بگۆڕیت و بە پێچەوانەوە بە bin().
  • کە کار دەکات باشتر بکەیت: ، ناوی ، try/except و تاقیکردنەوەی خۆکار.

The projectپڕۆژیلەکە

This lesson follows a real mini project from the first year of an IT course: a group of students wrote a Python program that converts a binary number with 2 or 3 digits into decimal. They presented it in English and wrote a report in Kurdish with the title «پڕۆژیلەی گۆڕینی دوویی بۆ دەیی» (Mini Project for Converting Binary to Decimal). You will study their plan, their code and their tests, find the bugs, and then improve the program.

ئەم وانەیە بەدوای ڕاستەقینەی ساڵی یەکەمی خوێندنی ITـدا دەڕوات: گرووپێک قوتابی بە نووسی کە ژمارەیەکی بە 2 یان 3 دەکات بە . بە ئینگلیزی پێشکەشیان کرد و ڕاپۆرتێکی کوردییان بە ناونیشانی «پڕۆژیلەی گۆڕینی دوویی بۆ دەیی» نووسی. پلان، کۆد و تاقیکردنەوەکانیان دەخوێنیتەوە، دەدۆزیتەوە و پاشان باشتر دەکەیت.

Definitionپێناسە

A small project that a student or a small group builds from start to finish — from the to tested code — to practise what a course taught.

پڕۆژەیەکی بچووکی کە خوێندکارێک یان گرووپێکی بچووک لە سەرەتاوە تا کۆتایی دروستی دەکەن، لە تا کۆدی تاقیکراوە، بۆ ڕاهێنان لەسەر ئەوەی لە وانەکاندا فێری بوون.

The group's Kurdish report explains its word in a footnote: «پڕۆژیلە» means Mini Project, a small project.

ڕاپۆرتە کوردییەکەی گرووپەکە لە پەراوێزێکدا وشەکەی ڕوون دەکاتەوە: «پڕۆژیلە» واتە ⁦Mini Project⁩: پڕۆژەی بچووک.

Definitionپێناسە

One of the symbols used to write numbers, such as 7 in decimal or F in hexadecimal. A number system with base b has b digits; the number 507 has three digits.

یەکێکە لەو هێمایانەی ژمارەیان پێ دەنووسرێت، وەک 7 لە یان F لە . کە b بێت، b تاکژمارەی هەیە؛ ژمارەی ⁦507⁩ سێ تاکژمارەی هەیە.

The same report's second footnote: «تاکژمارە» is the Kurdish word for digit. A binary digit is also called a bit.

پەراوێزی دووەمی هەمان ڕاپۆرت: «تاکژمارە» وشە کوردییەکەی Digitـە. پێی دەوترێت .

The group planned the program in five parts, the method taught in Algorithms, pseudocode and flowcharts: scenario → flowchart → algorithm → code → examples. This lesson walks through the same parts, then adds two more that every real project needs: finding bugs and improving the code.

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

Quick checkپشکنینی خێراIn which part of the method do you describe, in plain words, what the program does for the user?لە کام بەشی ڕێگاکەدا بە وشەی سادە باسی ئەوە دەکەیت کە چی بۆ دەکات؟

Binary to decimal in one minuteدووانی بۆ دەیی لە یەک خولەکدا

The maths behind the project is taught in Logic Design: Number Systems and Place Value and From Binary, Octal and Hex to Decimal. Here is the short version you need for the program. In a binary number every digit is 0 or 1, and every place has a place value that is a power of two. For three digits the place values are 4, 2 and 1. Multiply each digit by its place value and add:

بیرکارییەکەی پشت پڕۆژەکە لە کۆرسی دیزاینی دەخوێنرێت: سیستەمە ژمارەییەکان و بەهای خانەیی و لە دووانی، هەشتی و شانزەییەوە بۆ دەیی. ئەمە کورتەکەیەتی کە بۆ پێویستتە. لە ژمارەیەکی هەر 0 یان 1ـە و هەر خانەیەک هەیە کە 2ـە. بۆ سێ ، 4، 2 و 1ـن. هەر لە بدە و کۆیان بکەرەوە:

(101)2=1×22+0×21+1×20=4+0+1=(5)10(101)_2 = 1 \times 2^2 + 0 \times 2^1 + 1 \times 2^0 = 4 + 0 + 1 = (5)_{10}

The small 2 and 10 under the numbers name the base: binary and decimal.

2 و ⁦10⁩ـی بچووکی ژێر ژمارەکان دەناسێنن: و .

An animation. The binary number 101 appears as three digit boxes. Above them the place values 2 to the power 2 = 4, 2 to the power 1 = 2 and 2 to the power 0 = 1 appear. Under each digit the product is written: 1×4 = 4, 0×2 = 0, 1×1 = 1. At the end the sum 4 + 0 + 1 = 5 is shown.
An animation. The binary number 101 appears as three digit boxes. Above them the place values 2 to the power 2 = 4, 2 to the power 1 = 2 and 2 to the power 0 = 1 appear. Under each digit the product is written: 1×4 = 4, 0×2 = 0, 1×1 = 1. At the end the sum 4 + 0 + 1 = 5 is shown.
Each binary digit is weighted by a power of two, and the weights of the 1s are added.هەر بە 2 کێش دەکرێت و کێشی 1ـەکان کۆ دەکرێنەوە.CêIT
Quick checkپشکنینی خێراWhat is the binary number 110 in decimal?ژمارەی ⁦110⁩ بە چەندە؟

How to Convert Binary to Decimaltecmath · Englishئینگلیزی · 668K viewsبینین · 13K likesلایک

A short, clear way to turn a binary number into decimal: give each digit its place value and add the values under the 1s.

بۆ : لە ڕاستەوە بنووسە و هەر جارێک دوو هێندەی بکە، پاشان ئەوانە کۆ بکەرەوە کە 1یان لە ژێردایە.

A 2.5-minute reminder of binary to decimal, with practice examples (1:20).

بیرخستنەوەیەکی دوو خولەک و نیو بۆ گۆڕینی بۆ ، لەگەڵ نموونەی ڕاهێنان ⁦(1:20)⁩.

Binary to decimal in one minuteدووانی بۆ دەیی لە یەک خولەکدا

The two tables the program usesئەو دوو خشتەیەی بەرنامەکە بەکاری دەهێنێت

The group did not calculate with place values in the program. Instead they wrote down every possible input and its answer, like a truth table that lists every combination of 0s and 1s, and the program looks the answer up. Two digits have 4 combinations, three digits have 8:

گرووپەکە لە بە هەژماریان نەکرد. لەبری ئەوە هەموو گونجاو و وەڵامەکەیان نووسی، وەک کە هەموو تێکەڵەیەکی 0 و 1 ڕیز دەکات. وەڵامەکە لەوێدا دەدۆزێتەوە. دوو 4 تێکەڵەیان هەیە و سێ 8:

Every answer the program knows. Check a few rows with the place values 2–1 and 4–2–1.هەموو ئەو وەڵامانەی دەیانزانێت. چەند ڕیزێک بە ⁦2–1⁩ و ⁦4–2–1⁩ بپشکنە.
2 digitsدوو decimal3 digitsسێ decimal
0000000
0110011
1020102
1130113
1004
1015
1106
1117
Quick checkپشکنینی خێراHow many rows would the table need for 4 binary digits?خشتەکە بۆ 4 چەند ڕیزی پێویستە؟

Part 1: the scenarioبەشی 1: نەخشەنامە

A scenario describes the program from the user's side, before any code. The group's scenario, in clear steps:

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

  1. Nameناو

    The program greets the user and asks for a name.

    بەخێرهاتنی دەکات و داوای ناوێک دەکات.

  2. 2 or 32 یان 3

    It greets the user by that name and asks how many binary digits they want to enter: 2 or 3. Any other number gets a message and the question again.

    بە هەمان ناو بەخێرهاتنی دەکات و دەپرسێت چەند دەنووسێت: 2 یان 3. هەر ژمارەیەکی تر پەیامێک و دووبارە هەمان پرسیار وەردەگرێت.

  3. The digitsتاکژمارەکان

    The user types that many binary digits (0s and 1s).

    ئەو ژمارەیە (⁦0⁩ و ⁦1⁩) دەنووسێت.

  4. Wrong digitsتاکژمارەی هەڵە

    A digit other than 0 or 1, or the wrong number of digits, gets a message and another try.

    جگە لە 0 یان 1، یان ژمارەی هەڵەی ، پەیامێک و هەلێکی تر وەردەگرێت.

  5. The answerوەڵام

    The program shows the number in decimal. (The final version then asks whether to run again.)

    ژمارەکە بە پیشان دەدات. (وەشانی کۆتایی پاشان دەپرسێت ئایا دووبارە کار بکاتەوە.)

Quick checkپشکنینی خێراAccording to the scenario, what happens when the user types the digits 12 after choosing 2?بەپێی ، کاتێک دوای هەڵبژاردنی 2 12 دەنووسێت چی ڕوو دەدات؟

Part 2: the flowchartبەشی 2: هێڵکاریی ڕەوت

The flowchart shows the order of the work. The main program is short: it prints a title, reads the name, asks for 2 or 3, hands everything to the function Inputs and prints the answer. The final version wraps this in a loop that asks whether to run again.

ڕیزبەندیی کارەکان پیشان دەدات. سەرەکییەکە کورتە: ناونیشانێک چاپ دەکات، ناوەکە دەخوێنێتەوە، 2 یان 3 دەپرسێت، هەموو شتێک دەداتە Inputs و وەڵامەکە چاپ دەکات. وەشانی کۆتایی ئەمە دەخاتە ناو کە دەپرسێت ئایا دووبارە کار بکاتەوە.

A flowchart of the main program: Start, show the title, read the user's name, make the lists validNums and errorMsg, ask for 2 or 3 binary digits, the predefined process Inputs(choice) checks and converts, print the decimal result, ask whether to run again. If the answer is not y or n, print Invalid input and ask again. If it is y, go back to showing the title. If it is n, print Goodbye! and end.هێڵکاریی ڕەوتی بەرنامە سەرەکییەکە: دەستپێک، پیشاندانی ناونیشان، خوێندنەوەی ناوی بەکارهێنەر، دروستکردنی لیستەکانی validNums و errorMsg، پرسیاری 2 یان 3 تاکژمارەی دووانی، پرۆسەی ئامادەی Inputs(choice) دەپشکنێت و دەگۆڕێت، چاپکردنی ئەنجامە دەییەکە، پرسیار کە ئایا دووبارە کار بکاتەوە. ئەگەر وەڵام y یان n نەبوو، Invalid input چاپ دەکات و دووبارە دەپرسێت. ئەگەر y بوو، دەگەڕێتەوە بۆ پیشاندانی ناونیشان. ئەگەر n بوو، Goodbye! چاپ دەکات و کۆتایی دێت.
The main program of the final version, redrawn with the standard symbols. سەرەکییەکەی وەشانی کۆتایی، بە هێماکانی ستاندارد دووبارە کێشراوەتەوە.CêIT
Quick checkپشکنینی خێراIn a flowchart, which shape is used for Read the user's name?لە ، کام شێوە بۆ ناوی بخوێنەوە بەکار دێت؟

Part 2: the flowchartبەشی 2: هێڵکاریی ڕەوت

Inside the Inputs functionناو کرداری Inputs

Inputs(num) does all the checking and the converting. First a loop repeats until num is "2" or "3". Then, for two digits, a second loop reads the digits until their length is right and both are 0 or 1. Each problem has its own message from the list errorMsg. Finally the table gives the answer. The three-digit branch is the same with its own length message and the eight-row table.

Inputs(num) هەموو پشکنین و گۆڕینەکە دەکات. سەرەتا دووبارە دەبێتەوە تا num "2" یان "3" دەبێت. پاشان بۆ دوو ، دووەم دەخوێنێتەوە تا درێژییەکەیان دروست بێت و هەردووکیان 0 یان 1 بن. هەر کێشەیەک پەیامی تایبەتی خۆی لە errorMsg هەیە. لە کۆتاییدا خشتەکە وەڵامەکە دەدات. لقی سێ هەمان شتە بە پەیامی درێژیی خۆی و خشتە هەشت ڕیزییەکە.

A flowchart of Inputs(num). Decision: is num "2" or "3"? No: print errorMsg[0], ask again and go back. Yes: decision num == "2"? No: a predefined process, the same steps for 3 digits with errorMsg[3] and an 8-row table, then return. Yes: read two digits into Digits; decision: is the length 2? No: print errorMsg[1] and read again. Yes: decision: are both digits 0 or 1? No: print errorMsg[2] and read again. Yes: look up the table 00→0, 01→1, 10→2, 11→3, then return result.هێڵکاریی ڕەوتی Inputs(num). بڕیار: ئایا num "2" یان "3"ـە؟ نەخێر: errorMsg[0] چاپ بکە، دووبارە بپرسە و بگەڕێوە. بەڵێ: بڕیار num == "2"؟ نەخێر: هەمان هەنگاوەکان بۆ 3 تاکژمارە بە errorMsg[3] و خشتەیەکی 8 ڕیزی، پاشان return. بەڵێ: دوو تاکژمارە بخوێنەوە بۆ ناو Digits؛ بڕیار: ئایا درێژییەکەی 2ـە؟ نەخێر: errorMsg[1] چاپ بکە و دووبارە بخوێنەوە. بەڵێ: بڕیار: ئایا هەردوو تاکژمارەکە 0 یان 1ـن؟ نەخێر: errorMsg[2] چاپ بکە و دووبارە بخوێنەوە. بەڵێ: لە خشتەی 00→0، 01→1، 10→2، 11→3 بیدۆزەرەوە، پاشان return result.
The function Inputs: every check has its own message and its own loop back. Inputs: هەر پشکنینێک پەیامی خۆی و گەڕانەوەی خۆی هەیە.CêIT
IndexMessage in errorMsgپەیام لە errorMsgShown whenکەی پیشان دەدرێت
0Only 2 or 3 are valid.the choice is not 2 or 3هەڵبژاردنەکە 2 یان 3 نییە
1Only two binary numbers are valid!2 digits were wanted, the length is wrong2 داواکرابوو، درێژییەکە هەڵەیە
2You can only enter 0 or 1.a digit is not 0 or 1 0 یان 1 نییە
3Only three binary numbers are valid!3 digits were wanted, the length is wrong3 داواکرابوو، درێژییەکە هەڵەیە
Quick checkپشکنینی خێراThe user chose 3 and typed 1011. Which message appears? 3ـی هەڵبژارد و 1011ـی نووسی. کام پەیام دەردەکەوێت؟

Part 3: the algorithmبەشی 3: ئەلگۆریزم

The algorithm lists the steps from the very beginning, in words. The group wrote it twice: 20 steps in the Kurdish report (their «هەنگاونامە», for the first version of the code) and 22 steps in the English presentation (for the final version, which adds steps 2 and 21). Here both are merged into one numbered list. Steps 1–6 get everything ready:

هەنگاوەکان لە سەرەتاوە بە وشە ڕیز دەکات. گرووپەکە دوو جار نووسیویەتی: ⁦20⁩ هەنگاو لە ڕاپۆرتە کوردییەکەدا (بۆ وەشانی یەکەمی کۆدەکە) و ⁦22⁩ هەنگاو لە پێشکەشکردنە ئینگلیزییەکەدا (بۆ وەشانی کۆتایی کە هەنگاوەکانی 2 و ⁦21⁩ زیاد دەکات). لێرەدا هەردووکیان بە یەک ژمارەکردن تێکەڵ کراون. هەنگاوەکانی ⁦1–6⁩ هەموو شتێک ئامادە دەکەن:

StepهەنگاوWhat the program does چی دەکات
1Start the program. دەست پێ دەکات.
2Call the function program(), which holds steps 3 to 20. (Final version only.) program() بانگ دەکرێت کە هەنگاوەکانی 3 تا ⁦20⁩ لەخۆ دەگرێت. (تەنها وەشانی کۆتایی.)
3Print three lines (a row of stars, the title, stars again) to make the program friendlier.سێ دێڕ چاپ دەکات (ڕیزێک ئەستێرە، ناونیشان، دیسان ئەستێرە) بۆ ئەوەی جوانتر و دۆستانەتر بێت.
4Ask for the user's name and store it in the variable name.ناوی دەپرسێت و لە nameـدا هەڵی دەگرێت.
5Make the list validNums with the two valid choices: the strings "2" and "3" (the integers 2 and 3 in the first version). validNums دروست دەکات بە دوو هەڵبژاردە دروستەکە: "2" و "3" (لە وەشانی یەکەمدا 2 و ⁦3⁩).
6Make the list of strings errorMsg with four messages; when something goes wrong, the matching one is printed. errorMsg دروست دەکات بە چوار پەیام؛ کاتێک شتێک هەڵە دەبێت، پەیامە گونجاوەکە چاپ دەکرێت.
Quick checkپشکنینی خێراWhich step makes the list of error messages?کام هەنگاو پەیامەکانی دروست دەکات؟

Part 3: the algorithmبەشی 3: ئەلگۆریزم

The algorithm, steps 7 to 12ئەلگۆریزم، هەنگاوەکانی 7 تا ⁦12⁩

Steps 7–12 define the function Inputs, call it and make sure the choice is 2 or 3:

هەنگاوەکانی ⁦7–12⁩ Inputs دەناسێنن، بانگی دەکەن و دڵنیا دەبنەوە کە هەڵبژاردنەکە 2 یان 3ـە:

StepهەنگاوWhat the program does چی دەکات
7Define the function Inputs with one parameter, num. بە ناوی Inputs دەناسێنێت کە یەک هەیە بە ناوی num.
8Write a print() that calls Inputs (step 7) and prints what it returns.print()ـێک دەنووسێت کە Inputs (هەنگاوی ⁦7⁩) بانگ دەکات و ئەوەی دەیگەڕێنێتەوە چاپی دەکات.
9Ask the user to type 2 or 3.داوا لە دەکات 2 یان 3 بنووسێت.
10Whatever the user types goes into Inputs as num.هەرچی بینووسێت وەک num دەچێتە ناو Inputs.
11Inside Inputs, set the Boolean variable CorrectInput to False and the string variable result to an empty string.لەناو Inputsـدا CorrectInput دەکرێتە False و result دەکرێتە بەتاڵ.
12A loop checks num: while it is neither 2 nor 3, print errorMsg[0] (the list from step 6, index 0) and ask again. The loop ends when the user types 2 or 3. num دەپشکنێت: تا ئەو کاتەی نە 2ـە و نە 3، errorMsg[0] چاپ دەکات ( هەنگاوی 6، ⁦0⁩) و دووبارە دەپرسێتەوە. کاتێک کۆتایی دێت کە 2 یان 3 بنووسێت.
Quick checkپشکنینی خێراWhich step makes sure the user can only continue with 2 or 3?کام هەنگاو دڵنیا دەبێتەوە کە تەنها بە 2 یان 3 بەردەوام دەبێت؟

Part 3: the algorithmبەشی 3: ئەلگۆریزم

The algorithm, steps 13 to 18ئەلگۆریزم، هەنگاوەکانی ⁦13⁩ تا ⁦18⁩

Steps 13–18 read two digits, check them and convert them:

هەنگاوەکانی ⁦13–18⁩ دوو دەخوێننەوە، دەیانپشکنن و دەیانگۆڕن:

StepهەنگاوWhat the program does چی دەکات
13If num is 2, make the variable Digits holding an empty string.ئەگەر num یەکسانی 2 بوو، Digits دروست دەکات کە بەتاڵی تێدایە.
14Start a loop that repeats while CorrectInput (step 11) is False; the first time it goes straight in. دەست پێ دەکات کە تا CorrectInput (هەنگاوی ⁦11⁩) False بێت دووبارە دەبێتەوە؛ جاری یەکەم ڕاستەوخۆ دەچێتە ناوی.
15Read two binary digits from the user into Digits.دوو لە دەخوێنێتەوە بۆ ناو Digits.
16If the length of Digits is not 2, print errorMsg[1] and ask again (continue).ئەگەر درێژیی Digits 2 نەبوو، errorMsg[1] چاپ دەکات و دووبارە دەپرسێتەوە (continue).
17If step 16 passed, an if checks that the first and the second character are each 0 or 1. If so, CorrectInput becomes True; if not, the else prints errorMsg[2].ئەگەر هەنگاوی ⁦16⁩ تێپەڕی، ifـێک دەپشکنێت ئایا یەکەم و دووەم هەر یەکەیان 0 یان 1ـە. ئەگەر وابوو CorrectInput دەبێتە True؛ ئەگەرنا بەشی else پەیامی errorMsg[2] چاپ دەکات.
18With valid digits, an if–elif chain compares them with the table (00→0, 01→1, 10→2, 11→3) and stores the decimal value in result.کاتێک دروست بوون، زنجیرەیەکی if–elif بەراوردیان دەکات لەگەڵ خشتەکە (00→0، 01→1، 10→2، 11→3) و دەخاتە ناو resultـەوە.
Quick checkپشکنینی خێراThe user typed 1a after choosing 2. Which step prints a message? دوای هەڵبژاردنی 2، 1aـی نووسی. کام هەنگاو پەیامێک چاپ دەکات؟

Part 3: the algorithmبەشی 3: ئەلگۆریزم

The algorithm, steps 19 to 22ئەلگۆریزم، هەنگاوەکانی ⁦19⁩ تا ⁦22⁩

Steps 19–22 handle three digits, print the answer and, in the final version, offer to run again:

هەنگاوەکانی ⁦19–22⁩ سێ چارەسەر دەکەن، وەڵامەکە چاپ دەکەن و لە وەشانی کۆتاییدا پێشنیاری دووبارە کارکردنەوە دەکەن:

StepهەنگاوWhat the program does چی دەکات
19Back at step 13: if num is 3 instead, the same steps run for three digits (errorMsg[3] for a wrong length, an eight-row table).دەگەڕێینەوە بۆ هەنگاوی ⁦13⁩: ئەگەر num لەبری 2 یەکسانی 3 بوو، هەمان هەنگاوەکان بۆ سێ جێبەجێ دەبن (errorMsg[3] بۆ درێژیی هەڵە و خشتەیەکی هەشت ڕیزی).
20Inputs returns result, and the print() of step 8 prints it as the decimal number.Inputs result دەگەڕێنێتەوە و print()ـەکەی هەنگاوی 8 وەک ژمارە چاپی دەکات.
21Ask Do you want to run the program again? (y/n). Accept only y or n (anything else prints Invalid input. and asks again). y repeats steps 2 to 20; n prints Goodbye! and stops the loop. (Final version only.)دەپرسێت Do you want to run the program again? (y/n). تەنها y یان n وەردەگرێت (هەر شتێکی تر Invalid input. چاپ دەکات و دووبارە دەپرسێت). y هەنگاوەکانی 2 تا ⁦20⁩ دووبارە دەکاتەوە؛ n پەیامی Goodbye! چاپ دەکات و دەوەستێنێت. (تەنها وەشانی کۆتایی.)
22End the program.کۆتایی .
Quick checkپشکنینی خێراWhich step exists only in the final version, not in the Kurdish report?کام هەنگاو تەنها لە وەشانی کۆتاییدا هەیە و لە ڕاپۆرتە کوردییەکەدا نییە؟

Part 3: the algorithmبەشی 3: ئەلگۆریزم

What was corrected in the algorithmچی لە ئەلگۆریزمەکەدا ڕاست کرایەوە

Quick checkپشکنینی خێراWhy did the English algorithm's step references point one step too early?بۆچی ئاماژەکانی ئینگلیزییەکە بۆ هەنگاوەکان یەک هەنگاو زووتریان دەگرت؟

Part 4: the code, piece by pieceبەشی 4: کۆدەکە، پارچە بە پارچە

The final program has 99 lines. Everything except the run-again loop lives inside one function, program(). We read it in five pieces; the complete program follows at the end of this part. Piece 1 prints the title, reads the name and prepares the two lists:

کۆتاییەکە ⁦99⁩ دێڕە. هەموو شتێک جگە لە دووبارە کارکردنەوە لەناو یەک دایە، program(). بە پێنج پارچە دەیخوێنینەوە؛ تەواوەکە لە کۆتایی ئەم بەشەدا دێت. پارچەی 1 ناونیشان چاپ دەکات، ناوەکە دەخوێنێتەوە و دوو ئامادە دەکات:

Piece 1: lines 1–12پارچەی 1: دێڕەکانی ⁦1–12⁩PYTHONType in a terminalلە تێرمیناڵدا بینووسە
def program():
    print("*" * 41)
    print("Binary to Decimal Converter (2-3 inputs)")
    print("*" * 41)

    name = input("Please enter your name to get started: ")
    validNums = ["2", "3"]
    errorMsg = [f"Only {validNums[0]} or {validNums[1]} are valid.",
                "Only two binary numbers are valid!",
                "You can only enter 0 or 1.",
                "Only three binary numbers are valid!"
                ]
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2-4

"*" * 41 repeats the star 41 times: a frame around the title.

"*" * 41 ئەستێرە ⁦41⁩ جار دووبارە دەکاتەوە: چوارچێوەیەک بە دەوری ناونیشاندا.

Lineدێڕی 7

The valid choices are strings, because input() always returns a string.

هەڵبژاردە دروستەکان ، چونکە input() هەمیشە دەگەڕێنێتەوە.

Lineدێڕی 8-12

Four messages; the first is an f-string that puts the two choices into the text: Only 2 or 3 are valid.

چوار پەیام؛ یەکەمیان بە نووسراوە کە دوو هەڵبژاردەکە دەخاتە ناو دەقەکەوە: Only 2 or 3 are valid.

Quick checkپشکنینی خێراWhy does the final version store "2" and "3" in quotes?بۆچی وەشانی کۆتایی "2" و "3" لەناو هەڵدەگرێت؟

Part 4: the code, piece by pieceبەشی 4: کۆدەکە، پارچە بە پارچە

Piece 2: checking the choiceپارچەی 2: پشکنینی هەڵبژاردن

Inputs is defined inside program(), so it can use name, validNums and errorMsg from there (see Variable scope). Its first job is a validation loop: ask again while the answer is neither "2" nor "3".

Inputs لە ناو program()ـدا ناسێنراوە، بۆیە دەتوانێت name، validNums و errorMsgـی ئەوێ بەکار بهێنێت (سەیری مەودای گۆڕاوەکان بکە). یەکەم کاری : دووبارە بپرسە تا وەڵامەکە نە "2"ـە و نە "3".

Piece 2: lines 14–22 (inside program())پارچەی 2: دێڕەکانی ⁦14–22⁩ (لەناو ⁦program()⁩)PYTHONType in a terminalلە تێرمیناڵدا بینووسە
def Inputs(num):
    CorrectInput = False
    result = ""

    while num != "2" and num != "3":
        print(errorMsg[0])
        num = str(input("Hello " + name +
                        f"! Choose the number of inputs you"
                        f"like to enter {validNums}: "))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2-3

A Boolean flag (False until the digits are good) and the answer, empty for now.

ئاڵایەکی (تا باش دەبن Falseـە) و وەڵامەکە کە ئێستا بەتاڵە.

Lineدێڕی 5

and: repeat while the answer is not "2" and not "3".

and: دووبارە بکەرەوە تا وەڵامەکە "2" نییە و "3" نییە.

Lineدێڕی 7-9

Ask again. The two f-string pieces are joined with no space between them (a bug, see Finding the bugs).

دووبارە دەپرسێتەوە. دوو پارچەی بەبێ لە نێوانیاندا پێکەوە دەلکێن (، سەیری دۆزینەوەی بکە).

Quick checkپشکنینی خێراWhat would happen if line 5 used or: while num != "2" or num != "3":?ئەگەر دێڕی 5 orـی بەکار بهێنایە چی ڕوو دەدا: while num != "2" or num != "3":؟

Part 4: the code, piece by pieceبەشی 4: کۆدەکە، پارچە بە پارچە

Piece 3: two digitsپارچەی 3: دوو تاکژمارە

For two digits a second validation loop runs. It uses the flag CorrectInput: the loop goes round while the flag is False, and only a fully valid input sets it to True. Then an if–elif chain looks the answer up in the table.

بۆ دوو ، دووەمی کار دەکات. ئاڵای CorrectInput بەکار دەهێنێت: تا ئاڵاکە False بێت دەسووڕێتەوە و تەنها تەواو دروست دەیکاتە True. پاشان زنجیرەیەکی if–elif وەڵامەکە لە خشتەکەدا دەدۆزێتەوە.

Piece 3: lines 24–45پارچەی 3: دێڕەکانی ⁦24–45⁩PYTHONType in a terminalلە تێرمیناڵدا بینووسە
if num == "2":
    Digits = ""

    while CorrectInput == False:
        Digits = input("Enter two binary digits: ")
        if len(Digits) != 2 or len(Digits) < 2:
            print(errorMsg[1])
            continue
        if (Digits[0] == "1" or Digits[0] == "0")\
                and (Digits[1] == "1" or Digits[1] == "0"):
            CorrectInput = True
        else:
            print(errorMsg[2])

    if Digits[0] == "0" and Digits[1] == "0":
        result = "0"
    elif Digits[0] == "0" and Digits[1] == "1":
        result = "1"
    elif Digits[0] == "1" and Digits[1] == "0":
        result = "2"
    elif Digits[0] == "1" and Digits[1] == "1":
        result = "3"
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 6-8

Wrong length: print the message, then continue jumps back to the top of the loop at once.

درێژیی هەڵە: پەیامەکە چاپ دەکات، پاشان continue یەکسەر باز دەداتەوە سەرەتای .

Lineدێڕی 9-10

Each character must be "1" or "0". The backslash at the end of line 9 continues the condition on the next line.

هەر دەبێت "1" یان "0" بێت. ⁦(backslash)⁩ لە کۆتایی دێڕی 9 لە دێڕی داهاتوودا درێژ دەکاتەوە.

Lineدێڕی 15-22

The 2-digit table as four if/elif branches.

خشتەی دوو وەک چوار لقی if/elif.

Quick checkپشکنینی خێراThe user types 3 (one character) for two digits. Which line stops this input? بۆ دوو 3 دەنووسێت (یەک ). کام دێڕ ئەم ڕادەگرێت؟

Part 4: the code, piece by pieceبەشی 4: کۆدەکە، پارچە بە پارچە

Piece 4: three digitsپارچەی 4: سێ تاکژمارە

The three-digit branch repeats the same idea with a third character to check and an eight-row table. This time the table compares the whole string, Digits == "101", which is shorter than checking each position.

لقی سێ هەمان بیرۆکە دووبارە دەکاتەوە بە سێیەم بۆ پشکنین و خشتەیەکی هەشت ڕیزی. ئەم جارە خشتەکە هەموو بەراورد دەکات، Digits == "101"، کە لە پشکنینی هەر شوێنێک کورتترە.

Piece 4: lines 47–76پارچەی 4: دێڕەکانی ⁦47–76⁩PYTHONType in a terminalلە تێرمیناڵدا بینووسە
elif num == "3":
    while CorrectInput == False:
        Digits = input("Enter three binary digits: ")
        if len(Digits) != 3:
            print(errorMsg[3])
            continue
        if (Digits[0] == "1" or Digits[0] == "0") and\
                (Digits[1] == "1" or Digits[1] == "0") and\
                (Digits[2] == "1" or Digits[2] == "0"):
            CorrectInput = True
        else:
            print(errorMsg[2])

    if Digits == "000":  # 0
        result = "0"
    elif Digits == "001":  # 1
        result = "1"
    elif Digits == "010":  # 2
        result = "2"
    elif Digits == "011":  # 3
        result = "3"
    elif Digits == "100":  # 4
        result = "4"
    elif Digits == "101":  # 5
        result = "5"
    elif Digits == "110":  # 6
        result = "6"
    elif Digits == "111":  # 7
        result = "7"
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4-6

errorMsg[3] for a wrong length.

errorMsg[3] بۆ درێژیی هەڵە.

Lineدێڕی 7-9

Three characters, three tests, joined with and.

سێ ، سێ تاقیکردنەوە، بە and پێکەوە بەستراون.

Lineدێڕی 14-29

Eight cases: every 3-digit binary number from 000 to 111.

هەشت حاڵەت: هەموو ژمارەیەکی سێ لە ⁦000⁩ تا ⁦111⁩.

Quick checkپشکنینی خێراWhich result does the table give for "110"?خشتەکە بۆ "110" کام result دەدات؟

Part 4: the code, piece by pieceبەشی 4: کۆدەکە، پارچە بە پارچە

Piece 5: returning and running againپارچەی 5: گەڕاندنەوە و دووبارە کارکردنەوە

Inputs returns result. The last statement of program() asks for the choice and prints whatever Inputs returns, all in one line. Outside the function, program() runs once, then an outer while True: loop offers to run it again, with an inner loop that accepts only y or n.

Inputs result دەگەڕێنێتەوە. دوایین program() هەڵبژاردنەکە دەپرسێت و هەرچی Inputs بیگەڕێنێتەوە چاپی دەکات، هەمووی لە یەک دێڕدا. لە دەرەوەی ، program() یەک جار کار دەکات، پاشان دەرەکیی while True: پێشنیاری دووبارە کارکردنەوەی دەکات و ناوەکی تەنها y یان n وەردەگرێت.

Piece 5: lines 77–99پارچەی 5: دێڕەکانی ⁦77–99⁩PYTHONType in a terminalلە تێرمیناڵدا بینووسە
        return result

    print("The entered binary number in decimal is:",
          Inputs(input("Hello " + name +
                       f"! Choose the number of inputs you"
                       f"like to enter {validNums}: ")))

program()

while True:
    # main program
    while True:
        print()
        answer = str(input('Do you want to run the program again? (y/n): '))
        if answer in ('y', 'n'):
            break
        print("Invalid input.")
    if answer == 'y':
        print()
        program()
    else:
        print("Goodbye!")
        break
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3-6

input() runs first and its answer goes straight into Inputs(...); the result is printed.

سەرەتا input() جێبەجێ دەبێت و وەڵامەکەی ڕاستەوخۆ دەچێتە ناو Inputs(...)؛ ئەنجامەکە چاپ دەکرێت.

Lineدێڕی 8

The first run.

یەکەم جار کارپێکردن.

Lineدێڕی 12-17

The inner loop: only y or n can leave it (break).

ناوەکییەکە: تەنها y یان n دەتوانن لێی دەربچن (break).

Lineدێڕی 18-23

y runs the whole program again; n says goodbye and break ends the outer loop.

y هەموو دووبارە کار پێ دەکاتەوە؛ n ماڵئاوایی دەکات و break دەرەکییەکە کۆتایی پێ دەهێنێت.

Quick checkپشکنینی خێراWhy is there a loop inside the run-again loop?بۆچی لە ناو دووبارە کارکردنەوەدا هەیە؟

Part 4: the code, piece by pieceبەشی 4: کۆدەکە، پارچە بە پارچە

The complete program and two runsبەرنامە تەواوەکە و دوو جار کارپێکردن

Here are all 99 lines together, exactly as the group presented them (their slides showed the code as editor screenshots on two slides). The two runs below use the group's own test inputs, with neutral names. Look at the second line of each greeting: you will find the first bug there.

ئەمە هەر ⁦99⁩ دێڕەکەیە پێکەوە، ڕێک وەک گرووپەکە پێشکەشیان کرد (سلایدەکانیان کۆدەکەیان وەک وێنەی ئێدیتەر لەسەر دوو سلاید پیشان دەدا). دوو کارپێکردنەکەی خوارەوە هەمان تاقیکردنەوەی گرووپەکە بەکار دەهێنن، بە ناوی بێلایەن. سەیری پرسیارەکەی دوای بەخێرهاتن بکە: یەکەم لەوێدا دەدۆزیتەوە.

The final version: converter_final.pyوەشانی کۆتایی: ⁦converter_final.py⁩converter_final.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def program():
    print("*" * 41)
    print("Binary to Decimal Converter (2-3 inputs)")
    print("*" * 41)

    name = input("Please enter your name to get started: ")
    validNums = ["2", "3"]
    errorMsg = [f"Only {validNums[0]} or {validNums[1]} are valid.",
                "Only two binary numbers are valid!",
                "You can only enter 0 or 1.",
                "Only three binary numbers are valid!"
                ]

    def Inputs(num):
        CorrectInput = False
        result = ""

        while num != "2" and num != "3":
            print(errorMsg[0])
            num = str(input("Hello " + name +
                            f"! Choose the number of inputs you"
                            f"like to enter {validNums}: "))

        if num == "2":
            Digits = ""

            while CorrectInput == False:
                Digits = input("Enter two binary digits: ")
                if len(Digits) != 2 or len(Digits) < 2:
                    print(errorMsg[1])
                    continue
                if (Digits[0] == "1" or Digits[0] == "0")\
                        and (Digits[1] == "1" or Digits[1] == "0"):
                    CorrectInput = True
                else:
                    print(errorMsg[2])

            if Digits[0] == "0" and Digits[1] == "0":
                result = "0"
            elif Digits[0] == "0" and Digits[1] == "1":
                result = "1"
            elif Digits[0] == "1" and Digits[1] == "0":
                result = "2"
            elif Digits[0] == "1" and Digits[1] == "1":
                result = "3"

        elif num == "3":
            while CorrectInput == False:
                Digits = input("Enter three binary digits: ")
                if len(Digits) != 3:
                    print(errorMsg[3])
                    continue
                if (Digits[0] == "1" or Digits[0] == "0") and\
                        (Digits[1] == "1" or Digits[1] == "0") and\
                        (Digits[2] == "1" or Digits[2] == "0"):
                    CorrectInput = True
                else:
                    print(errorMsg[2])

            if Digits == "000":  # 0
                result = "0"
            elif Digits == "001":  # 1
                result = "1"
            elif Digits == "010":  # 2
                result = "2"
            elif Digits == "011":  # 3
                result = "3"
            elif Digits == "100":  # 4
                result = "4"
            elif Digits == "101":  # 5
                result = "5"
            elif Digits == "110":  # 6
                result = "6"
            elif Digits == "111":  # 7
                result = "7"

        return result

    print("The entered binary number in decimal is:",
          Inputs(input("Hello " + name +
                       f"! Choose the number of inputs you"
                       f"like to enter {validNums}: ")))

program()

while True:
    # main program
    while True:
        print()
        answer = str(input('Do you want to run the program again? (y/n): '))
        if answer in ('y', 'n'):
            break
        print("Invalid input.")
    if answer == 'y':
        print()
        program()
    else:
        print("Goodbye!")
        break
Quick checkپشکنینی خێراIn the second run, why does 101 get Only two binary numbers are valid! although all its digits are 0 or 1?لە کارپێکردنی دووەمدا، بۆچی 101 پەیامی Only two binary numbers are valid! وەردەگرێت لە کاتێکدا هەموو 0 یان 1ـن؟

Part 5: testing with examplesبەشی 5: تاقیکردنەوە بە نموونە

The last part of the plan is to run the program on examples and show the results. The group showed four examples in the presentation and three in the report; they are the same cases:

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

The group's examples (names replaced by neutral ones).نموونەکانی گرووپەکە (ناوەکان بە ناوی بێلایەن گۆڕدراون).
ExampleنموونەThe user types دەنووسێتThe program shows پیشان دەدات
1. Enter a name1. نووسینی ناوAramHello Aram! Choose the number of inputs …
2. A valid number2. ژمارەیەکی دروست2, then 11The entered binary number in decimal is: 3
3. A non-valid number3. ژمارەیەکی نادروست2, then 3Only two binary numbers are valid!
4. Exiting the program4. دەرچوون لە 3, then 101, then n… is: 5, then Goodbye!
Example 4 as a real run of converter_final.pyنموونەی 4 وەک کارپێکردنێکی ڕاستەقینەی ⁦converter_final.py⁩
*****************************************
Binary to Decimal Converter (2-3 inputs)
*****************************************
Please enter your name to get started: Hana
Hello Hana! Choose the number of inputs youlike to enter ['2', '3']: 3
Enter three binary digits: 101
The entered binary number in decimal is: 5

Do you want to run the program again? (y/n): n
Goodbye!

Good testing goes further than a few happy examples. The program knows only 12 valid inputs, so we can try all of them and compare each answer with Python's own int(digits, 2). This table was filled by running the program 12 times:

تاقیکردنەوەی باش لە چەند نموونەیەکی سەرکەوتوو زیاتر دەڕوات. تەنها ⁦12⁩ دروست دەناسێت، بۆیە دەتوانین هەموویان تاقی بکەینەوە و هەر وەڵامێک لەگەڵ int(digits, 2)ـی خودی بەراورد بکەین. ئەم خشتەیە بە ⁦12⁩ جار کارپێکردنی پڕ کراوەتەوە:

DigitsExpectedچاوەڕوانکراوProgram printed چاپی کردOKدروست
0000✓
0111✓
1022✓
1133✓
00000✓
00111✓
01022✓
01133✓
10044✓
10155✓
11066✓
11177✓
Quick checkپشکنینی خێراWhy can this project be tested completely, while most programs cannot?بۆچی ئەم پڕۆژەیە بە تەواوی تاقی دەکرێتەوە، لە کاتێکدا زۆربەی ناکرێن؟

Part 5: testing with examplesبەشی 5: تاقیکردنەوە بە نموونە

Testing wrong inputsتاقیکردنەوەی نێوخستەی هەڵە

A user can type anything at the first question: a word, an empty line, a number with a space. The final version never converts the choice to a number; it only compares strings, so none of these can crash it:

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

converter_final.py: a word instead of a number⁦converter_final.py⁩: وشەیەک لەبری ژمارە
*****************************************
Binary to Decimal Converter (2-3 inputs)
*****************************************
Please enter your name to get started: Aram
Hello Aram! Choose the number of inputs youlike to enter ['2', '3']: two
Only 2 or 3 are valid.
Hello Aram! Choose the number of inputs youlike to enter ['2', '3']: 2
Enter two binary digits: 01
The entered binary number in decimal is: 1

Do you want to run the program again? (y/n): n
Goodbye!
Quick checkپشکنینی خێراThe final version gets two at the first question. What happens?وەشانی کۆتایی لە پرسیاری یەکەمدا two وەردەگرێت. چی ڕوو دەدات؟

The first version and its crashیەکەم وەشان و کەوتنەکەی

The Kurdish report shows an earlier version of the code (as screenshots, 80 lines). It works the same way, with three differences: there is no program() function and no run-again loop, and the choices are the integers 2 and 3, read with int(input(...)). Here are its first 22 lines and its last statement; the digit checks and the two tables in between are the same as in the final version.

ڕاپۆرتە کوردییەکە وەشانێکی پێشووتری کۆدەکە پیشان دەدات (وەک وێنە، ⁦80⁩ دێڕ). هەمان شێوە کار دەکات، بە سێ جیاوازی: program() و دووبارە کارکردنەوەی تێدا نییە و هەڵبژاردەکان 2 و 3ـن کە بە int(input(...)) دەخوێنرێنەوە. ئەمە یەکەم ⁦22⁩ دێڕی و دوایین ؛ پشکنینی و دوو خشتەکەی نێوانیان وەک وەشانی کۆتایین.

The first version, lines 1–22یەکەم وەشان، دێڕەکانی ⁦1–22⁩PYTHONType in a terminalلە تێرمیناڵدا بینووسە
print("*" * 41)
print("Binary to Decimal Converter (2-3 inputs)")
print("*" * 41)

name = input("Please enter your name to get started: ")
validNums = [2, 3]
errorMsg = [f"Only {validNums[0]} or {validNums[1]} are valid.",
            "Only two binary numbers are valid!",
            "You can only enter 0 or 1.",
            "Only three binary numbers are valid!"
            ]

def Inputs(num):
    CorrectInput = False
    result = ""

    while num != 2 and num != 3:
        print(errorMsg[0])
        num = int(input("Hello " + name +
                        f"! Choose the number of inputs you like to enter {validNums}: "))

    if num == 2:
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 6

Integers this time: [2, 3].

ئەم جارە : [2, 3].

Lineدێڕی 19-20

int(input(...)) turns the answer into a number before any check.

int(input(...)) پێش هەر پشکنینێک وەڵامەکە دەکات بە ژمارە.

The first version, lines 78–80یەکەم وەشان، دێڕەکانی ⁦78–80⁩PYTHONType in a terminalلە تێرمیناڵدا بینووسە
print("The entered binary number in decimal is: ",
      Inputs(int(input("Hello " + name +
                       f"! Choose the number of inputs you like to enter {validNums}: "))))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

The text ends with a space, and print() adds another one between its two values: the output shows is: 3 with two spaces.

دەقەکە بە کۆتایی دێت و print() یەکێکی تر لە نێوان دوو زیاد دەکات: is: 3 بە دوو پیشان دەدات.

Two normal runs of the first versionدوو کارپێکردنی ئاسایی یەکەم وەشان
*****************************************
Binary to Decimal Converter (2-3 inputs)
*****************************************
Please enter your name to get started: Aram
Hello Aram! Choose the number of inputs you like to enter [2, 3]: 2
Enter two binary digits: 11
The entered binary number in decimal is:  3

*****************************************
Binary to Decimal Converter (2-3 inputs)
*****************************************
Please enter your name to get started: Aram
Hello Aram! Choose the number of inputs you like to enter [2, 3]: 3
Enter three binary digits: 101
The entered binary number in decimal is:  5

Now type a word at the first question. int("two") raises a ValueError before any check can run, and the program crashes:

ئێستا لە پرسیاری یەکەمدا وشەیەک بنووسە. int("two") پێش ئەوەی هیچ پشکنینێک کار بکات ValueError دروست دەکات و دەکەوێت:

The first version crashesیەکەم وەشان دەکەوێت
*****************************************
Binary to Decimal Converter (2-3 inputs)
*****************************************
Please enter your name to get started: Aram
Hello Aram! Choose the number of inputs you like to enter [2, 3]: two
Traceback (most recent call last):
  File "converter_first.py", line 79, in <module>
    Inputs(int(input("Hello " + name +
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'two'
The first version with get_int(): the changed partsیەکەم وەشان بە ⁦get_int()⁩: بەشە گۆڕدراوەکانPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def get_int(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Please type a whole number.")

# inside Inputs(): ask again with get_int() instead of int(input())
num = get_int("Hello " + name +
              f"! Choose the number of inputs you like to enter {validNums}: ")

# the last statement: the first question uses get_int() too
print("The entered binary number in decimal is: ",
      Inputs(get_int("Hello " + name +
                     f"! Choose the number of inputs you like to enter {validNums}: ")))
Quick checkپشکنینی خێراWhy did the final version NOT crash on two?بۆچی وەشانی کۆتایی بە two نەکەوت؟

Finding the bugsدۆزینەوەی باگەکان

The program works, but a careful reader finds several problems. The most visible one is in the greeting. The question is built from two f-strings written on two lines, and Python joins them with no space:

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

The bug and its fixباگەکە و چارەسەرەکەیyoulike.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
name = "Aram"
valid = ["2", "3"]
question = ("Hello " + name +
            f"! Choose the number of inputs you"
            f"like to enter {valid}: ")
print(question)
fixed = f"Hello {name}! How many binary digits, 2 or 3? "
print(fixed)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3-5

Two string pieces next to each other are joined into one string. "you" + "like" gives youlike. The list is also printed as Python sees it, ['2', '3'].

دوو پارچە کە لە تەنیشت یەکترن دەبنە یەک . "you" + "like" دەکاتە youlike. وەک دەیبینێت چاپ دەکرێت، ['2', '3'].

Lineدێڕی 7

One f-string, a clear question, no list.

یەک ، پرسیارێکی ڕوون، بێ .

Quick checkپشکنینی خێراWhy did the greeting print youlike?بۆچی پرسیارەکە youlikeـی چاپ کرد؟

Finding the bugsدۆزینەوەی باگەکان

More problems: style and small mistakesکێشەی تر: شێواز و هەڵەی بچووک

ProblemکێشەWhereلە کوێBetterباشتر
Missing space: youlikeنەبوونی : youlikethe choice questionپرسیاری هەڵبژاردنOne string: f"Hello {name}! How many binary digits, 2 or 3? "یەک : f"Hello {name}! How many binary digits, 2 or 3? "
The list is printed raw: ['2', '3'] وەک خۆی چاپ دەکرێت: ['2', '3']the same questionهەمان پرسیارWrite 2 or 3 in the text.لە دەقەکەدا 2 or 3 بنووسە.
len(Digits) != 2 or len(Digits) < 2len(Digits) != 2 or len(Digits) < 22-digit checkپشکنینی دوو len(Digits) != 2 already covers less than 2.len(Digits) != 2 پێشتر کەمتر لە 2ـیش دەگرێتەوە.
while CorrectInput == False:while CorrectInput == False:both digit loopsهەردوو while not correct_input: (PEP 8: do not compare Booleans with ==)while not correct_input: (⁦PEP 8⁩: بە == بەراورد مەکە)
Names Inputs, Digits, CorrectInput, validNums, errorMsgناوەکانی Inputs، Digits، CorrectInput، validNums، errorMsgeverywhereهەموو شوێنێکsnake_case: read_choice, digits, correct_input, valid_choices, error_messages: read_choice، digits، correct_input، valid_choices، error_messages
str(input(...))str(input(...))lines 20 and 90دێڕەکانی ⁦20⁩ و ⁦90⁩input() already returns a string: just input(...).input() خۆی دەگەڕێنێتەوە: تەنها input(...).
A backslash at the end of a line to continue a condition ⁦(backslash)⁩ لە کۆتایی دێڕ بۆ درێژکردنەوەی lines 32 and 53–54دێڕەکانی ⁦32⁩ و ⁦53–54⁩Wrap the condition in brackets; PEP 8 prefers that. بخەرە ناو کەوانەوە؛ ⁦PEP 8⁩ ئەوەی پێ باشترە.
Messages say binary numbers but mean binary digitsپەیامەکان دەڵێن ⁦binary numbers⁩ بەڵام مەبەستیان ⁦binary digits⁩ـەerrorMsg[1], errorMsg[3]errorMsg[1]، errorMsg[3]Only two binary digits are valid!Only two binary digits are valid!
One table branch per inputیەک لقی خشتە بۆ هەر both tablesهەردوو خشتەکەA loop or int(digits, 2) works for any length (next part). یان int(digits, 2) بۆ هەر درێژییەک کار دەکات (بەشی داهاتوو).
The two-digit check, cleaned upپشکنینی دوو تاکژمارە، پاککراوەtwo_digits_fixed.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def read_two_digits():
    correct_input = False
    while not correct_input:
        digits = input("Enter two binary digits: ")
        if len(digits) != 2:
            print("Only two binary digits are valid!")
            continue
        if digits[0] in ("0", "1") and digits[1] in ("0", "1"):
            correct_input = True
        else:
            print("You can only enter 0 or 1.")
    return digits


print("You typed", read_two_digits())
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

not reads like English: while not correct input.

not وەک ئینگلیزی دەخوێنرێتەوە: ⁦while not correct input⁩.

Lineدێڕی 5

One length test is enough.

یەک تاقیکردنەوەی درێژی بەسە.

Lineدێڕی 8

in ("0", "1") replaces == "1" or == "0" and needs no backslash.

in ("0", "1") جێگەی == "1" or == "0" دەگرێتەوە و پێویستی بە ⁦(backslash)⁩ نییە.

Quick checkپشکنینی خێراIn len(Digits) != 2 or len(Digits) < 2, which part can go?لە len(Digits) != 2 or len(Digits) < 2ـدا، کام بەش دەتوانرێت لاببرێت؟

Improving the converter: any lengthباشترکردنی گۆڕەرەکە: هەر درێژییەک

The tables are the program's biggest weakness. Every extra digit doubles the number of elif branches: 4 digits would need 16, 8 digits 256. A loop can convert any length with three lines. Read the digits from left to right; before adding each new digit, double the value you have so far:

خشتەکان گەورەترین لاوازیی . هەر زیادە ژمارەی لقەکانی elif دوو هێندە دەکات: 4 ⁦16⁩ـی پێویستە و 8 ⁦256⁩. دەتوانێت بە سێ دێڕ هەر درێژییەک بگۆڕێت. لە چەپەوە بۆ ڕاست بخوێنەوە؛ پێش زیادکردنی هەر نوێ، ئەو تا ئێستا هەتە دوو هێندە بکە:

Value × 2 + digitنرخ × ⁦2 +⁩ تاکژمارەdoubling.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def binary_to_decimal(digits):
    value = 0
    for digit in digits:
        value = value * 2 + int(digit)
        print(f"read {digit}: value = {value}")
    return value


print("Result:", binary_to_decimal("1011"))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

Doubling moves every digit read so far one place to the left (each place is worth twice the one to its right); then the new digit is added in the ones place.

دوو هێندەکردن هەموو کە تا ئێستا خوێندراونەتەوە یەک خانە بەرەو چەپ دەبات (هەر خانەیەک دوو هێندەی خانەکەی لای ڕاستی دەهێنێت)؛ پاشان نوێیەکە لە خانەی یەکەکاندا زیاد دەکرێت.

(1011)2=((1×2+0)×2+1)×2+1=11(1011)_2 = ((1 \times 2 + 0) \times 2 + 1) \times 2 + 1 = 11

The same calculation written as one formula. Logic Design calls it double and add.

هەمان هەژمارکردن وەک یەک هاوکێشە. کۆرسی دیزاینی پێی دەڵێت دوو هێندە بکە و زیاد بکە.

Why this method works is explained in A shortcut for long numbers: double and add.

بۆچی ئەم ڕێگایە کار دەکات لە کورتەڕێیەک بۆ ژمارەی درێژ: دوو هێندە بکە و زیاد بکە ڕوون کراوەتەوە.

Quick checkپشکنینی خێراWith the loop value = value * 2 + int(digit), what is value after reading "110"?بە value = value * 2 + int(digit)، دوای خوێندنەوەی "110" value چەندە؟

Improving the converter: any lengthباشترکردنی گۆڕەرەکە: هەر درێژییەک

Python can do it for you: int(x, 2) and bin()Python بۆت دەکات: ⁦int(x, 2)⁩ و ⁦bin()⁩

Python's built-in int() takes a second argument, the base. int("101", 2) reads the text as a binary number. The opposite direction is bin(), which returns a string that starts with 0b; an f-string with :b gives the bits without the prefix.

int()ـی ئامادەی دووەم وەردەگرێت، . int("101", 2) دەقەکە وەک ژمارەیەکی دەخوێنێتەوە. ئاڕاستە پێچەوانەکە bin()ـە کە دەگەڕێنێتەوە بە 0b دەست پێ دەکات؛ بە :b بەبێ پێشگرەکە دەدات.

Built-in conversionsگۆڕینە ئامادەکانbuiltins_demo.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
print(int("101", 2))
print(int("11", 2), int("111", 2))
print(int("1011", 2))
print(bin(5))
print(f"{5:b}", format(13, "b"))
print(f"{5:03b}")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

Base 2: "101" means 4+0+14 + 0 + 1.

2: "101" واتە 4+0+14 + 0 + 1.

Lineدێڕی 4

bin() adds the prefix 0b, like a binary literal in Python code.

bin() پێشگری 0b زیاد دەکات، وەک ژمارەیەکی لە کۆدی .

Lineدێڕی 6

:03b pads with zeros to three bits.

:03b بە سفر پڕی دەکاتەوە تا سێ .

There is a catch: int(text, 2) is generous. It also accepts spaces around the digits, a minus sign, the 0b prefix, underscores between digits and even Kurdish/Arabic digits. That is right for Python code, but a teaching program that asks for only 0s and 1s should check first. A set does it in one line:

داوێک هەیە: int(text, 2) زۆر بەخشندەیە. لە دەوری ، نیشانەی سالب، پێشگری 0b، _ لە نێوان و تەنانەت ژمارەی کوردی/عەرەبیش وەردەگرێت. ئەمە بۆ کۆدی دروستە، بەڵام فێرکاری کە تەنها 0 و 1 داوا دەکات دەبێت سەرەتا بپشکنێت. لە یەک دێڕدا دەیکات:

What int(text, 2) accepts⁦int(text, 2)⁩ چی وەردەگرێتlenient.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
for text in ["101", " 101 ", "-101", "0b101", "1_01", "١٠١", "102", ""]:
    try:
        result = int(text, 2)
    except ValueError:
        result = "ValueError"
    print(repr(text), "->", result)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

Eight test strings, from normal to strange. "١٠١" is 101 written with Kurdish digits.

هەشت تاقیکردنەوە، لە ئاساییەوە بۆ سەیر. "١٠١" هەمان ⁦101⁩ـە بە ژمارەی کوردی نووسراوە.

Only 0s and 1s, checked with a setتەنها 0 و 1، بە کۆمەڵە پشکنراوەset_check.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def is_binary(text):
    return text != "" and set(text) <= {"0", "1"}


for text in ["101", " 101 ", "-101", "0b101", "١٠١", "102", ""]:
    print(repr(text), is_binary(text))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

Not empty, and every character is in {"0", "1"} (see sets as a quick check).

بەتاڵ نییە و هەموو لەناو {"0", "1"}ـدایە (سەیری کۆمەڵە وەک پشکنینێکی خێرا بکە).

Quick checkپشکنینی خێراWhat does int("101") (no second argument) give?int("101") (بەبێ دووەم) چی دەدات؟

Improving the converter: any lengthباشترکردنی گۆڕەرەکە: هەر درێژییەک

The improved programبەرنامە باشترکراوەکە

Here is the converter rewritten with everything from this lesson and the course: small functions with clear snake_case names and docstrings, get_int() with try/except for the length, a set to check the digits, the doubling loop for any length from 1 to 16, an ask_yes_no() function for the run-again question, and the if __name__ == "__main__": guard from Modules.

ئەمە گۆڕەرەکەیە کە بە هەموو ئەوەی لەم وانەیە و کۆرسەکەدا هەیە دووبارە نووسراوەتەوە: بچووک بە ناوی ڕوونی و ، get_int() بە try/except بۆ درێژی، بۆ پشکنینی ، دوو هێندەکردن بۆ هەر درێژییەک لە 1 تا ⁦16⁩، ask_yes_no() بۆ پرسیاری دووبارە کارکردنەوە و پارێزەری if __name__ == "__main__": لە مۆدیوڵەکان.

The improved version: converter_improved.pyوەشانی باشترکراو: ⁦converter_improved.py⁩converter_improved.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
"""Binary to Decimal Converter: the improved version."""


def get_int(prompt):
    """Ask until the user types a whole number."""
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Please type a whole number.")


def get_length(name):
    """Ask how many binary digits the user wants (1 to 16)."""
    while True:
        length = get_int(f"Hello {name}! How many binary digits (1-16)? ")
        if 1 <= length <= 16:
            return length
        print("Please choose a number from 1 to 16.")


def read_binary(length):
    """Ask until the user types exactly `length` digits, each 0 or 1."""
    while True:
        digits = input(f"Enter {length} binary digits: ").strip()
        if len(digits) != length:
            print(f"Please type exactly {length} digits.")
        elif not set(digits) <= {"0", "1"}:
            print("You can only enter 0 or 1.")
        else:
            return digits


def binary_to_decimal(digits):
    """Turn a string of 0s and 1s into its decimal value."""
    value = 0
    for digit in digits:
        value = value * 2 + int(digit)
    return value


def ask_yes_no(question):
    """Return True for y and False for n; ask again for anything else."""
    while True:
        answer = input(question).strip().lower()
        if answer in ("y", "n"):
            return answer == "y"
        print("Please type y or n.")


def main():
    print("*" * 30)
    print("Binary to Decimal Converter")
    print("*" * 30)
    name = input("Please enter your name to get started: ")
    while True:
        length = get_length(name)
        digits = read_binary(length)
        print(f"{digits} in binary is {binary_to_decimal(digits)} in decimal.")
        if not ask_yes_no("Convert another number? (y/n): "):
            print(f"Goodbye, {name}!")
            break


if __name__ == "__main__":
    main()
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4-10

get_int() from Handling errors: a word can never crash the program.

get_int() لە مامەڵەکردن لەگەڵ هەڵاوێردە: وشەیەک هەرگیز ناخات.

Lineدێڕی 13-19

A plain if checks the range 1–16.

ifـێکی سادە سنووری ⁦1–16⁩ دەپشکنێت.

Lineدێڕی 22-31

Exactly length characters, all of them 0 or 1.

ڕێک length ، هەموویان 0 یان 1.

Lineدێڕی 34-39

The doubling loop replaces both tables.

دوو هێندەکردن جێگەی هەردوو خشتەکە دەگرێتەوە.

Lineدێڕی 42-48

True for y, False for n; .strip().lower() also accepts Y and y .

True بۆ y و False بۆ n؛ .strip().lower() Y و y ـیش وەردەگرێت.

Lineدێڕی 51-66

main() is short and reads like the scenario.

main() کورتە و وەک دەخوێنرێتەوە.

Because the conversion is now a separate function, it can be tested automatically. This small test program compares binary_to_decimal() with int(digits, 2) for every string of 0s and 1s up to 10 digits long (2+4+⋯+1024=20462 + 4 + \cdots + 1024 = 2046 strings):

لەبەر ئەوەی گۆڕینەکە ئێستا جیایە، دەکرێت خۆکارانە تاقی بکرێتەوە. ئەم بچووکەی تاقیکردنەوە binary_to_decimal() لەگەڵ int(digits, 2) بەراورد دەکات بۆ هەموو 0 و 1 تا درێژیی ⁦10⁩ (2+4+⋯+1024=20462 + 4 + \cdots + 1024 = 2046 ):

An automatic testتاقیکردنەوەیەکی خۆکارtest_improved.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
from itertools import product
from converter_improved import binary_to_decimal

checked = 0
for length in range(1, 11):
    for bits in product("01", repeat=length):
        digits = "".join(bits)
        assert binary_to_decimal(digits) == int(digits, 2), digits
        checked += 1
print("All", checked, "strings agree with int(digits, 2).")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

Importing the module does not start the game, thanks to the __main__ guard. Save the test in the same folder as converter_improved.py, or the import fails with ModuleNotFoundError.

هێنانی دەست پێ ناکات، بەهۆی پارێزەری __main__. تاقیکردنەوەکە لە هەمان converter_improved.pyـدا هەڵبگرە، ئەگەرنا هێنانەکە بە ModuleNotFoundError سەرناکەوێت.

Lineدێڕی 5-6

product("01", repeat=length) makes every combination of 0 and 1.

product("01", repeat=length) هەموو تێکەڵەیەکی 0 و 1 دروست دەکات.

Lineدێڕی 8

assert stops with an error if the two answers ever differ.

assert ئەگەر دوو وەڵامەکە هەرگیز جیاواز بن بە دەوەستێت.

FeatureتایبەتمەندیOriginal final versionوەشانی کۆتایی سەرەتاییImproved versionوەشانی باشترکراو
Digits supported پشتگیریکراو2 or 32 یان 31 to 16 (any, by changing one number)1 تا ⁦16⁩ (هەر ژمارەیەک، بە گۆڕینی یەک ژمارە)
How it convertsچۆن دەگۆڕێت12 if/elif branches⁦12⁩ لقی if/elifone 3-line loop سێ دێڕی
A word as the choiceوشەیەک وەک هەڵبژاردنasks again (string compare)دووبارە دەپرسێت (بەراوردی )asks again (try/except)دووبارە دەپرسێت (try/except)
NamesناوەکانcamelCase / CapWords / CapWordssnake_case (PEP 8) ⁦(PEP 8)⁩
Can be tested automaticallyدەکرێت خۆکارانە تاقی بکرێتەوەnoنەخێرyesبەڵێ
Quick checkپشکنینی خێراWhich part of the improved program decides how many digits are allowed?کام بەشی باشترکراوەکە بڕیار دەدات چەند ڕێگەپێدراوە؟

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

MistakeهەڵەWhat happensچی ڕوو دەداتFixچارەسەر
while num != "2" or num != "3":while num != "2" or num != "3":An endless loop: every answer passes.: هەموو وەڵامێک تێدەپەڕێت.Use and.and بەکار بهێنە.
Comparing input() with the number 2بەراوردکردنی input() لەگەڵ ژمارەی 2Never equal: "2" == 2 is False.هەرگیز یەکسان نین: "2" == 2 Falseـە.Compare with "2", or convert first inside try.لەگەڵ "2" بەراوردی بکە، یان سەرەتا لەناو tryـدا بیگۆڕە.
int(input()) with no tryint(input()) بەبێ tryA word crashes the program.وشەیەک دەخات.get_int()get_int()
int("101") without the baseint("101") بەبێ 101, read as decimal.⁦101⁩، بە خوێندراوە.int("101", 2)
Using bin(5) as plain bitsبەکارهێنانی bin(5) وەک ڕووتYou get 0b101, with a prefix.0b101 وەردەگریت، بە پێشگرەوە.bin(5)[2:] or f"{5:b}"bin(5)[2:] یان f"{5:b}"
Forgetting continue after a length errorلەبیرکردنی continue دوای درێژیThe digit check runs on a string of the wrong length.پشکنینی لەسەر درێژیی هەڵە جێبەجێ دەبێت.continue, or use elif as in the improved version.continue، یان وەک وەشانی باشترکراو elif بەکار بهێنە.
Reading place values from the left: 1, 2, 4خوێندنەوەی لە چەپەوە: 1، 2، 4101 would still be 5, but 110 becomes 3 instead of 6.101 هەر 5 دەبێت، بەڵام 110 لەبری 6 دەبێتە 3.The rightmost digit is worth 1. هەرە ڕاست 1ـە.
Three of the mistakes in codeسێ لە هەڵەکان لە کۆدداmistakes.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
print(int("101"))        # base 10: one hundred and one
print(int("101", 2))     # base 2: five
print(bin(5))            # a string with the prefix 0b
print(bin(5)[2:])        # drop the prefix
print("2" == 2)          # text is never equal to a number

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

ExerciseڕاهێنانHow many branches?چەند لق؟

The original program used one if/elif branch per possible input. How many branches would it need for 4 digits? For 8 digits? Write the rule as a formula.

سەرەتاییەکە بۆ هەر گونجاو یەک لقی if/elifـی بەکار دەهێنا. بۆ 4 چەند لقی پێویست دەبوو؟ بۆ 8 ؟ یاساکە وەک هاوکێشەیەک بنووسە.

Show answerوەڵامەکە پیشان بدە
n digits⇒2n branches:24=16,28=256n \text{ digits} \Rightarrow 2^n \text{ branches}: \quad 2^4 = 16, \quad 2^8 = 256

Each digit has 2 choices, so n digits have 2×2×⋯×2=2n2 \times 2 \times \cdots \times 2 = 2^n combinations. A loop needs the same 3 lines for every n.

هەر 2 هەڵبژاردەی هەیە، بۆیە n 2×2×⋯×2=2n2 \times 2 \times \cdots \times 2 = 2^n تێکەڵەیان هەیە. بۆ هەموو nـێک هەمان 3 دێڕی پێویستە.

ExerciseڕاهێنانTrace the doubling loopخولی دوو هێندەکردن بەدوادا بچۆ

Make a trace table of value = value * 2 + int(digit) for the digits 1101. Then check your table with Python.

بۆ value = value * 2 + int(digit) دروست بکە بۆ 1101. پاشان خشتەکەت بە بپشکنە.

Show answerوەڵامەکە پیشان بدە
Digit read خوێندراوvalue × 2 + digitvalue
10 × 2 + 11
11 × 2 + 13
03 × 2 + 06
16 × 2 + 113
ex_trace_1101.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
value = 0
for digit in "1101":
    value = value * 2 + int(digit)
    print(digit, value)
ExerciseڕاهێنانThe other directionئاڕاستە پێچەوانەکە

Write decimal_to_binary(n) with repeated division by 2 (the method of From decimal to other bases). Compare your answers with f"{n:b}".

decimal_to_binary(n) بنووسە بە دابەشکردنی دووبارە بەسەر 2ـدا (ڕێگاکەی لە دەییەوە بۆ بنچینەکانی تر). وەڵامەکانت لەگەڵ f"{n:b}" بەراورد بکە.

Hintئاماژە

Collect the remainders of n % 2 while n // 2 is still above 0.

پاشماوەکانی n % 2 کۆ بکەرەوە تا n // 2 هێشتا لە 0 گەورەترە.

Show answerوەڵامەکە پیشان بدە
ex_to_binary.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def decimal_to_binary(n):
    """Repeated division by 2; the remainders, read backwards, are the bits."""
    if n == 0:
        return "0"
    bits = ""
    while n > 0:
        bits = str(n % 2) + bits     # the new remainder goes in front
        n = n // 2
    return bits


for n in [0, 5, 6, 13, 255]:
    print(n, decimal_to_binary(n), f"{n:b}")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 7

The remainder n % 2 is the next bit from the right, so it goes in front of the bits found so far.

پاشماوەی n % 2 داهاتووە لە لای ڕاستەوە، بۆیە دەچێتە پێش ئەو کە تا ئێستا دۆزراونەتەوە.

ExerciseڕاهێنانOctal with the same loopهەشتی بە هەمان خول

Change the doubling loop so it converts octal (base 8) numbers: value = value * 8 + int(digit). Check 125 and 777 against int(text, 8).

دوو هێندەکردن بگۆڕە تا ژمارەی ( ⁦8⁩) بگۆڕێت: value = value * 8 + int(digit). 125 و 777 لەگەڵ int(text, 8) بپشکنە.

Show answerوەڵامەکە پیشان بدە
ex_octal.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def octal_to_decimal(digits):
    value = 0
    for digit in digits:
        value = value * 8 + int(digit)
    return value


for text in ["7", "10", "125", "777"]:
    print(text, octal_to_decimal(text), int(text, 8))

(125)8=1×64+2×8+5=(85)10(125)_8 = 1 \times 64 + 2 \times 8 + 5 = (85)_{10}, the same example as in Octal to decimal.

(125)8=1×64+2×8+5=(85)10(125)_8 = 1 \times 64 + 2 \times 8 + 5 = (85)_{10}، هەمان نموونەی لە هەشتییەوە بۆ دەیی.

ExerciseڕاهێنانFix the questionپرسیارەکە چاک بکە

Rewrite the choice question of the original program so that it has no youlike bug and does not print a Python list.

پرسیاری هەڵبژاردنی سەرەتاییەکە دووبارە بنووسەوە بە شێوەیەک کە youlikeـی تێدا نەبێت و چاپ نەکات.

Show answerوەڵامەکە پیشان بدە
question_fixed.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
name = "Aram"
question = f"Hello {name}! How many binary digits, 2 or 3? "
print(question)
ExerciseڕاهێنانAccept yes and noyes و no وەربگرە

Change ask_yes_no() so it also accepts the words yes and no, in any case and with spaces around them.

ask_yes_no() بگۆڕە تا وشەکانی yes و noـیش وەربگرێت، بە پیتی گەورە یان بچووک و بە لە دەوریاندا.

Show answerوەڵامەکە پیشان بدە
ex_yes_no.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def ask_yes_no(question):
    while True:
        answer = input(question).strip().lower()
        if answer in ("y", "yes"):
            return True
        if answer in ("n", "no"):
            return False
        print("Please type y or n.")


print(ask_yes_no("Again? (y/n): "))

Summaryپوختە

  • A mini project follows a plan: scenario → flowchart → algorithm → code → examples, then bug-finding and improvement.
  • Binary to decimal: multiply each digit by its place value (… 8, 4, 2, 1) and add; or read left to right with value * 2 + digit.
  • Validate input in a loop until it is right: the choice (2 or 3), the length, and every character (0 or 1).
  • Comparing strings avoids the int() crash; with integers, use try/except ValueError (get_int()).
  • The bugs: youlike, a printed list, a redundant test, == False, non-PEP 8 names, a table per input.
  • Python's tools: int(text, 2), bin(n), f"{n:b}"; check only 0s and 1s with set(text) <= {"0", "1"}.
  • بەدوای پلانێکدا دەڕوات: ← ← ← کۆد ← نموونەکان، پاشان دۆزینەوەی و باشترکردن.
  • بۆ : هەر لە بدە (… 8، 4، 2، ⁦1⁩) و کۆیان بکەرەوە؛ یان لە چەپەوە بۆ ڕاست بە value * 2 + digit بیخوێنەوە.
  • لە پشتڕاست بکەرەوە تا دروست دەبێت: هەڵبژاردنەکە (⁦2⁩ یان ⁦3⁩)، درێژی و هەموو (⁦0⁩ یان ⁦1⁩).
  • بەراوردکردنی ڕێگری لە کەوتنی int() دەکات؛ لەگەڵ ، try/except ValueError بەکار بهێنە (get_int()).
  • : youlike، چاپکراو، تاقیکردنەوەیەکی زیادە، == False، ناوی دژی ⁦PEP 8⁩، خشتە بۆ هەر .
  • ئامرازەکانی : int(text, 2)، bin(n)، f"{n:b}"؛ تەنها 0 و 1 بە set(text) <= {"0", "1"} بپشکنە.
Review questionsپرسیارەکانی پێداچوونەوە
Why does each extra binary digit double the size of the table?بۆچی هەر تاکژمارەیەکی دووانیی زیادە قەبارەی خشتەکە دوو هێندە دەکات؟

The new digit can be 0 or 1 for every old combination: 2n2^n combinations for n digits.

نوێیەکە بۆ هەر تێکەڵەیەکی کۆن دەتوانێت 0 یان 1 بێت: 2n2^n تێکەڵە بۆ n .

Why is the improved version easier to test?بۆچی تاقیکردنەوەی وەشانی باشترکراو ئاسانترە؟

The conversion is a separate function that returns a number, so a test program can call it thousands of times.

گۆڕینەکە جیایە کە ژمارەیەک دەگەڕێنێتەوە، بۆیە تاقیکردنەوە دەتوانێت هەزاران جار بانگی بکات.

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

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

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

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

Project: A Word-Scramble Gameپڕۆژیلە: یاریی پیتە تێکەڵەکان

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

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