Input Types

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • EAS

    Input Types

    How do you make a loop where the program keeps asking for
    an integer or float until it gets one? (No letters or other input.)


  • Jeff Epler

    #2
    Re: Input Types

    Here's a function that can do the job.

    def typed_input(pro mpt="", convert=int, catch=ValueErro r,
    eprompt="Invali d input."):
    while 1:
    s = raw_input(promp t)
    try:
    return convert(s)
    except catch:
    print eprompt

    Usage:[color=blue][color=green][color=darkred]
    >>> typed_input("En ter an integer: ")[/color][/color][/color]
    Enter an integer: asdf
    Invalid input
    Enter an integer: 3
    3[color=blue][color=green][color=darkred]
    >>> typed_input("En ter a number: ", float)[/color][/color][/color]
    Enter a number:
    Invalid input
    Enter a number: 3.14
    3.1400000000000 001

    How does it work?

    1. The "while 1" loop is repeated until the "return" statement is
    successfully executed.

    2. int(s) and float(s) convert a string argument s to the specified
    type, or raise the ValueError exception

    3. When there is a ValueError exception, the "error prompt" is printed,
    and the while loop returns to the top to try again.

    You can also write your own "convert" function to restrict values to a
    range, etc:
    [color=blue][color=green][color=darkred]
    >>> def int_0_100(s):[/color][/color][/color]
    .... i = int(s)
    .... if i < 0 or i > 100:
    .... raise ValueError # out of range
    .... return i
    ....[color=blue][color=green][color=darkred]
    >>> typed_input("En ter a number from 0 to 100: ", int_0_100)[/color][/color][/color]
    Enter a number from 0 to 100: asdf
    Invalid input.
    Enter a number from 0 to 100: 101
    Invalid input.
    Enter a number from 0 to 100: 37
    37

    You can also specify the catch= or eprompt= arguments to change the
    exception that is caught or the error prompt string.

    Jeff

    Comment

    • Leif K-Brooks

      #3
      Re: Input Types

      EAS wrote:[color=blue]
      > How do you make a loop where the program keeps asking for
      > an integer or float until it gets one? (No letters or other input.)[/color]

      import sys # We need sys.stdin for input
      while True: # Infinite loop. We break out of it after getting a float.
      try: # For catching the exception of getting an invalid float.
      num = float(sys.stdin .readline().rst rip("\r\n")) # Try
      # parsing it as a float.
      break # If we reach this line, it's valid. Exit the loop
      except ValueError: # It's an invalid float.
      pass # Just let the loop run again.

      Comment

      • moma

        #4
        Re: Input Types

        Jeff Epler wrote:[color=blue]
        > Here's a function that can do the job.
        >
        > def typed_input(pro mpt="", convert=int, catch=ValueErro r,
        > eprompt="Invali d input."):
        > while 1:
        > s = raw_input(promp t)
        > try:
        > return convert(s)
        > except catch:
        > print eprompt
        >[/color]

        You can send functions (int, float) and exceptions as parameters?
        Amazing.

        [color=blue]
        > Usage:[color=green][color=darkred]
        >>>>typed_input ("Enter an integer: ")[/color][/color]
        >
        > Enter an integer: asdf
        > Invalid input
        > Enter an integer: 3
        > 3
        >[color=green][color=darkred]
        >>>>typed_input ("Enter a number: ", float)[/color][/color]
        >
        > Enter a number:
        > Invalid input
        > Enter a number: 3.14
        > 3.1400000000000 001
        >
        > How does it work?
        >
        > 1. The "while 1" loop is repeated until the "return" statement is
        > successfully executed.
        >
        > 2. int(s) and float(s) convert a string argument s to the specified
        > type, or raise the ValueError exception
        >
        > 3. When there is a ValueError exception, the "error prompt" is printed,
        > and the while loop returns to the top to try again.
        >
        > You can also write your own "convert" function to restrict values to a
        > range, etc:
        >
        >[color=green][color=darkred]
        >>>>def int_0_100(s):[/color][/color]
        >
        > ... i = int(s)
        > ... if i < 0 or i > 100:
        > ... raise ValueError # out of range
        > ... return i
        > ...
        >[color=green][color=darkred]
        >>>>typed_input ("Enter a number from 0 to 100: ", int_0_100)[/color][/color]
        >
        > Enter a number from 0 to 100: asdf
        > Invalid input.
        > Enter a number from 0 to 100: 101
        > Invalid input.
        > Enter a number from 0 to 100: 37
        > 37
        >
        > You can also specify the catch= or eprompt= arguments to change the
        > exception that is caught or the error prompt string.
        >
        > Jeff
        >[/color]

        Comment

        • Jeff Epler

          #5
          Re: Input Types

          On Sat, May 15, 2004 at 08:23:51PM +0200, moma wrote:[color=blue]
          > You can send functions (int, float) and exceptions as parameters?
          > Amazing.[/color]

          You sure can.

          numbers, sequences, dicts, functions, exceptions, classes, modules: all
          these things are objects, and you can pass any object you like as a
          parameter. Of course, not all object types *make sense* everywhere!

          One "exception" to this rule is thinking that print is a function, and
          trying to write
          def send_to(value, action):
          return action(value)

          def f(x): return x*x
          [color=blue][color=green][color=darkred]
          >>> send_to(3, f) # square the argument: works[/color][/color][/color]
          9[color=blue][color=green][color=darkred]
          >>> send_to(3, print) # Print the argument: error[/color][/color][/color]
          File "<stdin>", line 1
          send_to(3, print)
          ^
          SyntaxError: invalid syntax

          because print is a statement, not a function, this isn't really an
          exception to the rule at all.

          Jeff

          Comment

          Working...