Exercise
Function To Print Title
Objective
Develop a Python program with a function called 'WriteTitle' that displays a text in uppercase, centered on the screen with extra spaces and lines above and below it. For example, calling WriteTitle('Welcome!') will produce an output like this, centered in an 80-column width:
--------------- W E L C O M E ! ---------------
(The number of hyphens should automatically adjust based on the text length.)
Example Python Exercise
Show Python Code
# Function to display a title in uppercase, centered with extra spaces and lines above and below it
def WriteTitle(text):
# Convert the text to uppercase
text = text.upper()
# Calculate the total width of the screen (80 characters)
screen_width = 80
# Calculate how many spaces are needed on the left and right to center the text
spaces = (screen_width - len(text) - 2) // 2 # The extra 2 accounts for the space on both sides of the text
# Create a line of hyphens based on the text length
line = '-' * (len(text) + 2) # The 2 extra characters account for spaces around the text
# Print a line of hyphens above the text
print(line)
# Print the text centered with spaces on both sides
print(' ' * spaces + text + ' ' * spaces)
# Print a line of hyphens below the text
print(line)
# Main function to demonstrate the WriteTitle function
def main():
# Example title to display
title = "Welcome!"
# Call the WriteTitle function to display the title
WriteTitle(title)
# Run the main function
if __name__ == "__main__":
main()
Output
--------------- WELCOME! ---------------
Share this Python Exercise