Convert any user input to int in Python - python

I need to convert user input to int. Below is what I have written so far which is not working out. It only accepts int. the end goal is to have a user inputs float (e.g 4.5) and the output would be (4).
i = input("Enter any value: ")
print(int(i))

int accepts integer string or a float but cannot handle float strings. So convert to float first and then convert to integer. If the input is invalid format, int(i) would raise ValueError exception, so you can use it to handle invalid inputs.
i = input("Enter any value: ")
try:
print(float(int(i))
except ValueError:
print("Please enter a number")

The input are in string format so first you need to convert it into float and then from float to int
You can do
i = input("Enter any value: ")
print(int(float(i)))
or you can do
i = float(input("Enter any value: "))
print(int(i))

Apart from the other answers, you can use round() function:
i = input("Enter any value: ")
print(round(i))
But if you want to simply cut the decimal part, you can use math lib and floor():
import math
i = input("Enter any value: ")
print(math.floor(i))

Related

Python Check only outputting a string

num = input("Enter Something:")
print(type(num))
for some reason when running this code, or any alternative version even without text (string), it still outputs a string.
<class 'str'>
is there any way to check for all types like expected? e.g str and int
The problem is that input() returns a string, so the datatype of num will always be a string. If you want to look at that string and determine whether it's a string, int, or float, you can try converting the string to those datatypes explicitly and check for errors.
Here's an example of one such check:
def check_user_input(input):
try:
# Convert it into integer
val = int(input)
print("Input is an integer number. Number = ", val)
except ValueError:
try:
# Convert it into float
val = float(input)
print("Input is a float number. Number = ", val)
except ValueError:
print("No.. input is not a number. It's a string")
I got this example here where there's a more thorough explanation: https://pynative.com/python-check-user-input-is-number-or-string/
Here is a solution based on that for your problem specifically:
def convert_input(input):
try:
# Convert it into integer
val = int(input)
return val
except ValueError:
try:
# Convert it into float
val = float(input)
return val
except ValueError:
return input
num = input("Enter Something:")
num = convert_input(num)
print(type(num))
Input always returns string. If you want some other type you have to cast.
For example:
input_int = int(input("Enter something"))
You should know that, the default input is set to return string. To make this clear, do refer to the following example:
>>> number_input = input("Input a number: ")
Input a number: 17
>>> number = number_input
>>> print(type(number))
<class 'str'>
Python defines the number_input as a string, because input is by default a string. And if python recognizes number_input as string, variable number must also be a string, even though it is purely numbers.
To set number as a int, you need to specify the input as int(input("Input a number: ")). And of course, if you want to input float, just change the data type to float input.
But answering your question, you can't print <class 'str'> and <class 'int'> at the same time.
By default when you type input(), python run it as string data-type so you can change or actually limit it by usage of int()
integer_number = int(input("only numbers accepted: "))

Why doesn't the int() function convert a float to integer while in input() function?

Why doesn't the int() function convert a float to integer while in input() function?
input_1 = input(f'enter the num: ')
try:
a = int(input_1)
print(f"it is an integer")
except:
print(f"no an integer")
input_1 = 3.532453
try:
a = int(input_1)
print(f"it is an integer")
except:
print(f"no an integer")
Result:
enter the num: 3.532453
no an integer
it is an integer
Bear in mind that the input_1 value when you request for an input is not a float, is a string
input_1 = input(f'enter the num: ')
print(type(input_1)) # ​<class 'str'>
So with the cast you are trying to convert a string with value 3.532453 into a integer.
If you cast this string to a float first and then you cast it into a integer, it will work.
input_1 = input(f'enter the num: ')
try:
a = int(float(input_1))
print(f"it is an integer")
except:
print(f"no an integer")
The input function returns a string (type str in python). The int function accepts a string as long as this string represents a valid integer (base 10 by default). This means when you pass a string that contains a ., int will fail because the string is not a valid integer.
>>> input_1 = input(f'enter the num: ')
enter the num: 3.532453
>>> print(type(input_1))
<class 'str'>
>>> int(input_1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.532453'
On the other hand, when you do input_1 = 3.532453, you are creating a variable input_1 of type float. The int function accepts float arguments and casts them to integer by stripping the floating point part.
>>> input_1 = 3.532453
>>> print(type(input_1))
<class 'float'>
>>> int(input_1)
3
print(int(123.456)): you can convert a non-integer to int
print(int("123456")): you can convert a string representing an integer to int
print(int("123.456")): you cannot convert a string representing a non-integer to int
I mean, you can, but not by using the int(...) operation directly.
So you can change a decimal to an int in python. But not without losing all the data past the decimal point. For example if you convert "12.3356" to an int using int(float("12.3356") and the result would be 12.
An int value in python is one without a decimal point for eg: 3.
A float value in python is a number with a decimal point for eg:
3.141.
So, if you want to check if what a user enters is a number and conserve everything past the decimal point, convert the strings to a float instead of an int:
input_1 = input('enter the num: ')
try:
a = float(input_1)
print("it is a number")
except ValueError:
print("not a number")
By using float() instead of int(), you get to keep all the data past the decimal point (if you need it in other parts of your program).
However, if you still want to convert a float to an int (and lose everything past the decimal point), you can do:
Note that the below is basically extra code for a disadvantage and the above is usually better (in most cases), but if that's what you want well here you go:
input_1 = input('enter the num: ')
try:
a = int(float(input_1))
print("it is a number")
except ValueError:
print("not a number")

How do I get the user to input an int rather than a float?

I'm writing a program that takes in a value from the user, in the console, and I'm casting it to an int like so:
num = int(input("Enter a number: "))
I need my program to work with ints only. This works to convert an actual int entered into the console to an int I can use in the program, but if the user enters a float, like 3.1, then it doesn't cast to an int by truncating or rounding up for example.
How do I get the user to input an int rather than a float? Or how do I convert a floating point input to an int?
You can use a try catch block to ensure they only give you an int:
while True:
try:
num = int(input("Enter a number: "))
#do something with num and then break out of the while loop with break
except ValueError:
print("That was not a number, please do not use decimals!")
When ValueError (when it fails to convert to int) is excepted it goes back to asking for a number which once you get your number you can do things with said number or break out of the loop then and use num elsewhere.
You can use a try except to test if a user input is a whole number. Example code:
while True:
try:
value=int(input("Type a number:"))
break
except ValueError:
print("This is not a whole number.")
This code will loop back to the start if a user inputs something that is not an int.
So int() of a string like "3.1" doesnt work of course. But you can cast the input to a float and then to int:
num = int(float(input("Enter a number: ")))
It will always round down. If you want it to round up if >= .5:
num = float(input("Enter a number: "))
num = round(num, 0)
num = int(num)
You can simply use eval python built-in function. num = int(eval(input("Enter a number: "))).
For converting string into python code and evaluating mathimatical expressions, eval function is mostly used. For example, eval("2 + 3") will give you 5. However, if you write "2 + 3", then u will get only '2 + 3' as string value.
Try:
num = int(float(input("Enter number: ")))
and the float will be rounded to int.
You can also add a try...except method to give error to user if the number cannot be converted for any reason:
while True:
try:
num = int(float(input("Enter number: ")))
print(num)
break
except ValueError:
print("This is not a whole number")
use abs() it returns the absolute value of the given number

How to find type of user input and print different values depending on the type of input in Python 3.x

Develop a Python function which either returns the float square of its parameter x if the parameter is a number, or prints the string "Sorry Dave, I'm afraid I can't do that" if the parameter is a string, and then returns 0.0.
What am I doing wrong? I'm a first year CS student and I have no previous programming background.
I created a function that takes user input, evaluates what type of input it is and print different out puts for number and strings.
For that I used eval(var) func. I also the type(var) == type to verify the type and a if-else loop.
def findt():
userin = input("Input: ") # Takes user input
inpeval = eval(userin) # Evaluates input type
if type(inpeval) == int: # If input is an int
userfloat = float(inpeval) # Modifies into a float
print(userfloat ** 2) # Prints the square of the value
elif type(inpeval) == float: # If input is a float
print(inpreval ** 2) # Prints the square of the value
elif type(userin) == str: # If input is a string
print("Sorry Dave, I'm afraid I can't do that") # Print a string
return 0.0 # Return 0.0
else:
print("Invalid Input")
findt()
When I run my code it works well when input is an int, a float or a char. But if I write more than one char it returns me an error:
NameError: name 'whateverinput' is not defined.
You're trying to eval input before you know it's needed. Get rid of it entirely:
def findt():
userin = input("Input: ") # Takes user input
if type(userin) == int: # If input is an int
userfloat = float(userin) # Modifies into a float
...
The root problem is that you can't evaluate an undefined name.
If your input is a string that is not the name of an object in your program, it will fail. eval requires everything you feed it to be defined.
I found the solution for my problem.
The way I did it I take the input from the user and i try to convert it to a float. If it is a number it will convert and print a float that is the square of the input. If the input is a string it cannot be converted to a float and will give me an error so I use an except ValueError: to print the string I want and return 0.0.
def whattype():
user_input = input(">>> ")
try:
user_input = float(user_input)
print(user_input ** 2)
except ValueError:
print("Sorry Dave, I'm afraid I can't do that")
return 0.0
whattype()
Thank you all for the suggestions and help
Here is a better way to achieve your goal by using the string method isnumeric() to test if the input is numeric or not.
def findt():
userin = input("Input: ")
if userin.isnumeric():
# userin is numeric
result = float(userin) ** 2
print(result)
else:
try:
# userin is a float
result = float(userin) ** 2
print(result)
except ValueError:
# userin is a string
print("Sorry Dave, I'm afraid I can't do that")
return 0.0
findt()
Update: a concise version:
def findt():
userin = input("Input: ")
try:
# userin is an int or float
result = float(userin) ** 2
print(result)
except ValueError:
# userin is a string
print("Sorry Dave, I'm afraid I can't do that")
return 0.0
findt()

Why does Python's eval(input("Enter input: ")) change input's datatype?

In Python 3, I write a simple command to accept an integer input from the user thus:
x = int(input("Enter a number: "))
If I skip the int() part and simply use x = input("Enter a number: "), my input's datatype is a string, not an integer. I understand that.
However, if I use the following command:
x = eval(input("Enter a number: "))
the input's datatype is 'int'.
Why does this happen?
Why does this happen?
x = eval(input("Enter a number: ")) is not the same thing as x = eval('input("Enter a number: ")')
The former first calls input(...), gets a string, e.g. '5' then evaluates it, that's why you get an int, in this manner:
>>> eval('5') # the str '5' is e.g. the value it gets after calling input(...)
5 # You get an int
While the latter (more aligned with what you were expecting), evaluates the expression 'input("Enter a number: ")'
>>> x = eval('input("Enter a number: ")')
Enter a number: 5
>>> x
'5' # Here you get a str
Because a number is a valid expression in Python, and it evaluates to itself (and its type is int). For example, if you input a rubbish string with a non-existing name (say, 'abcdefgh'), a NameError exception will be raised (the exception is raised while evaluating).

Categories