2

I'm starting out with Python after taking a class that taught us pseudocode. How could I make a validation loop to continue the function if a user inputted a decimal rather than a whole number? At its current state, I've gotten it to recognize when a user enters a number outside of the acceptable range, but if the user enters a decimal number, it crashes. Is there another validation loop that can recognize a decimal?

def main():
    again = 'Y'
    while again == 'y' or again == 'Y':
        strength_score = int(input('Please enter a strength score between 1 and 30: '))

        # validation loop
        while strength_score < 1 or strength_score > 30 :
            print ()
            print ('Error, invalid selection!')
            strength_score = int(input('Please enter a whole (non-decmial) number between 1 and 30: '))

        # calculations
        capacity = (strength_score * 15)
        push = (capacity * 2)
        encumbered = (strength_score * 5)
        encumbered_heavily = (strength_score * 10)

        # show results
        print ()
        print ('Your carrying capacity is' , capacity, 'pounds.')
        print ('Your push/drag/lift limit is' , push, 'pounds.')
        print ('You are encumbered when holding' , encumbered, 'pounds.')
        print ('You are heavyily encumbered when holding' , encumbered_heavily, 'pounds.')
        print ()

        # technically, any response other than Y or y would result in an exit. 
        again = input('Would you like to try another number? Y or N: ')
        print ()
    else:
        exit()

main()

2 Answers2

1

Depending on what you want the behavior to be:

  1. If you want to accept non-integer numbers, just use float(input()). If you want to accept them but turn them into integers, use int(float(input())) to truncate or round(float(input())) to round to the nearest integer.

  2. If you want to print an error message and prompt for a new number, use a try-catch block:

    try:
        strength_score = int(input('Please enter a strength score between 1 and 30: '))
    except ValueError:
        again = input("Invalid input, try again? Y / N")
        continue # skip the rest of the loop
    
Christoph Burschka
  • 4,467
  • 3
  • 16
  • 31
0

That is because you have strength_score as an int, and not a float.

Try changing

strength_score = int(input('Please enter a strength score between 1 and 30: '))

to

strength_score = float(input('Please enter a strength score between 1 and 30: '))

Tested with 0.1 and 0.0001 and both are working properly.

artemis
  • 6,857
  • 11
  • 46
  • 99