Search code examples
python-3.xmaxmintry-except

How to not include character or string input in the array (Python)


I'm trying to write a simple program where a variable will store the input type in by a user until the word "done" is seen. After that, the program will print out the maximum and minimum value store in the variable. However, I would like to prevent the variable from storing characters or strings where the user may accidentally type in. What are ways that I can use? Try and except?

a=0
store1=''
store2=''
while store1 !='done':
     store1 = input('Enter a number: ')
     store2=store2+' '+store1
     a =a+1
store3=store2.split()
store4=store3[:a-1]
print('Maximum: %s'%(max(store4)))
print('Minimum: %s'%(min(store4)))

Unwanted result

I tried another way and I got this problem. Does anyone know what is wrong?

def RepresentsInt(s):
    try: 
        int(s)
        return True
    except ValueError:
        return False
a=0
store1=''
store2=''
while store1 !='done':
    store1 = input('Enter a number: ')
    b = RepresentsInt(store1)
    if(b==True): 
        store2=store2+' '+store1
    #        a =a+1
 store3=store2.split()
 #store4=store3[:a-1]
 print(store3)
 print('Maximum: %s'%(max(store3)))
 print('Minimum: %s'%(min(store3)))
 #print(len(store3))

The stored value seems to contain only numbers in string-format. However, when it prints out the max and min values, it doesn't print out the correct max and min as the picture shown below. Another way


Solution

  • Using your current implementation (number of issues), here's how you'd perform the check:

    a=0
    store1=''
    store2=''
    while store1 !='done':
      store1 = input('Enter a number: ')
      if store1 == 'done':
        break;
      try:
        int(store1)
      except ValueError:
        continue
      store2=store2+' '+store1
      a =a+1
    store3=store2.split()
    store4=store3[:a-1]
    print('Maximum: %s'%(max(store4)))
    print('Minimum: %s'%(min(store4)))
    

    I added in an immediate check for the input value (otherwise it executes the with the 'done' value, causing the Maximum: d output).

    For the input checking, the approach is trying to convert the string to an integer and returning to the start of the loop if a ValueError is caught.

    Using this looks like:

    $ python3 input.py
    Enter a number: 1
    Enter a number: 2
    Enter a number: what
    Ivalid input.
    Enter a number: 3
    Enter a number: 4
    Enter a number: done
    Maximum: 3
    Minimum: 1
    

    So, we still have a problem with actually finding the maximum value. Which begs the question, why all the string manipulation?

    Here's a simpler implementation using an array instead:

    numbers = []
    while True:
      input_value = input('Enter a number: ')
      if input_value == 'done':
        break
      try:
        int_value = int(input_value)
      except ValueError:
        print("Ivalid input.")
        continue
      numbers.append(int_value)
    
    print('Maximum: %s'%(max(numbers)))
    print('Minimum: %s'%(min(numbers)))
    

    Usage:

    $ python3 input.py
    Enter a number: 1
    Enter a number: 2
    Enter a number: what
    Ivalid input.
    Enter a number: 3
    Enter a number: 4
    Enter a number: done
    Maximum: 4
    Minimum: 1
    

    EDIT: The problem with your second attempt is that you are performing a lexicographic sort, instead of a numerical one. This is due to fact that the array is storing string values.

    # sorting strings, lexicographically
    >>> [x for x in sorted(['1000', '80', '10'])]
    ['10', '1000', '80']
    
    # sorting numbers, numerically
    >>> [x for x in sorted([1000, 80, 10])]
    [10, 80, 1000]
    

    In my fixed example above, the strings are converted to integer values before they get stored in the array, so they end up being sorted numerically.