Exercise
Main Function Output Value
Objective
Develop a Python program that prompts the user to provide a title via the command line (using the previously defined WriteTitle function). If no input is given, the program should display an error message and return an exit code of 1 to the operating system.
Example Python Exercise
Show Python Code
import sys # Import the sys module to handle system exit codes
# 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 prompt the user for a title and display it
def main():
# Prompt the user for a title
title = input("Please enter a title: ").strip() # .strip() is used to remove leading and trailing spaces
# Check if the title is empty
if not title:
# Print an error message if no title is provided
print("Error: No title provided.")
# Exit the program with an exit code of 1 to indicate an error
sys.exit(1)
# Call the WriteTitle function to display the title if valid input is provided
WriteTitle(title)
# Run the main function if the script is executed directly
if __name__ == "__main__":
main()
Output
Please enter a title: Hello World
--------------- HELLO WORLD ---------------
Share this Python Exercise