Codeman131 Codeman131 - 9 months ago 48
Python Question

Python Sequences Example

Im learning Python and we are on a lesson about sequences, we have been given this example code but I have a few questions about it;

word = input("Word? ")
letter = input("Letter? ")
i = 0
found = False
while not found and i != len(word):
found = word[i] == letter
i = i + 1
if found :
print("letter ", letter, " found in word ", word, " at position ", i -1)
print("letter ", letter, " not found in word ", word)

  1. What happens at the line found = word[i] == letter

  2. Why does the print statement states a letter found at i-1

I am very new to this so if you could ELI5 that would be very helpful.
Thanks in advanced.

Answer Source
  1. If the letter the program is looking at right now (word[i]) is equal to letter, the boolean variable found becomes true, otherwise, the loop will continue until the end of the word or until letter is found.

  2. Because i has been incremented in the while loop above it, regardless of whether letter has been found or not.