Why Is 'user_input' Always A String? - python

def user_input_checker(user_input):
if isinstance(user_input, int):
print('user_input is an integer.')
if isinstance(user_input, float):
print('user_input is a float point.')
if isinstance(user_input, str):
print('user_input is a string')
print('What is your input?')
user_input = input()
print('Input = %s'%user_input)
user_input_checker(user_input)
I had created some code to check if a user's input was an integer, a float point, or a string, and everytime I would put use an integer or a float point, it would still output that it was a string.
Is there something really easy that I'm missing?

In your code, user_input is always a string because the input() function always returns string values. This is described in Python's documentation (emphasis mine):
https://docs.python.org/3/library/functions.html#input
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
It's true that Python does not have statically declared types and Python has some type-juggling, but Python variables still have types that generally aren't "magic" and so if someone enters 1.2 into an input() prompt, it will still be returned as a string "1.2" and not a decimal value.
Your question title says pay_rate, which sounds like a monetary value. You must not represent monetary amounts (i.e. currency, money) with a floating-point type such as float. Instead use Decimal.

Related

Convert string with "_" to int?

I have a function which takes a string input, tries to convert it to integer and then proceeds with two alternative paths depending on whether the conversion succeeded or not:
def make_int(arg):
try:
int_value = int(arg)
except ValueError:
str_value = arg
I now was quite surprised when the string '123_2307_7' was happily converted to the integer 12323077 - whereas I was expecting it to follow the str path here. What details of str -> int conversion is it I have not yet grokked?
As pointed out by #jonrsharpe the docs says you can embed single _ charcaters in your integer literal - which are simply ignored. Closing.
In python you can write any integer/float this way :
XXX_XXX_XXX
Keep in mind that integer/float are objects in python.

Why does input() only return strings?

