Who do I check if a user's input is string / int / float? My pseudo-code is: variable = input("Please enter a positive integer: ") if variable != int: #then do something awesome elif variable <0 #do something awesomer elif variable >=0 #do what you are supposed to do I have tried "if isinstance(variable, int)" to check types, but that just seems to crash my program with letters. With "raw_input" it also crashes. Any ideas? Thanks!
Raw input in python always takes in a string. So it is always a string. Then you can use the try system to see if it can be converted to a float to see if it is that. And if it makes it as a float, you can see if it has a decimal part to see if it is an int.
In this case, using "input" as you are, you could try checking the type(variable).
Recall that the difference between "raw_input" and "input" is that the first, as @e.mccormick stated, takes all input as a string and the latter takes the input in as int, string, float, etc., by interpreting how closely it matches the types.
As an aside, the 2.x input method is going away. 3.x is going to 100% raw input type actions because of exactly this issue. So for future proofing, getting used to the try system is worth it. Personally, I think try needs to be one of the first things they teach. Code people write in the start assumes the user follows the directions and give the program what it needs. This is not true in real life, so the exception handling system, try, is the solution. But they generally save that for the middle to end of a class....
Interestingly, the example for try under 8.3 is exactly what you would want. http://docs.python.org/2/tutorial/errors.html
Used the "try" system and it worked well, thank you guys for your input!
np. Have fun! And just think, by learning try you are ahead of the curve! The exception system is a key part of good programming. It keeps programs running when they could otherwise crash!
Join our real-time social learning platform and learn together with your friends!