Check if the input is integer float or string in python - python

I am a beginner in python and I am currently working on a calculator not like this:
Enter Something: add
"Enter 1 number : 1"
"Enter 2 number : 3"
The answer is 5
not like that or using eval()
I Want to create a calculator where they input something like this: "add 1 3" and output should be 4.
but I have to check that the first word is a string 2nd is a integer or float and 3rd is also number
I have created a script but I have one problem that I don't know how to check if the input is a integer or string or float I have used isdigit() it works but it doesn't count negative numbers and float as a number I have also used isinstance() but it doesn't work and thinks that the input is a integer even when its a string and I don't know how to use the try and except method on this script
while True:
exitcond = ["exit","close","quit"]
operators =["add","subtract","multiply","divide"]
uinput = str(input())
lowereduin = uinput.lower()
splited = lowereduin.split(" ")
if lowereduin in exitcond:
break
if splited[0] == operators[0]:
if isinstance(splited[1],int) == True:
if isinstance(splited[2] , int) == True:
result = int(splited[1]) + int(splited[2])
print(result)
else:
print("enter a number")
else:
print("enter a number")
and when I run this script and type add 1 3 its says enter a number and when I only type add its give this error
Traceback (most recent call last):
File "C:\Users\Tyagiji\Documents\Python Projects\TRyinrg differet\experiments.py", line 11, in <module>
if isinstance(splited[1],int) == True:
IndexError: list index out of range
Can someone tell me what's this error and if this doesn't work can you tell me how to use try: method on this script.

You can try the following approach and play with type checking
import operator
while True:
exitcond = ["exit","close","quit"]
operators ={"add": operator.add,"subtract":operator.sub,"multiply": operator.mul,"divide":operator.truediv}
uinput = str(input())
lowereduin = uinput.lower()
splited = lowereduin.split(" ")
if lowereduin in exitcond or (len(splited) !=3):
break
try:
if splited[0] not in operators.keys():
raise ValueError(f"{splited[0]} not in {list(operators.keys())}")
op = operators.get(splited[0])
val = op(
*map(int, splited[1:])
)
print(val)
except (ValueError, ZeroDivisionError) as err:
print(err)
break

Building on Deepak's answer. A dictionary of operator names to functions is a good approach. And you can add to splits until you have enough numbers to proceed.
import operator as op
while True:
exitcond = ["exit","close","quit"]
operators = {"add": op.add,"subtract": op.sub, "multiply": op.mul, "divide": op.truediv}
splits = str(input()).lower().split()
if any(part in exitcond for part in splits):
break
while len(splits) < 3:
splits.append(input('Enter number: '))
try:
print(operators[splits[0]](*map(lambda x: float(x.replace(',','')), splits[1:3])))
except ZeroDivisionError:
print("Can't divide by 0")
except:
print('Expected input: add|subtract|multiply|divide [number1] [number2] -- or -- exit|quit|close')
Things to note, the lambda function removes all commas , as they fail for floats, and then converts the all number strings to floats. So, the answer will always be a float, which opens the can of worms that add 1.1 2.2 won't be exactly 3.3 due to the well documented issues with floating point arithmatic and computers

Related

while loop not terminating on changing test condition [duplicate]

Switching from Unity JS to Python for a bit, and some of the finer points elude me as to why this does not work.
My best guess is that the variable guess is actually a string, so string 5 is not the same as integer 5?
Is this what is happening and either way how does one go about fixing this.
import random
import operator
ops = {
'+':operator.add,
'-':operator.sub
}
def generateQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
op = random.choice(list(ops.keys()))
a = ops.get(op)(x,y)
print("What is {} {} {}?\n".format(x, op, y))
return a
def askQuestion(a):
guess = input("")
if guess == a:
print("Correct!")
else:
print("Wrong, the answer is",a)
askQuestion(generateQuestion())
Yes, you are absolutely right that "5" is distinct from 5. You can convert 5 into a string by using str(5). An alternative would be to convert "5" into an integer by int("5") but that option can fail, so better handle the exception.
So, the change to your program could be e.g. the following:
if guess == str(a):
instead of:
if guess == a:
Another option would be to convert guess into an integer, as explained in the other answer.
EDIT: This only applies to Python versions 2.x:
However, you're using input(), not raw_input(). input() returns an integer if you type an integer (and fails if you type text that isn't a valid Python expression). I tested your program and it asked What is 4 - 2?; I typed 2 and it sait Correct! so I don't see what is your problem.
Have you noticed that if your program asks What is 9 - 4? you can type 9 - 4 and it says Correct!? That's due to you using input(), not raw_input(). Similarly, if you type e.g. c, your program fails with NameError
I would however use raw_input() and then compare the answer to str(correct_answer)
I am assuming you are using python3.
The only problem with your code is that the value you get from input() is a string and not a integer. So you need to convert that.
string_input = input('Question?')
try:
integer_input = int(string_input)
except ValueError:
print('Please enter a valid number')
Now you have the input as a integer and you can compare it to a
Edited Code:
import random
import operator
ops = {
'+':operator.add,
'-':operator.sub
}
def generateQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
op = random.choice(list(ops.keys()))
a = ops.get(op)(x,y)
print("What is {} {} {}?\n".format(x, op, y))
return a
def askQuestion(a):
# you get the user input, it will be a string. eg: "5"
guess = input("")
# now you need to get the integer
# the user can input everything but we cant convert everything to an integer so we use a try/except
try:
integer_input = int(guess)
except ValueError:
# if the user input was "this is a text" it would not be a valid number so the exception part is executed
print('Please enter a valid number')
# if the code in a function comes to a return it will end the function
return
if integer_input == a:
print("Correct!")
else:
print("Wrong, the answer is",a)
askQuestion(generateQuestion())

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()

