Practical Coding in Python

Learn to write and validate your own code

Darren Kessner, PhD

(revised September 1, 2025)

Previous: Hello loops

Hello algorithms

#
# hello_algorithms.py
#


# In each of these examples, we use a loop to perform a
# calculation.


# Find the first 'e' character in s.

def find_E(s):
    for i in range(len(s)):
        if s[i] == 'e':
            return i

s = "Dr. Kessner"
print("s: ", s)

print("find_E(s):", find_E(s));


# Count the number of 'e' characters in s.

def count_E(s):
    total = 0
    for c in s:
        if c == 'e':
            total += 1
    return total


print("count_E(s):", count_E(s));


# Calculate sum of integers from 1 to n.

def sum(n):
    total = 0
    for i in range(n+1):
        total += i
    return total


print()
print("sum(3):", sum(3))
print("sum(4):", sum(4))
print("sum(5):", sum(5))

Output:

s:  Dr. Kessner
find_E(s): 5
count_E(s): 2

sum(3): 6
sum(4): 10
sum(5): 15

Next: