Ejercicio
Valor De Salida De La Función Principal
Objectivo
Desarrollar un programa Python que solicite al usuario que proporcione un título mediante la línea de comandos (utilizando la función WriteTitle definida previamente). Si no se proporciona ninguna entrada, el programa debe mostrar un mensaje de error y devolver un código de salida de 1 al sistema operativo.
Ejemplo de ejercicio de Python
Mostrar código Python
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 ---------------
Código de ejemplo copiado
Comparte este ejercicio de Python