Oct-05-2023, 08:48 PM
(This post was last modified: Oct-05-2023, 08:49 PM by deanhystad.)
This logic is wrong:
I do not know how r could be assigned the input string, Maybe some bizarre convenience feature? If you fix your logic the program will work as expected.
if x.isalnum(): if x.isalpha(): r = "alphabetical" if x.isnumeric(): r = "numeric"A str can be alphanumeric and not be numeric or alphabetical.
def test(x): print("isalnum", x.isalnum()) print("isalpha", x.isalpha()) print("isnumeric", x.isnumeric()) print() test("a") test("2") test("a2")
Output:isalnum True
isalpha True
isnumeric False
isalnum True
isalpha False
isnumeric True
isalnum True
isalpha False
isnumeric False
In your code, entering "a2" results in nothing assigned to r. In regular python you would get a name error.x = "a1" if x.isalnum(): if x.isalpha(): r = "alphabetical" if x.isnumeric(): r = "numeric" elif x.isspace(): r = "space-based" elif x.isascii(): r = "ASCII text" else: r = "a mystery" print("x is " + r)
Error:Traceback (most recent call last):
File "...", line 14, in <module>
print("x is " + r)
NameError: name 'r' is not defined
In the notebook, it just uses the last value assigned to r. Sort of like this :for x in ("a", "a1", "1", "a1", " ", "a1"): if x.isalnum(): if x.isalpha(): r = "alphabetical" if x.isnumeric(): r = "numeric" elif x.isspace(): r = "space-based" elif x.isascii(): r = "ASCII text" else: r = "a mystery" print(x, "is", r)
Output:a is alphabetical
a1 is alphabetical
1 is numeric
a1 is numeric
is space-based
a1 is space-based
"a1" is pretty versatile.I do not know how r could be assigned the input string, Maybe some bizarre convenience feature? If you fix your logic the program will work as expected.