Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

4. [3 points] All functions for this part should be in a file called characters.

ID: 3599569 • Letter: 4

Question

4. [3 points] All functions for this part should be in a file called characters.py For this problem you will convert letters between upper and lower case. This is easy to do, because in the ASCII encoding, the code for each lower-case letter is obtained by adding 32 to the code for the corresponding upper-case letter. But you can't do arithmetic with characters in Python. Instead, you must get the character's code using the ord function, do the arithmetic, and convert the result back to a character using the chr function. Examples >>> ord( 'A' ) 65 >>> ord( 'a') 97 >>> ord('Z') 90 >>> ord( 'z') 122 >>> chr (65) >>> chr (97) >>>chr(90) >>> chr (122)

Explanation / Answer

def to_upper(c):
if ord(c) >= 97 and ord(c) <= 122:
return chr(ord('A') + (ord(c) - ord('a')))
return c

def to_lower(c):
if ord(c) >= 65 and ord(c) <= 90:
return chr(ord('a') + (ord(c) - ord('A')))
return c

def capitalize(s):
result = ""
words = s.split()
for word in words:
result += to_upper(word[0])
for i in range(1, len(word)):
result += to_lower(word[i])
result += " "
return result

# copy pastable link: https://paste.ee/p/JqINN

'''

Sample run

print(to_upper('a'))
print(to_upper('m'))
print(to_upper('M'))
print(to_upper('*'))

print(to_lower('A'))
print(to_lower('M'))
print(to_lower('m'))
print(to_lower('*'))

print(capitalize("the quick brown fox"))
print(capitalize("PYTHON IS A SNAKE"))
print(capitalize("abC"))

output

A
M
M
*
a
m
m
*
The Quick Brown Fox
Python Is A Snake
Abc
'''

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote