Need some help finishing this function [duplicate] - python

This question already has answers here:
What's the canonical way to check for type in Python?
(15 answers)
Closed 6 years ago.
Pretend there are three float values being passed through this function. The function takes the first two values and subtracts the second from the first. If the result of that subtraction is less than or equal to the value of the parameter tolerance, it returns true. I want to set up another test in there. How do you tell a function to return None if the arguments passed to it are not floats?
def assert_within_tolerance(x_1,x_2,tolerance):
result=abs(x_1-x_2)
if result<=tolerance:
return True
if result>tolerance:
print('\nThe result was greater than the tolerance')
return None

You can ask the type of a variable in python with type or isinstance:
def foo(x,y,z):
if type(x) is not float or type(y) is not float or type(z) is not float:
return None
# normal execution here
pass

You can use "if type(variable) is not float:". For example
def assert_within_tolerance(x_1,x_2,tolerance):
if type(x_1) is not float or type(x_2) is not float or type(tolerance) is not float:
print('\nInputs needs to be float')
return None
result=abs(x_1-x_2)
if result<=tolerance:
return True
if result>tolerance:
print('\nThe result was greater than the tolerance')
return None

Related

problem for a syntax in python, generally the order of statements in the "if" function should not affect the output [duplicate]

This question already has answers here:
Does Python support short-circuiting?
(3 answers)
Closed last year.
hi so i had a doubt in python:
def check(message):
if len(message)==0 or message[0]==message[-1]:
return True
else:
return False
print(check('else'))
print(check('tree'))
print(check(""))
this works.
def check(message):
if message[0]==message[-1] or len(message)==0:
return True
else:
return False
print(check('else'))
print(check('tree'))
print(check(""))
this doesn't. why?
emphasis on the 'if' function in the check function.
It is because or short-circuits: it doesn't evaluate the right argument if there's no need to judging by the value of the left argument.
Eg if a==0 or f() will not execute f() if a is 0 and thus it makes no difference for the result if f() evaluates to True or False.

Python - create separate lists but integers and strings not working [duplicate]

This question already has answers here:
Negative form of isinstance() in Python
(3 answers)
Closed 2 years ago.
Here's the info:
I have a list like this
trylist=[9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','-3.7','Python']
Looking to create three lists - integer, string and float
Integer list will have: 9,0,-5,1,-600,4
Float list will have: 0.7,5.9
String list will have: Europe,-9,English,0,-2,-3.7,Python
Wrote this program. Output was integers and integers marked as string. Not kind of what I want. Tweaked it to do the same with float. Did not work. Looking for a better way to get the desired output. Thanks!
trylist=[9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','Python']
newlistint=[]
newlistonlyint=[]
print(f'Initial list : {trylist}')
for item in trylist:
try:
int_val = int(item)
print(int_val)
except ValueError:
pass
else:
newlistint.append(item) #will print only integers including numbers mentioned as string and digit of float
print(f'newlistint is : {newlistint}')
newlistonlyint.append(int_val)
print(f'newlistonlyint is :{newlistonlyint}')
trylist = [9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','Python']
int_list = [x for x in trylist if type(x)==int]
float_list = [x for x in trylist if type(x)==float]
str_list = [x for x in trylist if type(x)==str]
You can read about list comprehension here
int() tries to convert its argument to an int, raising a ValueError if this can’t be done. While it’s true that any integer argument to int() will not raise a ValueError, non-integer arguments like ‘9’ can be successfully converted to an integer (the integer 9 in this case), therefore not raising a ValueError.
Hence, trying to verify whether something is an integer by calling int() on it and catching ValueErrors just doesn’t work.
You should really be using the isinstance() function. Specifically, item is an int if and only if isinstance(item, int) returns True. Similarly, you can check for strings or floats by replacing int by str or float.

safely comparing two strings in Python [duplicate]

This question already has an answer here:
Python unicode equal comparison failed
(1 answer)
Closed 5 years ago.
So I want to compare two strings, sometimes one of them will be of type "unicode" and sometimes one of them will be of type "str".
This is what I've currently got:
def poll_change(self):
''' Returns a tuple (has_changed, new_element_str) '''
new_element = self.find_element()
old_element = self.read_element_str()
# TODO: handle compare correctly
if type(new_element) is not type(old_element):
changed = False
else:
changed = new_element != old_element
return changed, new_element
what would be the best solution for this?
Right now I am just returning False if the types of the strings are unequal, but I would like to compare them anyways.
I would get an error if I would compare unicode with str for example.
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/difflib.py:433: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
a[besti-1] == b[bestj-1]
I am using Python 2.7
>>> u"a" == "a"
True
>>> "a" == "a"
True
>>> u"a" == u"a"
True
So what is the problem? Or do you mean you want to compare type too?

Is there a string.isnumeric function? [duplicate]

This question already has answers here:
Using isdigit for floats?
(8 answers)
Closed 8 years ago.
I am already using string.letters, string.digits and string.hexdigits to validate some of my User Input Fields. However, I have a need to validate a floating point number but cannot seem to find an equivalent call. No decimal point is acceptable as is one, but two or more should flag an Error! Is there function for this or do I need write my own validation routine?
Thank you...
There is one, but it doesn't work for decimal points. You could easily write what you want, however, by catching the ValueError:
def is_numeric_inc_point(s):
try:
float(s)
except ValueError:
return False
return True
Demo:
>>> is_numeric_inc_point('5')
True
>>> is_numeric_inc_point('4.8')
True
>>> is_numeric_inc_point('6..2')
False

checking string is number or not in python [duplicate]

This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
Closed 9 years ago.
Which of the following is the best way of checking if a string could be represented as number?
a)
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
b)
Import re
check_regexp = re.compile(“^\d*\.?\d*$”)
c)
def isNumber(token):
for char in token:
if not char in string.digits: return false
return True
d)
import re
check_replace = lambda x: x.replace(‘.’,’’,1).isdigit()
All four versions do different things. As the first version is the only one that correctly handles negatives, I would prefer it in almost all cases. Even if the other versions were adjusted to return the same values as the first version, I would prefer the first version for clarity. However, if the input format needs to be more strict than what float accepts, perhaps not allowing inputs like '123e+4', then a correctly-written regex would probably be the simplest solution.
You can this Python code, it will find string is number or float value.
def typeofvalue(text):
try:
int(text)
return 'int'
except ValueError:
pass
try:
float(text)
return 'float'
except ValueError:
pass
return 'str'
typeofvalue("1773171")

Categories

Resources