if(isr.isalpha() or (isr.isnumeric() and isr.isalpha())) : print("You can't use a letter here.")
else :
isr = math.sqrt(float(isr))
print(isr)
So i wanted it to detect if the isr
string gonna have a letter for example: "a" or a letter with a number "a8". I tried with the and
and or
logical operators, but with the actual code it just gives me "could not convert string to float: 'xxx'" like it kinda just skips the whole if
line. When I put the "," instead of and
then I put there a "a3" and it says the right thing it should say, but when i put there a normal number that You can actually use in the square rooting it says the thing that it shouldn't.
For and
= "a3" the visual studio gonna say "could not convert string to float: 'a3'. For and
= "a" it gonna print the right thing "You can't use a letter here.". For and
= "4" it gonna print "2.0" as it should.
The one with the ,
instead of and
.
if(isr.isalpha() or (isr.isnumeric(), isr.isalpha())) : print("You can't use a letter here.")
else :
isr = math.sqrt(float(isr))
print(isr)
For ,
= "a3" It prints out the right thing "You can't use a letter here." For ,
= "a" It prints out the right thing "You can't use a letter here." For ,
= "4" Should print the 2 but it prints out "You can't use a letter here."
Anyone can help me with it?
The isnumeric
and isalpha
functions tell you if the entire string is numeric or alphabetic:
>>> "aa".isalpha()
True
>>> "aa3".isalpha()
False
Rather than trying to stack a bunch of conditions to tell you if a string is a valid float
that you can take the square root of, just use try/except
:
>>> isr = "a3"
>>> try:
... print(math.sqrt(float(isr)))
... except ValueError:
... print(f"{isr} isn't a valid number.")
...
a3 isn't a valid number.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.