0% found this document useful (0 votes)
3 views1 page

Guide Python2

The Bug Hunter Guide covers essential Python concepts such as lists, dictionaries, functions, variable initialization, for loops, floor division, and if comparisons. Each section provides definitions, examples, and exercises to help readers understand and apply these concepts in coding. The guide is available in English, French, and Arabic.

Uploaded by

nezhahella
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views1 page

Guide Python2

The Bug Hunter Guide covers essential Python concepts such as lists, dictionaries, functions, variable initialization, for loops, floor division, and if comparisons. Each section provides definitions, examples, and exercises to help readers understand and apply these concepts in coding. The guide is available in English, French, and Arabic.

Uploaded by

nezhahella
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

🐛 Bug Hunter Guide

🇬🇧 English
The Python concepts you need to read, understand, and fix code

📋 Concepts covered in this guide


1 Lists & dictionaries

2 Functions — def & return

3 Initializing variables to 0

4 for loops & += accumulation

5 // floor division

6 if comparisons & tracking the best

1 Lists & Dictionaries


A list is an ordered collection of items, written with square brackets [ ]. A dictionary is a collection of
labelled values written with curly braces { } — each label is called a key, and you use it to look up the
matching value.

# A list of temperatures
temps = [22, 25, 19]

# A dictionary: key → value


city = {"name": "Oujda", "temps": [22, 25, 19]}

# Access a value using its key


city["name"] → "Oujda"
city["temps"] → [22, 25, 19]

💡 You can put a list inside a dictionary as a value — and dictionaries can be put inside a list. This is
how complex data is structured in Python. When you see item["key"], Python fetches the value stored
under that label.

✏️ Try it yourself
product = {"title": "Laptop", "prices": [4500, 4200, 4800]}
product["title"]

→ "Laptop" — The key "title" maps to the value "Laptop" in the dictionary.

2 Functions — def & return


A function is a reusable block of code with a name. You define it once with def, and call it by name
whenever you need it. The value you pass in is called an argument; inside the function it's called a
parameter. return sends the result back to whoever called the function.

def double(number): # "number" is the parameter


result = number * 2
return result # sends the answer back

# Calling the function:


double(7) → 14 # 7 is the argument
double(3) → 6

⚠️ def doesn't run the code — it only defines it. The code inside the function runs only when you call
it by name. Without return, the function gives back None (nothing).

✏️ Try it yourself
def add_tax(price):
return price + price * 0.2

add_tax(100)

→ 120.0 — The function adds 20% to the price: 100 + 20 = 120.

3 Initializing a variable to 0
When you want to add up a series of numbers, you need a "running total" variable. You must create it and
set it to 0 before the loop starts — so the first addition builds on nothing, giving a correct result.

# Starting at the wrong value — corrupts every result


total = 5 # BAD: every sum is inflated by 5

# Starting at 0 — clean slate


total = 0 # GOOD: adding on top of nothing
total = total + 8 → 8
total = total + 3 → 11
total = total + 6 → 17 # correct sum of 8+3+6

💡 This pattern appears in almost every program that calculates a total or average. The starting value
of the accumulator must be 0 — any other starting value silently poisons every calculation that follows.

✏️ Try it yourself
total = 0
total = total + 10
total = total + 20
total = total + 30
total

→ 60 — Starting at 0 and adding 10, 20, 30 gives the correct sum: 60.

4 for loops & += accumulation


A for loop visits every item in a list, one at a time. To add them all up, use +=, which is shorthand for total =
total + item. It adds onto whatever is already in the variable — very different from =, which replaces it.

# = replaces — only keeps the last value


total = 0
for n in [8, 3, 6]:
total = n # overwrites each time
→ total = 6 # WRONG: lost 8 and 3

# += accumulates — builds up the running total


total = 0
for n in [8, 3, 6]:
total += n # 0→8→11→17
→ total = 17 # CORRECT: 8 + 3 + 6

The key difference:


total = n → "Forget everything, store only this."
total += n → "Add this on top of what's already there."

✏️ Try it yourself
total = 0
for price in [1200, 800, 450]:
total += price
total

→ 2450 — Loop: 0+1200=1200 → 1200+800=2000 → 2000+450=2450. All three


