-1

In Python how do you define a variable as a users response without type casting the response?

if the variable is a

a = raw_input("ENTER A NUMBER") # type casts "a" as a string
a = input("ENTER A NUMBER")     # type casts "a" as a integer

How do I let the computer decide what the the answer type the answer is?

martineau
  • 119,623
  • 25
  • 170
  • 301
Enod
  • 1
  • 1
  • 2
    Trust me: You do not want the computer to decide. – DYZ Feb 05 '17 at 23:31
  • Not sure what you mean. If you are using `input` (in python 2) it will let the computer decide. All inputs are strings ultimately, but `input` uses `eval` to decide type. `eval` use is generally considered bad practice. It's not used for `input` function python 3. – Paul Rooney Feb 05 '17 at 23:31
  • i want the user to originally put in a integer or a float but if the put in a string i want the computer to repeat the question until they put in an integer or a float – Enod Feb 05 '17 at 23:58

1 Answers1

0

You have to decide what types you are willing to accept, and what formats should become what types. Letting the user input arbitrary strings, and then having something "automatically" figure out the type, doesn't really make sense. If I type "1j", do you want a complex number? Probably not.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • i want the user to originally put in a integer or a float but if the put in a string i want the computer to repeat the question until they put in an integer or a float – Enod Feb 05 '17 at 23:34
  • 1
    @Enod in that case you have an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) i.e. an issue with your solution. You should take an input and attempt conversion to int and run it in a loop until the conversion succeeds. Look at something like [this](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response). – Paul Rooney Feb 05 '17 at 23:37
  • @Enod: All user keyboard input starts out as a string of characters. In Python 2, `input()` automatically calls `eval()` on this string which tries to interpret its contents as a Python expression—so what you say you want really makes no sense. – martineau Feb 05 '17 at 23:39