-1

I try to check if string s contain any alphanumeric characters using the following code:

s = input()

bool1 = False

while bool1 == False:
     for i in list(s):
         bool1 = i.isalnum()
print(bool1)

But it resulted in runtime error.

Why is this happening?

  • I ran your code there is not a runtime error, other than that there is no need for while statement, if there is no alphanumeric character in the string you'll be stuck in a infinite loop, so remove while statement. – Sarthak Kumar Jun 16 '20 at 03:17
  • I used the while loop so that the programming will stop once an alphanumeric character is found. (i.e. to eliminate unnecessary running of codes) – peter825212 Jun 16 '20 at 03:43
  • 1
    That seems illogical, after entering while loop the condition will be checked again after the completion of for loop i.e each character has been checked even it finds the alpha numeric character loop will continue to iterate over whole string and the program will stuck in a infinite loop if there are no alpha numeric character in string then how `boo1` will become true if there are no alpha numeric characters , I would recommend you first understand the basic control flow of loops. See @Babak's answer that's the way to go. – Sarthak Kumar Jun 16 '20 at 03:57
  • also [check this](https://stackoverflow.com/questions/44057069/checking-if-any-character-in-a-string-is-alphanumeric) – Sarthak Kumar Jun 16 '20 at 04:00

2 Answers2

2

I ran it. there was not an error. What is the use of while loop?

s = input()

bool1 = False

for i in s:
    if bool1 == True:
        break
    bool1 = i.isalnum()
print(bool1)
1

Your code is not working when string doesn't contain any alphanumeric characters, because you have then infinitive while loop. You should use only one loop.

s = input()

bool1 = False

for i in s:
    if i.isalnum():
        bool1 = True
        break

print(bool1)
Jsowa
  • 9,104
  • 5
  • 56
  • 60