0

How can I handle the part from while True to the for? I need an exception that tells the user that he needs to enter a number (in case he accidentally types a string) or a value > 0. I tried converting the nyear to an int so it would raise a value error but this only lead to an error.

So how would you guys handle this?

 def main():

    nyear = int(raw_input('Enter the years: '))    
    i = 0
    while True:
        try:
            intTarget = int(nyear)
        except ValueError:
            print 'Value needs to be a number and needs to be greater than 0'

        nyear = int(raw_input('Enter the years: '))

    for year in range(nyear):
        for month in range(12):
            rinch = float(raw_input('How many inches of rain: '))
            i += rinch 

        total = i
        tmonths = (month + 1) * (year + 1)
        ravg = total/tmonths
        print total, tmonths, ravg        
main()
PlateArmor
  • 25
  • 5
  • 2
    You already convert it to int before even entering the try block. – tobias_k Jan 08 '15 at 09:30
  • Put a `break` below `intTarget = int(nyear)`. –  Jan 08 '15 at 09:32
  • 1. you have write `int(raw_input('Enter the years: '))` statement two times- write only once in code. 2. As you want to again `Enter the years:` again and again - so move code of this statement into `while` loop. 3. Do Type conversion ins `try and exception` block. – Vivek Sable Jan 08 '15 at 09:47

1 Answers1

1
  1. Move raw_input statement into try block.
  2. Use break keyword to break while loop when user enter valid number string.
  3. Convert user value from string to int. if any exception raise during type conversion then ask again. This will go in exception part of code.
  4. Also check enter number is greater then 0 or not by if loop.

Use e.g.

while True:
    try:
        nyear = int(raw_input('Enter the years: '))
        if nyear>0:
            break
        print 'Value needs to be a number and needs to be greater than 0.'
    except ValueError:
        print 'Value needs to be a number and needs to be greater than 0.'

Output:

Enter the years: w
Value needs to be a number and needs to be greater than 0.
Enter the years: -100
Value needs to be a number and needs to be greater than 0.
Enter the years: 2015
Vivek Sable
  • 9,938
  • 3
  • 40
  • 56