Exercise
Underline Text Function
Objective
Develop a Python function that can center the text on the screen (assuming a screen width of 80 characters) and then underline it with hyphens:
write_underlined("Hello!")
Example Python Exercise
Show Python Code
# Define the function write_underlined which accepts text as a parameter
def write_underlined(text):
screen_width = 80 # Assume the width of the screen is 80 characters
# Calculate the padding needed on the left side to center the text
padding_left = (screen_width - len(text)) // 2 # Calculate the number of spaces to center the text
# Print the centered text
print(' ' * padding_left + text) # Print the text with leading spaces for centering
# Print the underline below the text. Only underline the letters, not the spaces.
underline = '-' * len(text) # Create the underline with the same length as the text
print(' ' * padding_left + underline) # Print the underline with the same length as the text
# Main code to call write_underlined with the text "Hello!"
write_underlined("Hello!") # Call the function with the text "Hello!"
Output
Hello!
------
Share this Python Exercise