The exercises in the lesson follow a few patterns. We review them with an example function for each.
Functions on texts
def count_spaces(text):
return text.count(" ")
def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == text[::-1]
print(count_spaces("a b c")) # 2
print(reverse("hello")) # olleh
print(is_palindrome("ana")) # True
They are used in Function count spaces of a text, Function to show an inverted string and Function to check palindrome.
Replacing a letter
Since strings are immutable, to change a letter you build a new string with slices:
def change_letter(text, position, new):
return text[:position] + new + text[position + 1:]
print(change_letter("cat", 1, "u")) # cut
It is the idea of Replace character in a string.
Checking the kind of content
def is_alphabetic(text):
for c in text.lower():
if not ("a" <= c <= "z"):
return False
return True
print(is_alphabetic("Hello")) # True
print(is_alphabetic("Hello1")) # False
Notice the pattern: you go through the text, and as soon as you find something that does not comply, you do return False without waiting for the end. Only if the loop finishes without problems do you return True. It is the solution of Check alphabetical string.
try / except: checking whether a text is a number
Converting a text that is not a number raises ValueError. With try/except the error is caught and you answer without the program crashing:
def is_number(text):
try:
float(text)
return True
except ValueError:
return False
print(is_number("3.5")) # True
print(is_number("abc")) # False
It is used in Check numeric string. Python tries the try block; if it fails with that error, it runs the except.
Functions with lists
def add_list(numbers):
total = 0
for n in numbers:
total += n
return total
def largest(numbers):
return max(numbers)
print(add_list([1, 2, 3])) # 6
print(largest([4.5, 9.1, 2.0])) # 9.1
They are used in Function to add an array of integers and Search the greatest value in an array. A function receives the list as one more parameter.
Summing the digits of a number
def sum_digits(number):
total = 0
for digit in number: # number arrives as text: "472"
total += int(digit)
return total
print(sum_digits("472")) # 13
It is the idea of Function to sum the digits of a number.
Functions that format
def title(text):
print("-" * 20)
print(text.upper().center(20))
print("-" * 20)
title("hello")
center(n) pads with spaces to center the text in n characters. It is what is used in Function to write text with title format and Function to write format text.