How to handle ValueError while if int() is provided non-integer - python

Python reads function input() as string.
Before passing it to my function for division, variables are typecasted into int using int().
If one variable is non-int (eg "a") then how to catch it?
def divideNums(x,y):
try:
divResult = x/y
except ValueError:
print ("Please provide only Integers...")
print (str(x) + " divided by " + str(y) + " equals " + str(divResult))
def main():
firstVal = input("Enter First Number: ")
secondVal = input("Enter Second Number: ")
divideNums (int(firstVal), int(secondVal))
if __name__ == "__main__":
main()
How to handle typecast of firstVal / secondVal ?

You can use isdigit function to check if the input values are integer or not
def main():
firstVal = input("Enter First Number: ")
secondVal = input("Enter Second Number: ")
if firstVal.isdigit() and secondVal.isdigit():
divideNums (int(firstVal), int(secondVal))
else:
print ("Please provide only Integers...")

You are right about using a try/except ValueError block, but in the wrong
place. The try block needs to be around where the variables are converted to
integers. Eg.
def main():
firstVal = input("Enter First Number: ")
secondVal = input("Enter Second Number: ")
try:
firstVal = int(firstVal)
secondVal = int(secondVal)
except ValueError:
# print the error message and return early
print("Please provide only Integers...")
return
divideNums (firstVal, secondVal)

Related

Python while _ValueError

In this program if user enter a str input, the program won't run and user will get an error.
how can I develope my program to tell the user that input is wrong?
Could you help me with this problem please?
summation = 0
while True:
user_input = input("Enter your input \n")
if user_input == "done":
break
else:
summation = summation + float(user_input)
print("End \n", "SUMMATION = ", summation)
"conention.py/while.py"
Enter your input
Hi
Traceback (most recent call last):
File "c:\Users\ASUS\Desktop\python\name conention.py\while.py", line 7,
in <module> summation = summation + float(user_input)
ValueError: could not convert string to float: 'Hi'
PS C:\Users\ASUS\Desktop\python>
You run float("Hi") and this makes problem.
You should use try/except to catch error and do something or skip it.
For example.
summation = 0
while True:
user_input = input("Enter your input \n")
if user_input.lower() == "done":
break
try:
summation = summation + float(user_input)
print("End \n", "SUMMATION = ", summation)
except ValueError:
print('It is not float value:', user_input)

How can I get print except statement printed instead of an error below in try/except syntax in Python

I am new to Python programming. Following is the code written and it works fine when I print any numeric digit and give me the desired result as expected but the problem comes when I enter string (anything other than integer/float) instead of giving me just the except statement, it also gives me an error which I don't want. So, what I want is when a user enter anything other than numeric digits, he should be prompted with a message i.e., "Invalid input. Enter a number please" instead of an error which I am getting after the except print statement in the end. Please help.
hours_string = input("Enter Hours: ")
rate_string = input("Enter Rate: ")
try:
hours_float = float(hours_string)
rate_float = float(rate_string)
except:
print("Invalid input. Enter a number please.")
result = hours_float * rate_float
print("Pay",result)
This is the error I am getting. If I enter string, I should simply get an except statement. That's it. Not any other error. How can I accomplish to get there?
Enter Hours: 9
Enter Rate: entered string by mistake
Invalid input. Enter a number please.
Traceback (most recent call last):
File "<string>", line 9, in <module>
NameError: name 'rate_float' is not defined
For a particular Error you can do a particular Exeption like in the Code below. Also note that each question is in a whileloop that you need to acomplish the task before you get to the next one.
while True:
try:
hours_string = input("Enter Hours: ")
hours_float = float(hours_string)
except ValueError:
print("Invalid input. Enter a number please.")
else:
break
while True:
try:
rate_string = input("Enter Rate: ")
rate_float = float(rate_string)
except ValueError:
print("Invalid input. Enter a number please.")
else:
break
result = hours_float * rate_float
print("Pay",result)
hours_float = None
rate_float = None
while hours_float is None:
hours_string = input("Enter Hours: ")
try:
hours_float = float(hours_string)
except ValueError:
print("Invalid input. Enter a number please.")
while rate_float is None:
rate_string = input("Enter Rate: ")
try:
rate_float = float(rate_string)
except ValueError:
print("Invalid input. Enter a number please.")
result = hours_float * rate_float
print("Pay", result)
In the while loop we repeatedly ask user for input, while they don't enter a valid number, separately for hours and rate.
Valid input changes the initially set None value to something else, which finishes the corresponding loop.
Since this is a expected situation and it can be treated as a test I would recommend instead of trying to execute the operation with wathever input the user provided you could ask the user for the input and while it is not an integer you ask for the input again.
def get_input(name, var_type):
userin = None
while userin is None:
userin = input(f'Input {name}: ')
try:
userin = var_type(userin)
except ValueError:
print(f'{name} must be {str(var_type)}, not {str(type(userin))}')
userin = None
return userin
hours = get_input('hours', int)
rate = get_input('rate', float)
result = hours * rate
print('Pay', result)
The function get_input tries to cast the input input value to the type you want and if it is not as desired it will keep asking until the type matches.