prices added up.

5 // — Floor division
// divides two numbers and drops the decimal part, always returning a whole number. Regular / keeps the
decimal. Use // when you only care about the whole-number result (like a whole-number average).

17 / 3 → 5.666... # regular: keeps decimal


17 // 3 → 5 # floor: drops .666
20 // 4 → 5 # exact division, same result
11 // 2 → 5 # 5.5 → drops the .5

💡 Computing an average with //: add all the values into a total, then do total // len(list).
len(list) counts how many items are in the list. The result is the whole-number average.

✏️ Try it yourself
scores = [14, 16, 15]
total = 14 + 16 + 15
total // len(scores)

→ 15 — total = 45, len = 3, 45 // 3 = 15. The whole-number average.

6 if comparisons & tracking the best value


To find the highest value across a list, you compare each item to the current best. Start best at 0 so the first
real value always wins. Use > to check if something is higher. If you use < instead, you find the lowest — the
opposite of what you want.

# Finding the highest score


best = 0
for score in [72, 88, 65, 91]:
if score > best: # is this score better than current best?
best = score # yes → update the best
→ best = 91 # correctly found the maximum

# Common mistake: using < instead of >


best = 100
if score < best: ... # finds the MINIMUM — wrong direction!

Pattern to find the maximum:


Start: best = 0
Check: if value > best → best = value

Pattern to find the minimum:


Start: best = float('inf') (or a very large number)
Check: if value < best → best = value

✏️ Try it yourself
best = 0
for temp in [18, 34, 27, 31]:
if temp > best:
best = temp
best

→ 34 — The loop compares each temperature: 18 >0 ✓, 34 >18 ✓, 27 >34 ✗,


31 >34 ✗. Highest is 34.

🇫🇷 Français
Les concepts Python nécessaires pour lire, comprendre et corriger du code

📋 Concepts couverts dans ce guide


1 Listes & dictionnaires

2 Fonctions — def & return

3 Initialiser une variable à 0

4 Boucles for & accumulation +=

5 // division entière

6 Comparaisons if & trouver le meilleur

1 Listes & Dictionnaires


Une liste est une collection ordonnée d'éléments, écrite avec des crochets [ ]. Un dictionnaire est une
collection de valeurs étiquetées écrite avec des accolades { } — chaque étiquette s'appelle une clé, et on
l'utilise pour accéder à la valeur correspondante.

# A list of temperatures
temps = [22, 25, 19]

# A dictionary: key → value


city = {"name": "Oujda", "temps": [22, 25, 19]}

# Access a value using its key


city["name"] → "Oujda"
city["temps"] → [22, 25, 19]

💡 Vous pouvez mettre une liste à l'intérieur d'un dictionnaire comme valeur — et les dictionnaires
peuvent être mis dans une liste. C'est ainsi que les données complexes sont structurées en Python.
Quand vous voyez item["clé"], Python récupère la valeur stockée sous cette étiquette.

✏️ Essaie par toi-même


product = {"title": "Laptop", "prices": [4500, 4200, 4800]}
product["title"]

→ "Laptop" — La clé "title" correspond à la valeur "Laptop" dans le


dictionnaire.

2 Fonctions — def & return


Une fonction est un bloc de code réutilisable avec un nom. On la définit une fois avec def, et on l'appelle
par son nom quand on en a besoin. La valeur qu'on passe est appelée argument ; à l'intérieur de la
fonction, elle s'appelle paramètre. return renvoie le résultat à l'appelant.

def double(number): # "number" is the parameter


result = number * 2
return result # sends the answer back

# Calling the function:


double(7) → 14 # 7 is the argument
double(3) → 6

⚠️ def n'exécute pas le code — il le définit seulement. Le code à l'intérieur ne s'exécute que quand
on appelle la fonction par son nom. Sans return, la fonction renvoie None (rien).

✏️ Essaie par toi-même


def add_tax(price):
return price + price * 0.2

add_tax(100)

→ 120.0 — La fonction ajoute 20% au prix : 100 + 20 = 120.

3 Initialiser une variable à 0


Quand vous voulez additionner une série de nombres, vous avez besoin d'une variable "total courant". Vous
devez la créer et la mettre à 0 avant que la boucle commence — ainsi la première addition part de zéro,
donnant un résultat correct.

