0
isr = input()
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 orlogical 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.

isr = input()
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?

nonDucor
  • 2,057
  • 12
  • 17
Blogames
  • 3
  • 2
  • 3
    The `isnumeric()` method returns `True` if **all** the characters are numeric. The `isalpha()` method returns `True` if **all** the characters are alphabet letters (a-z). So, it's impossible for `(isr.isnumeric() and isr.isalpha())` to be `True`. The part with `isr.isalpha() or (isr.isnumeric(), isr.isalpha())` also makes no sense; the part to the right of the `or` will always be evaluated as `True` because it's a tuple of two values, and the truth value of a tuple with items in it is always `True`. – Random Davis Dec 10 '21 at 16:48

1 Answers1

1

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.
Samwise
  • 68,105
  • 3
  • 30
  • 44