#100DaysOfCode - Day 2

·

2 min read

I should have written this up yesterday but life was a blur, being the weekend.
The sun was out, I was putting new security bolts on the gate, some security lighting, and the CCTV with my partner after finishing off my code. Then a trip to the local Honda dealer to see if they had a motorcycle jacket for me. I have tried quite a few online, all of which are returned due to sizing issues or just not being the quality I expected. With CoVid restrictions reduced I thought the time was now.

Day 2 - The main project was to create a Tip Calculator. There were a few smaller projects that were part of today's exercise and I worked my way through them. I noticed a lot of things that weren't there, namely error handling of user input. The exercises were console tools that required user input.

  • Add two digits - The user should input a two-digit number and the code adds the two digits and gives the answer.
  • BMI Calculator - User inputs their weight and height and the code calculates the BMI.
  • Your Life in Weeks - User inputs their age in years and the code calculates how many days, weeks and months until you would reach 90 years old.

Once I completed the various exercises as per the instructions I decided to pick one of them to add in some error handling. I chose the first exercise.

The input number is a string and is converted to an integer, and the first error would be a ValueError, if the string contained anything other than integers (letters or special characters).
A try/except loop was set to handle this.

 try:
        int(two_digits)
    except ValueError:
        print('It has to be a number')
        sleep(2)
        two_digit_add()

Log an error message to the console, use sleep to hold the message for a couple of seconds, and restart the function. Oh, I forgot to mention, the exercises didn't use functions but I decided to always set the code into functions for easier handling. TBH, this would be where the coding would be heading anyway.

The second error to be handled would be if the user inputs a value with more than two digits.
This time I handled this with an if statement.

 if len(two_digits) != 2:
        print('It has to be a two digit number')
        sleep(2)
        two_digit_add()