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
= "Dr. Kessner"
s print("s: ", s)
print("find_E(s):", find_E(s));
# Count the number of 'e' characters in s.
def count_E(s):
= 0
total for c in s:
if c == 'e':
+= 1
total return total
print("count_E(s):", count_E(s));
# Calculate sum of integers from 1 to n.
def sum(n):
= 0
total for i in range(n+1):
+= i
total 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