How does this string add to this int - python

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.

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/

Why Is 'user_input' Always A String?

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.

How to check for a string's "natural" datatype in Python?

I have a user inputting arguments to the command line when running a python3 script, and I wish to check whether specific arguments are floats, ints, booleans, or strings. I'm familiar with the errors that are thrown when a string like 'car' is cast to an int using the int() function, and am also familiar with using a try/except block to attempt to cast a string to an int, and if this is unsuccessful, how to map error messages to helpful output to the user. I've also seen this previous question, which will probably do the job. Was just wondering if there had been any new development.
Not sure if this is possible, but looking for a smart type() function that could operate as such:
#!/usr/bin/env python3
import sys
smarttype(sys.argv[-1])
and is capable of handling the following kinds of inputs:
./script.py 50
./script.py True
./script.py 50.0
./script.py run
and output:
int
bool
float
str
I usually use ast.literal_eval to parse “elementary” data types:
type(ast.literal_eval('50')) # outputs int
You need however a set of quotes to mark something as a string (otherwise every input could be taken as a string):
type(ast.literal_eval('run')) # error
type(ast.literal_eval('"run"')) # string
If you want to allow unqouted strings you could do the following:
def parse_data(x):
"""Takes a string x and returns the "value" of x"""
try:
return ast.literal_eval(x)
except (ValueError, SyntaxError):
return x

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.

Categories