Loops

Find number of characters in a string, the hard way

word = 'sound'
length = 0
for char in word:
    length += 1
print(length)
5

Find if a character is present in a string, the hard way

word = 'easy'
ch = 'b'
is_present = False
for char in word:
    if char == ch:
        is_present = True
        break
print(is_present)
False
word = 'easy'
ch = 'e'
index = 0
is_present = False
while index < len(word):
    char = word[index]
    if char == ch:
        is_present = True
        break
    index += 1
print(is_present)
True

Keep accepting input from user until \(0\)​ is entered

When the number of iterations is not known a priori, a while loop is the preferred approach.

x = int(input())
while x != 0:
    x = int(input())

Find the sum the of digits in an integer

n = 12345
dsum = 0
while n != 0:
    dsum += (n % 10)
    n = n // 10
print(dsum)
15
n = 12345
dsum = 0
for char in str(n):
    dsum += int(char)
print(dsum)
15

Reverse a string, the hard way

word = 'rest'
out = '' # empty string
for char in word:
    out = char + out
print(out)
tser
word = 'rest'
out = '' # empty string
for char in reversed(word):
    out = out + char
print(out)
tser
word = 'rest'
out = '' # empty string
n = len(word)
for i in range(n):
    out = out + word[n - 1 - i]
print(out)
tser

This differs from the previous method in its use of negative indexing.

word = 'rest'
out = '' # empty string
n = len(word)
for i in range(n):
    out = out + word[-i - 1]
print(out)
tser
word = 'rest'
n = len(word)
out = '' # empty string
for i in range(n - 1, -1, -1):
    out = out + word[i]
print(out)
tser
word = 'rest'
out = '' # empty string
index = len(word) - 1
while index >= 0:
    out = out + word[index]
    index -= 1
print(out)
tser

Remove all commas from a sentence, the hard way

sentence = 'this, is, not, formatted, properly'
out = '' # empty string
for char in sentence:
    if char != ',':    
        out = out + char
print(out)
this is not formatted properly
sentence = 'this, is, not, formatted, properly'
out = '' # empty string
for char in sentence:
    if char == ',':
        continue
    out = out + char
print(out)
this is not formatted properly
sentence = 'this, is, not, formatted, properly'
out = '' # empty string
index = 0
while index < len(sentence):
    char = sentence[index]
    if char != ',':
        out = out + char
    index += 1
print(out)
this is not formatted properly

Count the number of factors of an integer

n = 10
count = 0
for f in range(1, n + 1):
    if n % f == 0:
        count += 1
print(count)
4
n = 10
count = 0
f = 1
while f <= n:
    if n % f == 0:
        count += 1
    f += 1
print(count)
4

Determine if a number is perfect

A positive integer \(n\) is termed perfect if the sum of all its factors excluding the number itself is equal to \(n\). For example, \(6\) is a perfect number because \(1 + 2 + 3 = 6\). Likewise, \(28\) is a perfect number because \(1 + 2 + 4 + 7 + 14 = 28\).

n = 28
fsum = 0
for f in range(1, n):
    if n % f == 0:
        fsum += f
if fsum == n:
    print(f'{n} is a perfect number')
else:
    print(f'{n} is not a perfect number')
28 is a perfect number
n = 28
fsum = 0
f = 1
while f < n:
    if n % f == 0:
        fsum += f
    f += 1
if fsum == n:
    print(f'{n} is a perfect number')
else:
    print(f'{n} is not a perfect number')
28 is a perfect number

Find all perfect numbers less than or equal to \(1,000\)

for n in range(1, 1_001):
    fsum = 0
    for f in range(1, n):
        if n % f == 0:
            fsum += f
    if fsum == n:
        print(n)
6
28
496
n = 1
while n <= 1_001:
    f, fsum = 1, 0
    while f < n:
        if n % f == 0:
            fsum += f
        f += 1
    if fsum == n:
        print(n)
    n += 1
6
28
496

Determine if \(n\) is prime

We assume that \(n > 1\) in all snippets of code given here.

n = int(input())
count = 0
for f in range(1, n + 1):
    if n % f == 0:
        count += 1
if count == 2:
    print('PRIME')
else:
    print('NOTPRIME')
n = int(input())
# optimistic start
is_prime = True

for f in range(1, n + 1):
    if (n % f == 0) and (f != 1) and (f != n):
        is_prime = False
        break

if is_prime:
    print('PRIME')
else:
    print('NOTPRIME')

Though the following code will not work for \(n = 1\), the question states that \(n > 1\). We have made use of this fact. This code is a slight improvement over method-2.

n = int(input())
# optimistic start
is_prime = True

for f in range(2, n):
    if n % f == 0:
        is_prime = False
        break

if is_prime:
    print('PRIME')
else:
    print('NOTPRIME')

Find all Pythagorean triplets \((x, y, z)\) with \(x < y < z < n\)

The purpose of this how-to is to introduce you to triply nested loops.

n = int(input())

for x in range(1, n):
    for y in range(1, n):
        for z in range(1, n):
            if x < y < z:
                if (x ** 2 + y ** 2 == z ** 2):
                    print(x, y, z)

Since \(x < y < z\), it is sufficient if we have the following ranges for the three loops:

  • \(1 \leqslant x < n\)
  • \(x < y < n\)
  • \(y < z < n\)

This considerably reduces the number of iterations overall.

n = int(input())

for x in range(1, n):
    for y in range(x + 1, n):
        for z in range(y + 1, n):
            if (x ** 2 + y ** 2 == z ** 2):
                print(x, y, z)

There is some more wasteful computation happening. Once we know that \(x^{2} + y^{2} \geqslant n^2\), there is no point in looking for \(z\). Therefore, we have the following code:

n = int(input())

for x in range(1, n):
    for y in range(x + 1, n):
        lhs = x ** 2 + y ** 2
        if (lhs >= n ** 2):
            break
        for z in range(y + 1, n):
            if lhs == z ** 2:
                print(x, y, z)   

Some parts of this code may look awkward. In line-5, we are computing the lhs once for each value of \(y\). This is to avoid computing \(x^{2} + y^{2}\) each time in the innermost loop.