'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)
else:
    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.



Solution 1:[1]

Welcome to python. To answer your questions:

  1. This statement assigns to found the value of the comparison between word[i] and letter. In other words, found takes the boolean value of the answer to the question:

    "is `word[i]` equal to `letter`?"
    
  2. You use i-1 instead of i because the loop is not prevented from incrementing i even when it was found.

Solution 2:[2]

  1. found = word[i] == letter: As you can see, in an earlier point in your program you set found to False. This type of variable is commonly called a "boolean flag". Inside your for loop, the value of found is set to the boolean expression word[i] == letter, which means in plain English: If the value of word at index i, is equal to the value of the variable letter return true, otherwise return false.

  2. Inside your print statement, when the boolean flag found(see above answer) is true, it will print the index at which the match occurred. As you might have already learned, each character in each string has specific index. eg.

    >>> string = "string"
    >>> string[0] # what is the value of the character at postion zero?
    's'
    >>> string[1] # what is the value of the character at postion one?
    't'
    >>> etc..
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sal
Solution 2 Christian Dean