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?

4

1 回答 1

1

isnumericandisalpha函数告诉您整个字符串是数字还是字母:

>>> "aa".isalpha()
True
>>> "aa3".isalpha()
False

而不是试图堆叠一堆条件来告诉你一个字符串是否是一个float你可以取平方根的有效字符串,只需使用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.
于 2021-12-10T16:50:19.310 回答