Search code examples
pythonpython-2.7while-loopinfinite-loop

Find largest number from user input


I trying to make a code which print largest and smallest number from user input. I want that user can input the number until there is ValueError

I have tried something like this:

value = raw_input(">")

largest_so_far = None
smalest_so_far = None

while(value):
    if value > largest_so_far:
        largest_so_far = value
    if ValueError:
        print largest_so_far

this code creates infinite loop. So how can I make it finite.


Solution

  • You need to use try and except here.

    while(True):
        try:
             value = float(raw_input(">"))     # Get the input from user
             if value > largest_so_far:        # Type cast to integer
                largest_so_far = value
        except ValueError as e:                # Handle ValueError
            print largest_so_far
            break                              # Break the infinite loop