So, I've approached an obstacle in a programming exercise. I understand the concept of try except but how can I use a try except handler to only accept a float or decimal and if a whole number or integer is entered, it throws an error message. I know in theory it's not possible but is there a way?
Ideally I want to use a try except block of code as that's the current lesson I am on.
Thanks to all in advance!
How about using .is_integer() on float?
>>> float(5).is_integer()
True
>>> float(5.12).is_integer()
False
>>>
so
if float(x).is_integer():
raise ValueError('Non integers please')
There are good answers here, but so far the answers do not use try/except as requested. To use try except, you need try something that will throw an exception if false and then catch the exception.
try:
x / (x - int(x))
except ZeroDivisionError:
raise Exception("No integers allowed.")
if type(variable) is not float:
raise ValueError('Invalid number provided')
OR
if type(variable) is int:
raise ValueError('Invalid number provided')
OR (to check if whole number):
if abs(variable) - floor(abs(variable)) < 1.0e-9:
raise ValueError('Invalid number provided')
you can check the number against types.
# add or remove types from the list
if type(num) in (float, int, Decimal):
do something
Related
I want to see ValueError 4 times but it is showing once, why the program cutting to search the other double numbers?
def isitDoubleorSingle(value):
if(value%2!=0):
raise ValueError("Number isn't double")
print(value)
list=[10,22,79,43,11,80]
for x in list:
isitDoubleorSingle(x)
This will solve your problem. You have to catch your Error in the except block or your script will stop running at your first raise ValueError()
edit: As #Nin17 said, you shouldn't redefine the built-in list, so renaming the list in my_list(or any name you want) should be better.
def isitDoubleorSingle(value):
try:
if(value%2!=0):
raise ValueError()
except ValueError:
print(f"Number {value} isn't double")
my_list=[10,22,79,43,11,80]
for x in my_list:
isitDoubleorSingle(x)
When you raise an exception, the program is already closed automatically, so it is not possible to display the ValueError more than once
I am required to write a function that takes a simple mathematical formula as a string as an argument. The function should then return the result of that formula. For example, for the input "2 + 3" the function should return 5.
A string is considered a valid formula if it has the format . Note that operator and integer are separated by whitespace.
A valid operator is either +, -, * or /
If a string doesn't consist of three parts (integer operator integer), the function should raise a ValueError with the message "Formula must be of the following format: ."
If the first part or the last part of the input string can't be converted to integers, the function should raise a ValueError with the message "Expected two integers."
If the second part of the string is not one of the valid operators, the function should raise a ValueError with the message "Invalid operator ''. Expected one of these operators: +, -, *, /."
If the second integer is zero and the operator is /, the function should raise a ZeroDivisionError with the message "Division by zero not possible."
So far I've managed to split the string by whitespace and convert the [0] and [2] indexes to integers to be used in solving the respective mathematical equations, and I've also written a try: except: block that successfully catches invalid operators and returns the desired error message. My problem is going on to accommodate the other exceptions as outlined in the conditions, although I've written code that attempts to catch the exceptions and print the relevant error messages, it isn't working and I'm still getting the default internal python error messages. I'm assuming something in my approach is off, maybe the order that the try: except blocks are written in? something with the indenting? I'm new to this so any pointers or advice would be much appreciated.
def formula_from_string(formula):
valid_operators = '+-*/'
chopped=formula.split()
equa=int(chopped[0]),chopped[1],int(chopped[2])
subtraction=equa[0]-equa[2]
addition=equa[0]+equa[2]
division=equa[0]/equa[2]
multiplication=equa[0]*equa[2]
if chopped[1]=='+':
return(addition)
elif chopped[1]=='-':
return(subtraction)
elif chopped[1]=='*':
return(multiplication)
elif chopped[1]=='/':
return(division)
try:
if chopped[1] not in valid_operators:
invalid=chopped[1]
raise ValueError
except ValueError:
print('Value Error:')
return("Invalid operator '"+invalid+"'. Expected one of these operators: +, -, *, /.")
try:
if chopped[0] or chopped[2] != int:
raise ValueError
except ValueError:
print('Value Error:')
return('Expected two integers.')
try:
if equa[1]=='/' and equa[2]==0:
raise ZeroDivisionError
except ZeroDivisionError:
print('ZeroDivisionError:')
return('Division by zero not possible.')
try:
if chopped <=1 or chopped >=2:
raise ValueError
except ValueError:
print('ValueError:')
return('Formula must be of the following format: <integer> <operator> <integer>.')
This code should helps you.
learn about Regex (Regular Expressions)
See Regular expression operations
import re
def formula_from_string(formula):
valid_operators = '+-*/'
pattern = re.compile(r'^(\d+)(?:\s+)?([*/+\-^])(?:\s+)?(\d+)$')
try:
if match := pattern.search(formula):
operator = match.group(2)
if operator not in valid_operators:
raise ValueError(f"Invalid operator {repr(operator)}. Expected one of these operators: +, -, *, /.")
else:
raise ValueError('Formula must be of the following format: <integer> <operator> <integer>.')
return eval(formula) # Safe call
except (ValueError, ZeroDivisionError) as e:
print(e)
# Uncomment to see output
# formula_from_string('3 / 2') # 1.5
# formula_from_string('3 ^ 2') # ValueError Invalid operator
# formula_from_string('a / 2') # ValueError Formula must be...
# formula_from_string('3 / 0') # ZeroDivisionError
SO I have a program where the input is in an int, but when the user enters a str, the program crashes. I want the program to ignore any str that it can't convert to an int. I tried declaring a variable that said type(input). Then, I added an if statement:
if (variable) == str:
print(oops)
Remember I declared the input as an int. So I don't know.
Thank you.
You can use exceptions for this. You get a Value Error when you try to convert a string input to int. By enclosing it in a try clause here, it is telling that if a Value Error arises, you can ignore it. For now I've used the pass statement, but if there's something else you want to do if the input is a string, you can add it there.
try:
x = input()
value = int(x)
print(value)
except ValueError:
pass
You can use try-except to handle the case.
try:
value = int(input())
except ValueError:
print("Input is not an int type")
pass
In python you can call isinstance() on the variable passing the datatype you want to check for-
sent = 'your_string'
num = 24
isinstance(sent, int) # returns False
isinstance(num, int) # returns True
isinstance(sent, str) # returns True
isinstance(num, str) # returns False
Applicable with other data types too!
So a simple-
if not isinstance(str, int):
print('Only integer values accepted')
if my_input.isdigit():
int(my_input)
# your code goes here
else:
print('oops')
exit() # maybe you like to exit
You could do something like
input_number = input("Enter your number")
if type(eval(input_number)) == int:
#Do stuff
else:
print('Sorry that is an invalid input')
I also noticed you said
Remeber I declared the input as an int
Python is not statically typed, so you don't have to declare a variable as a certain data type, and along with that even if you do, their type can still be changed.
You can use str.isnumeric() to check if input is of int type or not. THis is better than using try..except
input_number = input("enter a number: ")
if input_number.isnumeric():
input_number = int(input_number)
# do magic
I want to verify that values in a CSV are integers and report an error if they are not. Being an amateur, I thought I had it figured out if the user entered '8k' or whatever as a value by using this:
try:
int(value)
except ValueError:
print("No Deal, Howie!")
I completely overlooked the possibility that a user can enter 8.8, which is unacceptable as well. Unfortunately, I can't use:
if type(value) == int
because pandas dataframe turns all the ints in my CSV into numpy.float64. What can I do about this?
Here's a pretty safe method that will capture a bunch of different integer types.
import numpy as np
def num_is_int(x):
if isinstance(x, (int, np.integer)):
return True
else:
try:
return x.is_integer()
except AttributeError:
return False
num_is_int(7)
True
num_is_int(7.0)
True
num_is_int(np.int16(7))
True
num_is_int(7.1)
False
num_is_int('7')
False
num_is_int(None)
False
You can use int() like this:
if value == int(value)
To check if the value is an integer you can convert it into a string, use .split() method and search for zeros.
An example:
A=5.000006
print(A)
B=str(A).split(sep='.')
print(B)
print(B[1])
integer=1
for b in B[1]:#B[1] is the decimal part of A
if b!='0':
integer=0
If integer=0, this is not an integer,
If integer=1 this is an integer.
I would use Python's builtin isinstance function. Like this:
if not isinstance(value, int):
print("No Deal, Howie!")
I have a GUI where I ask the user to enter some values. When the user submits the data I do some validation:
first I check if the user has entered a value for each input
then I check if each of the inputted values are integers
Trying not to repeat myself to much I came up with this, but the second part of the validation looks more like a hack. Is there a more pythonic way of rewriting this, short of spelling everything out like in the first part of the validation?
errors = []
# 1) check if values exist
if not self.startInput.GetValue():
errors.append("Please provide a start")
if not self.stopInput.GetValue():
errors.append("Please provide a stop")
if not self.valueInput.GetValue():
errors.append("Please provide a value")
# 2) check if values are integers
try:
self.start = int(self.startInput.GetValue())
self.stop = int(self.stopInput.GetValue())
self.value = int(self.valueInput.GetValue())
except ValueError as err:
tb = traceback.format_exc()
func = re.search('self\.(.*) =', tb).groups()[0]
errors.append("Value for {0} needs to be an integer.".format(func))
if errors:
raise RuntimeError('\n'.join(errors))
Since you're checking for integers, and not floats, you can simply do:
if self.start.GetValue().strip().isdigit():
pass
isdigit() returns False for both cases where the input is an empty string, and when the input contains non-digits.
If you want to send specific errors for incorrect assignment:
startValue = self.start.GetValue().strip()
if not startValue:
errors.append("Please provide a start.")
if not startValue.isdigit():
errors.append("Value of start must be an integer.")
If you have these inputs in a dictionary called inputs you can do:
errors = []
for inputname, inputval in self.inputs.items():
if not inputval:
errors.append("Please provide a {}".format(inputname))
try:
setattr(self, inputname, int(inputval.GetValue()))
except:
errors.append("Value for {0} needs to be an integer.".format(inputname))
if errors:
raise RuntimeError('\n'.join(errors))
I think the try: ... except is perfectly Pythonic. I would have uses an helper function instead of searching through an error message get_int_of_name(name, value, error) which return an int and update error if needed:
def get_int_of_name(name, value, error):
try:
res = int(value)
except ValueError:
error.append("...")
return 0
else:
return res