Searching & Checking
These programs answer a question rather than produce a value: is it a palindrome, is it there, is it all digits, where is it. Two habits carry all six — stop as soon as the answer is settled, and be careful about what “not found” looks like when the loop simply runs out.
1Program 1 — is the word a palindrome?
A palindrome reads the same backwards: madam, Malayalam, level. Ask for a word and say whether it is one, ignoring capitals.
# is the word a palindrome? built by reversing it first
word = input('Enter a word: ')
word = word.lower()
backwards = ''
for ch in word:
backwards = ch + backwards
if backwards == word:
print(word, 'is a palindrome')
else:
print(word, 'is not a palindrome')Enter a word: Malayalam malayalam is a palindrome
Enter a word: Python python is not a palindrome
word = word.lower()Before anything else, so both the reversal and the comparison work on the same lower-case version. Without it 'Malayalam' reverses to 'malayalaM' and the program says no — a right answer to the wrong question.
backwards = ch + backwardsThe new character goes in FRONT of everything collected so far. Written the other way round, backwards + ch, it rebuilds the word as it was and every word is declared a palindrome.
if backwards == word:At the margin, after the loop — the question can only be answered once the whole reversal exists.
And the one-line version, using a slice with a step of −1:
# the same question, answered with a slice
word = input('Enter a word: ')
word = word.lower()
if word == word[::-1]:
print(word, 'is a palindrome')
else:
print(word, 'is not a palindrome')Enter a word: Malayalam malayalam is a palindrome
word[::-1] is what you would write in real code. “Using a loop” in a question means the first version, and the loop is the one that still works when the comparison gets fussier — ignoring spaces in “never odd or even”, for instance.2Program 2 — is the character in the word?
Say whether a character appears anywhere in a word — stopping as soon as it does, and saying so when it does not.
# is the character anywhere in the word? stop as soon as it turns up
word = 'lambdalab'
wanted = 'd'
for ch in word:
if ch == wanted:
print(wanted, 'is in the word')
break
else:
print(wanted, 'is not in the word')d is in the word
else belongs to the for, not to the if. Look at the column it starts in. A loop's else runs only when the loop finished without hitting a break — which is exactly what “we looked at every character and never found it” means. Without it, a missing character produces no output at all.Python writes this in one word — if wanted in word: — and that is what real code says. The loop is the version an exam asks for, and it is the one that generalises: in can answer is it there, but not where, and not how many.
3Program 3 — every position a character appears at
Report all the positions at which a character occurs, not just the first.
# every position a character appears at
word = 'mississippi'
wanted = 's'
for i in range(len(word)):
if word[i] == wanted:
print(wanted, 'at position', i)s at position 2 s at position 3 s at position 5 s at position 6
The index form, because the answer is the position. And no break, because the question asks for all of them — this is the one search on the page that must run to the end. word.find('s') would give 2 and stop; nothing built in gives you the list.
4Program 4 — the first character that appears twice
Find the first character of a word that occurs again later in it. In programming that is r.
# the first character that appears twice
word = 'programming'
found = ''
for i in range(len(word)):
for j in range(i + 1, len(word)):
if word[i] == word[j]:
found = word[i]
break
if found != '':
break
if found == '':
print('No character repeats')
else:
print('The first repeated character is', found)The first repeated character is r
for j in range(i + 1, len(word)):The inner loop starts at i + 1 — everything AFTER the character being tested. Starting at 0 would compare each character with itself and declare every word repeated at position 0.
breakThis one leaves the inner loop only. break never leaves two loops, which is why there is a second one below.
if found != '':The outer loop's own way out. A flag variable is doing the work a single break cannot: it carries the news from the inner loop up to the outer one.
5Program 5 — is the whole string made of digits?
Check whether everything the user typed is a digit — the check a program would do before trusting int() with it.
# does the string hold nothing but digits? checked the long way
value = input('Enter a value: ')
all_digits = True
for ch in value:
if not ch.isdigit():
all_digits = False
if all_digits:
print('That is a number')
else:
print('That has something other than digits in it')Enter a value: 45210 That is a number
Enter a value: 45 210 That has something other than digits in it
True and look for a reason to say no. “All of them” questions work this way round: assume yes, and one counter-example is enough to settle it for ever. Note that all_digits is never set back to True — once a non-digit has been seen, nothing later can undo it.Adding a break after all_digits = False would make it faster and change no answer — there is nothing left to learn once one non-digit has turned up. Python's own value.isdigit() answers the whole question in one call.
6Recap
A search that has found what it wants should break. A search for every occurrence must not.
It runs only when the loop was never broken. Lined up with the for, not with the if — the column is the only thing that says so.
Assume yes, set the flag to False on the first counter-example, and never set it back.
backwards = ch + backwards. The other order rebuilds the word and calls everything a palindrome.
- 1
Check whether a sentence is a palindrome, ignoring spaces.
Hint · Build a spaces-free copy first, then reverse that. Two loops, or one loop and a slice.
- 2
Report the position of the last occurrence of a character.
Hint · No
break— keep overwriting a variable and whatever survives is the last one. - 3
Say whether two words are anagrams of each other.
Hint ·
sorted(word)gives a list of the letters in order; two anagrams sort to the same list. - 4
Check whether a word contains every vowel at least once.
Hint · Loop over
'aeiou', not over the word, and useinon each. - 5
Find the first character that does not repeat anywhere in the word.
Hint · Program 4 turned round: for each character, count its occurrences, and stop at the first with a count of 1.
In backwards = ch + backwards, what happens if the two are swapped to backwards + ch?
A search loop has a break in its if and an else on the for. When does the else run?
Why does the inner loop of the first-repeat program start at i + 1?