# Starting at the wrong value — corrupts every result


total = 5 # BAD: every sum is inflated by 5

# Starting at 0 — clean slate


total = 0 # GOOD: adding on top of nothing
total = total + 8 → 8
total = total + 3 → 11
total = total + 6 → 17 # correct sum of 8+3+6

💡 Ce schéma apparaît dans presque tous les programmes qui calculent un total ou une moyenne. La
valeur de départ de l'accumulateur doit être 0 — toute autre valeur de départ corrompt
silencieusement tous les calculs qui suivent.

✏️ Essaie par toi-même


total = 0
total = total + 10
total = total + 20
total = total + 30
total

→ 60 — En partant de 0 et en ajoutant 10, 20, 30, on obtient la somme


correcte : 60.

4 Boucles for & accumulation +=


Une boucle for visite chaque élément d'une liste, un par un. Pour les additionner tous, utilisez +=, qui est un
raccourci pour total = total + élément. Cela s'ajoute à ce qui est déjà dans la variable — très différent de
=, qui le remplace.

# = replaces — only keeps the last value


total = 0
for n in [8, 3, 6]:
total = n # overwrites each time
→ total = 6 # WRONG: lost 8 and 3

# += accumulates — builds up the running total


total = 0
for n in [8, 3, 6]:
total += n # 0→8→11→17
→ total = 17 # CORRECT: 8 + 3 + 6

La différence clé :
total = n → "Oublie tout, stocke seulement ceci."
total += n → "Ajoute ceci à ce qui est déjà là."

✏️ Essaie par toi-même


total = 0
for price in [1200, 800, 450]:
total += price
total

→ 2450 — Boucle : 0+1200=1200 → 1200+800=2000 → 2000+450=2450. Les trois


prix additionnés.

5 // — Division entière
// divise deux nombres et supprime la partie décimale, retournant toujours un nombre entier. La / normale
garde la décimale. Utilisez // quand vous ne voulez que le résultat entier (comme une moyenne entière).

17 / 3 → 5.666... # regular: keeps decimal


17 // 3 → 5 # floor: drops .666
20 // 4 → 5 # exact division, same result
11 // 2 → 5 # 5.5 → drops the .5

💡 Calculer une moyenne avec // : additionnez toutes les valeurs dans un total, puis faites total //
len(liste). len(liste) compte le nombre d'éléments dans la liste. Le résultat est la moyenne en
nombre entier.

✏️ Essaie par toi-même


scores = [14, 16, 15]
total = 14 + 16 + 15
total // len(scores)

→ 15 — total = 45, len = 3, 45 // 3 = 15. La moyenne en nombre entier.

6 Comparaisons if & suivre la meilleure valeur


Pour trouver la plus haute valeur dans une liste, vous comparez chaque élément au meilleur actuel.
Commencez best à 0 pour que la première vraie valeur gagne toujours. Utilisez > pour vérifier si quelque
chose est plus grand. Si vous utilisez < à la place, vous trouvez la valeur la plus basse — le contraire de ce
que vous voulez.

# Finding the highest score


best = 0
for score in [72, 88, 65, 91]:
if score > best: # is this score better than current best?
best = score # yes → update the best
→ best = 91 # correctly found the maximum

# Common mistake: using < instead of >


best = 100
if score < best: ... # finds the MINIMUM — wrong direction!

Schéma pour trouver le maximum :


Départ : best = 0
Vérification : if value > best → best = value

Schéma pour trouver le minimum :


Départ : best = float('inf') (ou un très grand nombre)
Vérification : if value < best → best = value

✏️ Essaie par toi-même


best = 0
for temp in [18, 34, 27, 31]:
if temp > best:
best = temp
best

→ 34 — La boucle compare chaque température : 18 >0 ✓, 34 >18 ✓, 27 >34


✗, 31 >34 ✗. La plus haute est 34.

‫العربية‬ 🇸🇦
‫مفاهيم بايثون التي تحتاجها لقراءة وفهم وإصالح الكود‬

‫المفاهيم المشمولة في هذا الدليل‬ 📋


1 ‫القوائم والقواميس‬

