0

Still fairly new at writing code. I have written a Python 3.10.5 program to calculate home siding. The program works great as long as only numbers are entered. I need code to check for letters instead of numbers and keep asking to enter a number until a number is entered. I cannot get any type of loop to work. I have searched the Python documentation and this website, but cannot find anything that seems to work. This is what I am starting with:

    WallFactor = input("How many Walls? ")
    print("Number of Walls: ", WallFactor)

    while int(CurrentWallNumber) <= int(WallFactor):
        print("Current Wall Number:", CurrentWallNumber)
        HeightFeet = input("How many feet high? ")
        HeightInches = input("How many extra inches? ")
        TotHFtIn = int(HeightFeet) * 12  #Number of HeightFeet in inches
        TotHInches = int(TotHFtIn) + int(HeightInches)  #Total Height in inches

When I enter the letter 'i' I get the following message:

    How many Walls? i
    Number of Walls:  i
    Traceback (most recent call last):
      File "C:\Users\bible\AppData\Local\Programs\Python\Python310\SidingCalculator.py", 
    line 16, in <module>
        while int(CurrentWallNumber) <= int(WallFactor):
    ValueError: invalid literal for int() with base 10: 'i'

I want a code, please, that I can add to each question checking for a number that keeps asking for a number until a number is entered. Thank you

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
  • Seems like you need `.isdigit()`. Maybe make a `check` variable your input and then do something like `if check.isdigit():` then do something. – smichael_44 Jun 30 '22 at 18:39

1 Answers1

0

Hi buddy congrats on starting this journey! You can do a simple try catch:

try:
   TotHFtIn = int(HeightFeet) * 12  #Number of HeightFeet in inches
   TotHInches = int(TotHFtIn) + int(HeightInches)  #Total Height in inches
except ValueError:
   print "Wrong input, please only use numbers"

This is simple and there are better solutions but it works. A good followup read is probably googling: "Python cast string to int"

Martin W
  • 21
  • 4