How to make the calculator print a statement if the input is a string rather than integer [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
I am running into a problem, I am trying to make a calculator as my first program!(I am still a very beginner at programming), and i wan't it to print out a statement when someone enters a string rather than an integer , Here is my code:
add = ["add", "+", "plus"]
minus = ["minus", "-", "subtract"]
multiply = ["multiply", "*", "product"]
divide = ["divide", "/",]
quit = ["quit", "q", "leave", "shut down"]
retry = ["retry", "start again", "start", "r",]
leave = False
while True:
service = input("What would you like to do? ")
if service.lower() in add:
x = int(input("First number... "))
y = int(input("Second number... "))
print(x + y)
elif service.lower() in minus:
x = int(input("First number... "))
y = int(input("Second number... "))
print(x - y)
elif service.lower() in divide:
x = int(input("First number... "))
y = int(input("Second number... "))
print(x / y)
elif service.lower() in multiply:
x = int(input("First number... "))
y = int(input("Second number... "))
print(x * y)
elif service != int:
print("You entered a string , not an integer")
elif service.lower() in quit: #if the user types quit , it'll kill the loop
break
else:
print("Invalid command...Do you want to quit or retry? ")
lastOption = input()
if lastOption.lower() in quit: #If the user writes in quit , it'll kill the loop here
break
elif lastOption.lower() not in retry: #if the user inputs gibberish again, it begins a check otherwise it restarts
while True: #A loop begins if the user has entered an unrecognized input
print("Sorry I did not catch that, can you please repeat? ")
lastOption = input()
if lastOption.lower() in quit:
leave = True #sets leave condition to true as you cannot break two loops in one break statement
break
elif lastOption.lower() in retry:
break
if leave == True: #continuing on from the check loop for unrecognized inputs this allows you to break the loops
break
EDIT: Here is the "try" and "except" code added
while True:
service = input("What would you like to do? ")
if service.lower() in add:
try:
x = int(input("First number... "))
y = int(input("Second number... "))
print(x + y)
except ValueError:
print("You did not enter an integer")
You're taking input, and casting it to int. The casting will raise a ValueError exception if it isn't an integer, you can try catching that exception.
try:
x = int(input("First number... "))
y = int(input("Second number... "))
except ValueError:
print("You should enter a number instead.")
Write a try / catch block. If a string is passed rather than an integer, it will throw an exception (a flag used to denote an error, halts execution). Wrap the block in a try statement. Then write a catch statement to do something (probably print) when it's not an integer. Of course, there are many types of exceptions, and in this case, if a string is passed, a ValueError exception will be thrown.
try:
int (input (">> "))
catch ValueError:
print("Error: string not valid. Try again")

Says X must be a value in logarithmic function?

I have the following code:
import math
q = input("Is there a square root in the function? (y,n) ")
if q == "y":
base = input("base? ")
x_value = input("x? ")
print (math.log(math.sqrt(base),x_value))
else:
base_2 = input("base? ")
x_value_2 = input("x? ")
print (math.log(base_2, x_value_2))
When I run the code, it says that the second value in math.log() must be a number. Shouldn't it work if I just use the variable I assigned to it?
input() returns a string. You should convert the user inputs to floating numbers with the float() constructor:
import math
q = input("Is there a square root in the function? (y,n) ")
if q == "y":
base = float(input("base? "))
x_value = float(input("x? "))
print (math.log(math.sqrt(base),x_value))
else:
base_2 = float(input("base? "))
x_value_2 = float(input("x? "))
print (math.log(base_2, x_value_2))

try: statement fails

I have some python code that fails:
import sys
print ("MathCheats Times-Ed by jtl999")
numbermodechoice = raw_input ("Are you using a number with a decimal? yes/no ")
if numbermodechoice == "yes":
try:
numberx1 = float(raw_input('Enter first number: '))
except ValueError:
print ("Oops you typed it wrong")
try:
numberx1 = float(raw_input('Enter first number: '))
except ValueError:
print ("Oops you typed it wrong")
numberx2 = (float)(raw_input('Enter second number: '))
elif numbermodechoice == "no":
print ("Rember only numbers are allowed")
numberx1 = (int)(raw_input('Enter first number: '))
numberx2 = (int)(raw_input('Enter second number: '))
else:
print ("Oops you typed it wrong")
exit()
print ("The answer was")
print numberx1*numberx2
ostype = sys.platform
if ostype == 'win32':
raw_input ("Press enter to exit")
elif ostype == 'win64':
raw_input ("Press enter to exit")
(Full code here)
I want to wrap the float operations with try statements so if a ValueError happens, it gets caught. Here is the output:
File "./Timesed.py", line 23
try:
^
IndentationError: expected an indented block
What is wrong with it and how can I fix this?
Python is whitespace sensitive, with regards to the leading whitespace.
your code probably should be indented like
import sys
from sys import exit
print ("MathCheats Times-Ed by jtl999")
numbermodechoice = raw_input ("Are you using a number with a decimal? yes/no ")
if numbermodechoice == "yes":
try:
numberx1 = float(raw_input('Enter first number: '))
numberx2 = float(raw_input('Enter second number: '))
except ValueError:
print ("Oops you typed it wrong")
exit()
elif numbermodechoice == "no":
print ("Remember only numbers are allowed")
try:
numberx1 = (int)(raw_input('Enter first number: '))
numberx2 = (int)(raw_input('Enter second number: '))
except ValueError:
print ("Oops you typed it wrong")
exit()
else:
print ("Oops you typed it wrong")
exit()
print ("The answer was")
print numberx1*numberx2
ostype = sys.platform
if ostype == 'win32':
raw_input ("Press enter to exit")
elif ostype == 'win64':
raw_input ("Press enter to exit")
In python, the indentation of your code is very important. The error you've shown us points here:
if numbermodechoice == "yes":
try:
numberx1 = float(raw_input('Enter first number: '))
except ValueError:
print ("Oops you typed it wrong")
All code that is part of a block must be indented. By starting a try block, the following line is part of that block and must be indented. To fix it, indent it!
if numbermodechoice == "yes":
try:
numberx1 = float(raw_input('Enter first number: '))
except ValueError:
print ("Oops you typed it wrong")
You had a wrong syntax. It should be except ValueError: and not except: ValueError. Correct it for you in the question too.
You need to indent the second print statement.
Indentation is important in Python. It's how you delimit blocks in that language.
The conversion to float is using an incorrect syntax. That syntax is valid for C/C++/Java, but not in Python. It should be:
numberx1 = float(raw_input('Enter first number: '))
Which will be interpreted like float("2.3"), which is a constructor for the float type being called with a string parameter. And, yes, the syntax is exactly the same for the function call, so you might even think the constructor is a function that returns an object.
import sys
class YesOrNo(object):
NO_VALUES = set(['n', 'no', 'f', 'fa', 'fal', 'fals', 'false', '0'])
YES_VALUES = set(['y', 'ye', 'yes', 't', 'tr', 'tru', 'true', '1'])
def __init__(self, val):
super(YesOrNo,self).__init__()
self.val = str(val).strip().lower()
if self.val in self.__class__.YES_VALUES:
self.val = True
elif val in self.__class__.NO_VALUES:
self.val = False
else:
raise ValueError('unrecognized YesOrNo value "{0}"'.format(self.val))
def __int__(self):
return int(self.val)
def typeGetter(dataType):
try:
inp = raw_input
except NameError:
inp = input
def getType(msg):
while True:
try:
return dataType(inp(msg))
except ValueError:
pass
return getType
getStr = typeGetter(str)
getInt = typeGetter(int)
getFloat = typeGetter(float)
getYesOrNo = typeGetter(YesOrNo)
def main():
print("MathCheats Times-Ed by jtl999")
isFloat = getYesOrNo("Are you using a number with a decimal? (yes/no) ")
get = (getInt, getFloat)[int(isFloat)]
firstNum = get('Enter first number: ')
secondNum = get('Enter second number: ')
print("The answer is {0}".format(firstNum*secondNum))
if __name__=="__main__":
main()
if sys.platform in ('win32','win64'):
getStr('Press enter to exit')

Categories

Resources