2 return ‫ و‬def — ‫الدوال‬

3 0 ‫تهيئة المتغيرات إلى‬

4 =+ ‫ وتراكم‬for ‫حلقات‬

5 ‫ القسمة الصحيحة‬//

6 ‫ وتتبع األفضل‬if ‫مقارنات‬

1 ‫القوائم والقواميس‬
‫ القاموس هو مجموعة من القيم‬.] [ ‫ ُتكتب بأقواس مربعة‬،‫القائمة هي مجموعة مرتبة من العناصر‬
‫ وتستخدمه للبحث عن القيمة‬،‫الُمعنونة ُتكتب بأقواس معقوفة { } — كل عنون ُتسمى مفتاحًا‬
.‫المقابلة‬

A list of temperatures #
temps = [22, 25, 19]

A dictionary: key → value #


city = {"name": "Oujda", "temps": [22, 25, 19]}

Access a value using its key #


"city["name"] → "Oujda
city["temps"] → [22, 25, 19]

‫ هكذا ُتنظم‬.‫يمكنك وضع قائمة داخل القاموس كقيمة — ويمكن وضع القواميس داخل القائمة‬ 💡
‫ يجلب بايثون القيمة المخزنة تحت‬،]"‫["مفتاح‬item ‫ عندما ترى‬.‫البيانات المعقدة في بايثون‬
.‫هذا العنوان‬

‫جربها بنفسك‬ ✏️
product = {"title": "Laptop", "prices": [4500, 4200, 4800]}
product["title"]

.‫" في القاموس‬Laptop" ‫" يقابل القيمة‬title" ‫" — المفتاح‬Laptop" →

