0

I have a task

Print the minimal value from list you entered. First entered value defines the length of the list. Each next value should be placed in list one by one. Use operator for.

n is defined before, by input and start_n = 1

def list2_func():     
    global list2
    list2 = []
    for i in xrange(start_n, n + 1):
        list2.append(raw_input('Enter the %s number: ' % i))
        list2_check()
def list2_check():
    global start_n
    try:
        value = int(list2[-1])
    except ValueError:
        print "Please use only 0-9 keys. Re enter %s number" % len(list2)
        start_n = len(list2)
        list2_func()
    else: 
        start_n = start_n + 1

Everytime I enter any key which is not passing the try it asks for same value again - which is great. But when I enter my last value (for example n = 4, so 4th value) program asks me again to input. At the end I got 2*n - 1 amount of values - which is not what i want.

Could you please suggest me any another way to check if entered value is a number? Or point the mistake in my code!

I'm using python 2.7.

Konstantin
  • 24,271
  • 5
  • 48
  • 65
  • possible duplicate of [Python - How to check if input is a number (given that input always returns strings)](http://stackoverflow.com/questions/5424716/python-how-to-check-if-input-is-a-number-given-that-input-always-returns-stri) – Łukasz Rogalski Apr 23 '15 at 10:51
  • The list2_check() function should be de-coupled. It should only check if a number is numeric. It shouldn't call the caller. In the for loop, add a while loop that loops until the person has entered a valid number. – Scooter Apr 23 '15 at 10:59

5 Answers5

0

There are possible errors in your code. You are appending the number multiple times if the check fails. Try the following code which would make sure you are appending single valid value to the list.

def get_value(i):
    while True:
        number = raw_input('Enter the %s number: ' % i)
        try:
            value = int(number)
        except:
            continue
        return value

def list2_func():
    list2 = []
    for i in xrange(start_n, n + 1):
        number = get_value(i)
        list2.append(number)
Barun Sharma
  • 1,452
  • 2
  • 15
  • 20
0

you don't need to use the list2_check function :

def list2_func():     
        list2 = []
        i=start_n
        while i<n+1:
            try:
                list2.append(int(raw_input('Enter the %s number: ' % i)))
                i+=1
            except ValueError:
                print "Please use only 0-9 keys. Re enter %s number" % len(list2)
        return list2

I also deleted your global variable, as it is preferable to use a return than having global variables. (they may cause issues if you try to have another variable with the same name)

CoMartel
  • 3,521
  • 4
  • 25
  • 48
0

Just played with the code a litle and found the problem. Program was finishing first FOR loop and starting new for loop for every value which didnt passed the try test.

def list2_func():
    global list2
    list2 = []
    for i in xrange(1, n+1):
        list2.append(raw_input('Enter the %s number: ' % i))
        list2_check()
def list2_check():
    try:
        value = int(list2[-1])
    except ValueError:
        list2[-1]= raw_input("Please, use only 0-9 keys" % len(list2))
        list2_check()
    else:
        pass

Now it just asking to replace the wrong value instead of starting for loop again :)

0

This because you have a recursive function. Each function call the other. Also, strart_n is modified in each loop (remove else case of try).

cosmoscalibur
  • 1,131
  • 1
  • 8
  • 17
0

Your problem is in the logic used : you add the wrong entered value (via list2.append), then check the list and never delete the last entered value if value is wrong. So, if you want to keep your code, you juste have to delete the last item in the list when ValueError is raised.

BUT, your code also have many other problems you should resolve : you use recursion, and it will be easy to crash your program : only enter bad values : each time, you do a new call to "list2_func" inside "list2_func". So with 5 consecutive wrong values we have :

call to list2_func:
    call to list2_func:
        call to list2_func:
            call to list2_func:
                call to list2_func:

Of course, python will crash when its max recursion will be reached :)

Another problem is the use of a global variable. It's bad. Only do that if you really need a global var.

Here is one of many solutions existing to your exercise :

def get_list():
    """
    Returns an user's entered list.
    First entered value defines the length of the list. 
    Each next value should be placed in list one by one. 
    """
    wanted_length = None
    my_list = []
    while wanted_length < 1:
        try:
            wanted_length = int(raw_input('Please enter the wanted length of the list (int > 0) : '))
        except ValueError:
            pass
    i = 1
    while i <= wanted_length:
        try:
            my_list.append(int(raw_input('Please enther the number %d (int only) : ' % i)))
        except ValueError:
            pass
        else:
            i += 1
    return my_list

def print_min_with_for(l):
    """
    Prints the minimal value from list you entered using operator `for`.
    """
    if not l:
        print 'List is empty'
        return
    min_value = None
    for i in l:
        if min_value is None or i < min_value:
            min_value = i
    print 'min value in the list is : %d' % min_value

my_list = get_list()
print 'Printed min value in the list should be : %d' % min(my_list)
print_min_with_for(my_list)

Welcome to python BTW ;-)

DylannCordel
  • 586
  • 5
  • 10