Thursday, January 21, 2021

Python - Find and Fix errors (Day 13)

This is a 100 Days challenge to learn a new language (Python). 100 Days of Code - The Complete Python Pro Bootcamp 

I will post some notes to motivate myself to finish this challenge.


Tip 1 - Describe your problems



Analyze what the program/function is built for, and check whether the output is correct or not.

Ex:
def my_function():
    """Loop through 1 to 20 and print "You got it" if it is 20"""

    for i in range(1, 20):
        if i == 20:
            print("You got it")


my_function()

Result:

# No Output


From this example, my_function will loop through 1 to 20, and once i is 20, it should print the log 'You got it'. So our assumption is that i will be 20 in the end of the loop. However, after running this code, you noticed that there is no any output. So there must be something wrong.

This is a bug that we misuse range function. Reference


Tip 2 - Reproduce



Sometimes, the reproduced rate is not 100%, which will make you hard to debug it. If you cannot reproduce it, then you don't have enough knowledge/clue to resolve the issue.

Ex:
from random import randint

dice_imgs = ["h", "e", "l", "l", "o"]
dice_num = randint(1, 5)
print(dice_imgs[dice_num])

Result:

IndexError: list index out of range


For this example, the dice_num will be 1 to 5. Then dice_imgs[5] will throw erros.


Tip 3 - Play Computer and Evaluate each line



Ex:
year = int(input("What's your year of birth?"))
if year > 1980 and year < 1994:
    print("You are a millennial.")
elif year > 1994:
    print("You are a Gen Z.")

Result:

# No Output if the input is 1994


Try to use 1994 or some number less than 1980 as an input to run this function through your brain and finger.


Tip 4 - Fixing Errors and Watching for Red Underlines



Some IDE will help you to find out the syntax errors.

Ex:
age = input("How old are you?")
if age > 18:
print("You can drive at age {age}.")

Result:

IndentationError: expected an indented block


There are three issues in this example.
First, before running this code, the ide will show the Red Underlines to warn you.
Second, once you run it, the console will log some error, and you will have clue for how to resolve it.
Third, it misuse the f-string.


Tip 5 - print() is your friend



Ex:
pages = 0
word_per_page = 0
pages = int(input("Number of pages: "))
word_per_page == int(input("Number of words per page: "))
total_words = pages * word_per_page
print(total_words)

Result:

0


Since there is a typo in this example, and it is hard to detect. Print out the variables value can save your time.


Tip 6 - Use a debugger

Tip 7 - Take a break



Tip 8 - Ask a friend



Fresh eyes or different way to look through the issues.


Tip 9 - Run Often



Once you finish a small chunk of feature, run it and test it directly. Don't wait until you finish the whole feature.


Tip 10 - Ask StackOverflow


No comments:

Post a Comment