1

I have created a program in Python 3.4.1 that; asks for a whole number, verifies that it is a whole number, throws an error message and asks for the number to be re-input if not a whole number, once the number is verified adds it to a list, ends if -1 is input.

mylist = []

def checkint(number):
    try:
        number = int(number)
    except:
        print ("Input not accepted, please only enter whole numbers.")
        number = input("Enter a whole number. Input -1 to end: ")
        checkint(number)


number = input("Enter a whole number. Input -1 to end: ")
checkint(number)

while int(number) != -1:

    mylist.append(number)
    number = input("Enter a whole number. Input -1 to end: ")
    checkint(number)   

This all works fine, except in one scenario. If a non-whole number is input e.g. p (which gives an error message) followed by -1 to end the program, I get this message:

Traceback (most recent call last):
  File "C:/Users/************/Documents/python/ws3q4.py", line 15, in <module>
    while int(number) != -1:
ValueError: invalid literal for int() with base 10: 'p'

I don't understand why this is happening, as the input of p should never get as far as

while int(number) != -1:
K Mo
  • 2,125
  • 8
  • 16
  • 2
    This is a scoping issue. You have a variable `number` which is global, and a variable `number` that is local to `checkint`- this is causing confusion. Once checked, you need to pass the variable out of the function to make it work. – anon582847382 Oct 29 '14 at 11:12

1 Answers1

2

Here is a minimal example to illustrate the issue:

>>> def change(x):
        x = 2
        print x

>>> x = 1
>>> change(x)
2 # x inside change
>>> x
1 # is not the same as x outside

You need to fix the function to return something, and assign that to number in the outer scope:

def checkint(number):
    try:
        return int(number) # return in base case
    except:
        print ("Input not accepted, please only enter whole numbers.")
        number = input("Enter a whole number. Input -1 to end: ")
        return checkint(number) # and recursive case

number = input("Enter a whole number. Input -1 to end: ")
number = checkint(number) # assign result back to number

Also, it is better to do this iteratively rather than recursively - see e.g. Asking the user for input until they give a valid response.

Community
  • 1
  • 1
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437