'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)
What happens at the line found = word[i] == letter
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:
This statement assigns to
foundthe value of the comparison betweenword[i]andletter. In other words,foundtakes thebooleanvalue of the answer to the question:"is `word[i]` equal to `letter`?"You use
i-1instead ofibecause the loop is not prevented from incrementingieven when it was found.
Solution 2:[2]
found = word[i] == letter: As you can see, in an earlier point in your program you setfoundtoFalse. This type of variable is commonly called a "boolean flag". Inside your for loop, the value offoundis set to the boolean expressionword[i] == letter, which means in plain English: If the value ofwordat indexi, is equal to the value of the variableletterreturn true, otherwise return false.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 |