2 — ‫ الدوال‬def ‫ و‬return
،def ‫ يتم تعريفها مرة واحدة باستخدام‬.‫الدالة هي كتلة قابلة إلعادة االستخدام مع اسم‬
‫)؛ وداخل الدالة‬argument( ‫ ُتسمى القيمة التي تمررها وسيطة‬.‫وتستدعيها باالسم كلما احتجت إليها‬
.‫ النتيجة إلى من استدعى الدالة‬return ‫ ُيرجع‬.)parameter( ‫ُتسمى معامًلا‬

def double(number): # "number" is the parameter


result = number * 2
return result # sends the answer back

:Calling the function #


double(7) → 14 # 7 is the argument
double(3) → 6

‫ الكود داخل الدالة ال يعمل إال عندما تستدعيها‬.‫ بتشغيل الكود — بل يحدده فقط‬def ‫ال يقوم‬ ⚠️
.)‫ (ال شيء‬None ‫ ُترجع الدالة‬،return ‫ بدون‬.‫باالسم‬

‫جربها بنفسك‬ ✏️
:def add_tax(price)
return price + price * 0.2

add_tax(100)

.120 = 20 + 100 :‫ إلى السعر‬%20 ‫ — تضيف الدالة‬120.0 →

3 ‫ تهيئة متغير إلى‬0


‫ يجب عليك إنشاؤه‬."‫ فأنت بحاجة إلى متغير "اإلجمالي الجاري‬،‫عندما تريد جمع سلسلة من األرقام‬
.‫ مما يعطي نتيجة صحيحة‬،‫ قبل بدء الحلقة — بحيث تبدأ عملية الجمع األولى من الصفر‬0 ‫وضبطه على‬

Starting at the wrong value — corrupts every result #


total = 5 # BAD: every sum is inflated by 5

Starting at 0 — clean slate #


total = 0 # GOOD: adding on top of nothing
total = total + 8 → 8
total = total + 3 → 11
total = total + 6 → 17 # correct sum of 8+3+6

‫ يجب أن تكون قيمة‬.‫تظهر هذه األنماط في كل برنامج تقريبًا يحسب إجمالًيا أو متوسًطا‬ 💡
.‫ — أي قيمة بداية أخرى ُتفسد بصمت كل حساب يليها‬0 ‫البداية للُمجِّمع‬

‫جربها بنفسك‬ ✏️
total = 0
total = total + 10
total = total + 20
total = total + 30
total

.60 :‫ نحصل على المجموع الصحيح‬30 ،20 ،10 ‫ وإضافة‬0 ‫ — بالبدء من‬60 →

4 ‫ حلقات‬for ‫= وتراكم‬+
‫ وهي‬،=+ ‫ استخدم‬،‫ لجمعها كلها‬.‫ واحدًا تلو اآلخر‬،‫ بزيارة كل عنصر في القائمة‬for ‫تقوم حلقة‬
‫ إنها تضيف إلى ما هو موجود بالفعل في المتغير — وهو مختلف‬.total = total + item ‫اختصار لـ‬
.‫تمامًا عن = الذي يستبدله‬

replaces — only keeps the last value = #


total = 0
:for n in [8, 3, 6]
total = n # overwrites each time
total = 6 # WRONG: lost 8 and 3 →

accumulates — builds up the running total =+ #


total = 0
:for n in [8, 3, 6]
total += n # 0→8→11→17
total = 17 # CORRECT: 8 + 3 + 6 →

:‫الفرق الجوهري‬
".‫ وخّزن هذا فقط‬،‫ → "انَس كل شيء‬total = n
".‫ → "أضف هذا إلى ما هو موجود بالفعل‬total += n

‫جربها بنفسك‬ ✏️
total = 0
:for price in [1200, 800, 450]
total += price
total

‫ تم جمع‬.2450=450+2000 → 2000=800+1200 → 1200=1200+0 :‫ — الحلقة‬2450 →


.‫األسعار الثالثة‬

5 // ‫— القسمة الصحيحة‬
‫ تحتفظ‬/ ‫ القسمة العادية‬.‫ ُمرجعًة دائمًا رقمًا صحيحًا‬،‫ بقسمة رقمين وتحذف الجزء العشري‬// ‫تقوم‬
.)‫ عندما تهتم فقط بالنتيجة الصحيحة (مثل المتوسط الصحيح‬// ‫ استخدم‬.‫بالعالمة العشرية‬

regular: keeps decimal # ...5.666 → 3 / 17


floor: drops .666 # 5 → 3 // 17
exact division, same result # 5 → 4 // 20
drops the .5 → 5.5 # 5 → 2 // 11

total // len(list). ‫ ثم قم بـ‬،‫ اجمع كل القيم في إجمالي‬:// ‫حساب المتوسط باستخدام‬ 💡


.‫ النتيجة هي المتوسط كرقم صحيح‬.‫ تحسب عدد العناصر في القائمة‬len(list)

‫جربها بنفسك‬ ✏️
scores = [14, 16, 15]
total = 14 + 16 + 15
total // len(scores)

.‫ المتوسط كرقم صحيح‬.total = 45, len = 3, 45 // 3 = 15 — 15 →

6 ‫ مقارنات‬if ‫وتتبع أفضل قيمة‬


‫ بحيث تفوز أول‬0 ‫ عند‬best ‫ ابدأ بـ‬.‫ تقارن كل عنصر بأفضل قيمة حالية‬،‫إليجاد أعلى قيمة في قائمة‬
،‫ إذا استخدمت < بدًال من ذلك‬.‫ استخدم > للتحقق مما إذا كان هناك شيء أكبر‬.‫قيمة حقيقية دائمًا‬
.‫ستجد القيمة األقل — وهو عكس ما تريده‬

Finding the highest score #


best = 0
:for score in [72, 88, 65, 91]
?if score > best: # is this score better than current best
best = score # yes → update the best
best = 91 # correctly found the maximum →

> Common mistake: using < instead of #


best = 100
!if score < best: ... # finds the MINIMUM — wrong direction

:‫نمط إيجاد الحد األقصى‬


best = 0 :‫البداية‬
if value > best → best = value :‫التحقق‬

:‫نمط إيجاد الحد األدنى‬


)‫ (أو رقم كبير جدًا‬best = float('inf') :‫البداية‬
if value < best → best = value :‫التحقق‬

‫جربها بنفسك‬ ✏️
best = 0
:for temp in [18, 34, 27, 31]
:if temp > best
best = temp
best

34> 31 ،✗ 34> 27 ،✓ 18> 34 ،✓ 0> 18 :‫ — تقارن الحلقة كل درجة حرارة‬34 →


.34 ‫ األعلى هي‬.✗

You might also like