My question is very simple, I want to know that when we initialize a variable in python it recognize it whether it is string or integer, But when we use input function it takes input as string and if we need integer or float we have to type cast it. why?
Because input() always returns a str. In another words, input() "recognizes" everything (what is entered to it) as a string.
There is a difference between "123", which is string and 123, which is int. To make int from string, you should use type casting - int(input('Number: ').
input() function is not designed to autodetect type, like Python does, because it is inconvenient default behavior. In all usual cases, a program except certain input type from user. You can implement such thing by yourself (if needed).
Python CAN recognize type of variable. But most of the time python doesn't NEED to.
As mentioned, input always returns str. You need to cast it into int only if you're gonna do something integer-specific with it. In most cases python doesn't care about type of variables. It is called duck typing
https://realpython.com/lessons/duck-typing/

How does this string add to this int

I was under the impression that in Python it was necessary to write (str) when converting an int to a str, but in this case, if the user inputs a number, it still executes fine
print('Enter a name.')
name = input()
if name:
print('Thank you for entering a name, ' + name)
else:
print('You did not enter a name.')
I didn't need to write + str(name) on line 4 when the input entered was 1, for example (or any number).
If you read the docs on input then you will see this line that refers to your scenario:
The function reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
We can also see this in the interpreter:
>>> type(input())
<class 'str'>
And, to clarify, Python will never return an int from input(), you always need to convert if you want to do arithmetic operations or otherwise.
Note that the behaviour is different in Python 2 which offers input() and raw_input(). The first of which will convert the input to the appropriate data type (such as int) whereas the latter will function the same as input() in Python 3.
This can again be tested in the interpreter:
>>> type(input())
5
<type 'int'>
>>> type(raw_input())
5
<type 'str'>
Because Python does some stuff in the background to figure out what the variable types are. Plus, the input from input is always a string. You just concatenated two strings.
The function input always returns a string. What you just witnessed is a string concatenation.
If you wanted to convert the results of input into a different type, say integers, then you can do:
x = int(input("Enter a number"))
This will raise an error if the input cannot be expressed as an int type though. You can do additional parsing or type testing (e.g. isinstance() or type() is...) depending on the complexity of the input you're expecting.

How to detect and cast string back into right type in Python

In my python server code, I am getting all arguments as strings. I am unaware of the original type of the argument.
For example,
if the actual value is integer 10, the argument received is string value '10'
if the actual value is string "apple". The argument received is unchanged string 'apple'
if the actual value is float 10.0 , the argument received is string value '10.0'
What is the best way to detect the right type of the argument and cast them back to 'int' in the first example, 'string' in the second example, 'float' in the third example?
Ideally, you want to fix the client code so it doesn't throw away type information in the first place. Or, if you can't do that, you at least want to know what the rule is for how these strings are generated, so you can work out how to reverse the rule.
But if neither of those is possible, and you need to guess, one possibility is something like this:
def parseval(s):
try:
return int(s)
except ValueError:
pass
try:
return float(s)
except ValueError:
pass
return s
This will treat anything that could be a valid int as an int, anything that can't be a valid int but could be a valid float as a float, and anything else as a str.
In the special case where the output comes from just calling repr or str in Python, you may want this:
import ast
def parseval(s):
try:
return ast.literal_eval(s)
except ValueError:
return s
This will convert any Python literal, or any collection display made up of literals and other collection displays made up of etc. recursively, to the original value, but leave anything else as itself. (If you know the client is using repr rather than str, you should leave off the try/except. But if it's using str, this works, because it relies on the fact that, for every kind of literal but strings, the str is interpretable as a repr.)
However, note that this makes it impossible to, e.g., send the string "10" to your server.

How can I determine if user input is a valid hexadecimal number?

#Hex Check
def Check():
while False:
for char in UserInput:
if char not in Valid:
print ('That is an invalid hex value.')
print('That is a valid hex value.')
return Check
UserInput=input('Enter a hex number: ')
Valid='1''2''3''4''5''6''7''8''9''10''A''B''C''D''E''F'
EDIT: I've tried this. When I enter a hex value e.g. B2 no message comes up.
Change line 6 to
Hex=int(input('Enter a hex number: '), 16)
This line would successfully parse any hexadecimal input (for example, '0x123f') and would throw a ValueError on an invalid input (such as 'hello').
ETA: Based on your comments, the following is all you need:
user_input = input('Enter a hex number: ')
try:
hexval = int(user_input, 16)
print 'That is a valid hex value.'
except:
print 'That is an invalid hex value.'
ETA: If you really have to have a Check function, this structure would be the best way to do it:
import re
def Check(s):
"""Check if a string is a valid hexadecimal number"""
# code for checking if it is a valid hex number here
user_input = raw_input("Enter a hex number: ")
if Check(user_input):
print 'That is a valid hex value.'
else:
print 'That is an invalid hex value.'
Since this is a homework question I'm not going to finish the answer- just know that the Check function has to return True if the string is a valid hex statement or False if the string is not.
There are many ideas among everyone's answers of how to do it, and you could indeed use a try/except statement like I do above. One of the best ways to do it would be to use regular expressions, which are a very powerful way to parse strings.
Investigate the regex library. Or do explicit cast to int then catch any errors and process them accordingly.
The only valid values for hex strings are 0-9, A-F . It should be possible to store these values in a list / array and then do a simple contains call. Something along the lines of this:
for char in userInput:
if not char in validTokens:
print 'invalid hex value'
Here is a nice, Python way to check your input for a valid hex number.
def Check():
while not Valid:
try:
Hex=int(raw_input('Enter a hex number: '), 16)
print('That is valid.')
return True
except ValueError:
print('That is an invalid entry.')
return False
I am answering this question from a Python philosophy point of view, because you have already received good answers, some of them involving try: .. except.
The Pythonic thing about using exception handling try: .. except is the way Python programmers seem to be encouraged to use it is, at least for me, a departure from exception handling in other languages.
In Python, you are encouraged to raise an exception, either explicitly using raise or more implicitly within the construct of try .. except.
When I posed a question a while back about how to deal with null integer values in a .csv file, I was encouraged to go ahead with the assignment to the Python integer variable within try: .. except, instead of testing first to test to see if the value was null.
The answer went on to say don't bother to test and then take action, use exception handling, because it is more Pythonic. Using try: .. except also appeared to consume fewer instructions.
That attitude got me to write more exception handling than I would have thinking using try: .. except was reserved only for when bad things happen.
The expression
string.translate(x, None, "0123456789abcdefABCDEF") == ''
is True iff x contains valid hexadecimal characters, or x is the null string.(You need to "import string".)
Obviously this can be used to validate that a string contains only characters from any given set (or is null).

Categories