2 Replies - 3047 Views - Last Post: 18 October 2016 - 03:00 AM

#1 atraub   User is offline

  • Pythoneer
  • member icon

Reputation: 833
  • View blog
  • Posts: 2,257
  • Joined: 23-December 08

Get input of specified type

Posted 21 April 2015 - 06:57 PM

This will give the user a message and ask him to return a value of a specified type (such as int, str, bool, float, etc...). If the user enters something that can't be cast to the appropriate type, an error is printed to the user and he's prompted to try again. This isn't meant to be a particularly robust strategy, just one that will help newer programmers get on their way.

#Python 2.x
def getInputOfType(message,typeExpected, errorMessage="Wrong Type!"):
    while True:
        userInput = raw_input(message)
        try:
            if typeExpected == bool and userInput.lower() == "false":
                return False
            return typeExpected(userInput)
        except ValueError:
            print(errorMessage)



#Python 3.x
def getInputOfType(message,typeExpected, errorMessage="Wrong Type!"):
    while True:
        userInput = input(message)
        try:
            if typeExpected == bool and userInput.lower() == "false":
                return False
            return typeExpected(userInput)
        except ValueError:
            print(errorMessage)



Is This A Good Question/Topic? 2
  • +

Replies To: Get input of specified type

#2 Feldrok   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 19-February 14

Re: Get input of specified type

Posted 21 April 2015 - 07:10 PM

Thanks :) I love this forum... So much help and understanding. Keep it going! Would love to be able to help some day when I become a better programmer :)
Was This Post Helpful? 0
  • +
  • -

#3 DK3250   User is offline

  • Pythonian
  • member icon

Reputation: 551
  • View blog
  • Posts: 1,721
  • Joined: 27-December 13

Re: Get input of specified type

Posted 18 October 2016 - 03:00 AM

I like your code snippet; it works well for type int, str and float.
I guess, however, that it may surprise most people that when typeExpected is bool, almost any input evaluates to True, including '42' and 'xyz'.
This is because you really evaluate bool(<str>) as the input generates an str output.

I suggest modifying the code such that bool only accepts *True', False' '0' and '1'; all other input should raise the ValueError.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1