How do I check for error in Python to stop it from looping?

88 views Asked by At

I am a beginner Python learner. This keeps looping and I couldn't seem to find the error in this to get it corrected. Any help would be appreciated. Thanks.

sentence = "that car was really fast"
i = 1
while i > 0:
    for char in sentence:
        if char == "t":
            print("found a 't' in sentence")
        else:
            print("maybe the next character?")
3

There are 3 answers

1
SaGaR On

I think what you want is to print 'found t in sentence' if the char is a 't' and else print 'maybe the next character?'. You should not use the while loop in this program only for loop will suffice what you are trying to do.

1
Samwise On

If you only want to determine whether the letter "t" is in the sentence, this can be done very simply with Python's in operator:

if 't' in sentence:
    print("found a 't' in sentence")

If you want to iterate over every letter in the sentence and print a line of output for each one depending on what it is, you only need a single for loop:

for char in sentence:
    if char == "t":
        print("found a 't' in sentence")
    else:
        print("maybe the next character?")

If you want to stop this loop as soon as you find a "t", the way to do that is break:

for char in sentence:
    if char == "t":
        print("found a 't' in sentence")
        break
    print("maybe the next character?")
1
Daniel On

You have set i = 1 but in the while loop there is nothing that changes the value of i to eventually become 0 and break out of the loop. Also, you don't even need the while loop because you are just iterating over the characters in the string sentence, so just do this:

sentence = "that car was really fast"

for char in sentence:
    if char == "t":
        print("found a 't' in sentence")
    else:
        print("maybe the next character?")