Why does input() only return strings? - python

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/

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.

How can we understand if the value inside a String is an int or not in Python?

I am writing a code where I am facing the problem and need a solution if it exists.
Suppose we have a following String type variable in Python which contains an integer value.
Eg:x='123'
I know that we can easily convert this by type conversion to int.
However, suppose we have the following list.
x=['123','Spain']
Is there any method in Python by which I can know which element of the list x is Integer contained inside a string and which is purely an Object?
I would recommend this method:
x = "123"
if x.isdigit():
# int
elif x.replace(".","",1).isdigit():
# float
else:
# str
I assume you have similar question with this post.
But, from my perspective, for more general solution (language agnostic), you should learn more about Regular Expression, here also the same question

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

Iterable error with int when using for / argument ()error while using map. Where am i going worng

I tried bith ways using map nad using for loop but its not working i know for for loop it has to list,tuples or string. So how do i make this work
1
def narcissistic(value):
x = ((value)== sum((c)**len(value) for c in list(value)))
return x
2
def narcissistic(value):
x=(value== (map(lambda c :sum(c**len(value)),value)))
return x
Your issue comes down to confusion about the type of your different objects. Python is a strongly typed language, so each object has a clear type at any given moment and the language generally won't convert anything to another type automatically for you.
Based on the error you're getting, you're calling your function with an int argument. This causes you trouble when you try to call len or iterate on your value. Python ints don't have a length, nor are they iterable, so it's quite understandable that these fail under the circumstances.
What you want to do is create a string representation of your value number. Then you can loop over the characters of the string, and take its len freely.
There's another issue though. You're also trying to do an exponential operation on the c variable in the generator expression. That won't work because c is a string, not a number. It's a one-digit string, but still a str instance! To do math with it, you need to convert it back to a number with int.
Here's a fixed version of your function:
def narcissistic(number):
num_str = str(number)
return sum(int(c)**len(num_str) for c in num_str) == number
I've renamed the very generic value name with number, which should hopefully make it more clear what type each thing is.

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