Exception message not printing when I give a string character

`I'm trying to get this exception to trigger so I can see if python can handle when I input a string instead of an int.
I've tried changing the ValueError statement to a different type of exception such as TypeError instead of Value Error. I've also checked for syntax issues.
try:
u_list.append(userInput)
if userInput % 2 == 0:
list_sum += userInput
except ValueError: #this is supposed to be thrown when I put
# a string character instead of an int. Why is this
#not being invoked
#when I put a str character in?!?!
print("da fuq!?!. That ain't no int!")
I'm trying to get the program to print my last line shown when I input a string character, such as a (k) or something, instead it's throwing an error message.
Here's the full code that someone asked for:
u_list = []
list_sum = 0
for i in range(10):
userInput = int(input("Gimme a number: "))
try:
u_list.append(userInput)
if userInput % 2 == 0:
list_sum += userInput
except ValueError: #this is supposed to be thrown when I put
# a string character instead of an int. Why is this not being invoked
#when I put a str character in?!?!
print("da fuq!?!. That ain't no int!")
print("u_list: {}".format(u_list))
print("The sum of tha even numbers in u_list is: {}.".format(list_sum))
ValueError will be thrown when failing to convert a string to an int. input() (or raw_input() in Python 2) will always return a string, even if that string contains digits, and trying to treat it like an integer will not implicitly convert it for you. Try something like this:
try:
userInput = int(userInput)
except ValueError:
...
else:
# Runs if there's no ValueError
u_list.append(userInput)
...
Add the userInput in the try-except block and check it for ValueError. If its an integer then append it to the list.
Here's the Code:
u_list = []
list_sum = 0
for i in range(10):
try:
userInput = int(input("Gimme a number: "))
except ValueError:
print("da fuq!?!. That ain't no int!")
u_list.append(userInput)
if userInput % 2 == 0:
list_sum += userInput
print("u_list: {}".format(u_list))
print("The sum of tha even numbers in u_list is: {}.".format(list_sum))
I hope it helps!

How do I avoid error while using int()?

I have a question concerning int(). Part of my Python codes looks like this
string = input('Enter your number:')
n = int(string)
print n
So if the input string of int() is not a number, Python will report ValueError and stop running the remaining codes.
I wonder if there is a way to make the program re-ask for a valid string? So that the program won't just stop there.
Thanks!
You can use try except
while True:
try:
string = input('Enter your number:')
n = int(string)
print n
break
except ValueError:
pass
Put the whole thing in an infinite loop. You should catch and ignore ValueErrors but break out of the loop when you get a valid integer.
What you're looking for isTry / Except
How it works:
try:
# Code to "try".
except:
# If there's an error, trap the exception and continue.
continue
For your scenario:
def GetInput():
try:
string = input('Enter your number:')
n = int(string)
print n
except:
# Try to get input again.
GetInput()
n = None
while not isinstance(n, int):
try:
n = int(input('Enter your number:'))
except:
print('NAN')
While the others have mentioned that you can use the following method,
try :
except :
This is another way to do the same thing.
while True :
string = input('Enter your number:')
if string.isdigit() :
n = int(string)
print n
break
else :
print("You have not entered a valid number. Re-enter the number")
You can learn more about
Built-in String Functions from here.

Categories