1
resposta

Código não está funcionando como deveria

Oii, meu código não está funcionando como deveria e já bati a cabeça mas não consigo entender. Alguém pode ajudar por favor?

import os

restaurants = [{'name': 'Praça', 'category': 'Japonesa', 'active': False},
               {'name': 'Supreme Pizza', 'category': 'Pizza', 'active': True},
               {'name': 'Cantina', 'category': 'Italian', 'active': False}]

def show_program_name():
    print ("""
Flavour Express
""")

def show_options():
    print('1. Register Restaurant')
    print('2. List Restaurant')
    print('3. Change Restaurant Status')
    print('4. Log Out\n')

def end_app():
    show_subtitle('Goodbye')

def return_home():
    input('\nSelect any key to return to main menu ')
    main()

def invalid_option():
    print('Invalid Option\n')
    return_home()

def show_subtitle(text):
    os.system('cls')
    line = '*' * (len(text))
    print (line)
    print(text)
    print(line)
    print()

def register_new_restaurant():
    show_subtitle('Registering Your Restaurant')
    restaurant_name = input('Type the name of the Restaurant you need to register: ')
    category = input(f'Type the name of the Category of Restaurant {restaurant_name}: ')
    restaurant_data = {'name': restaurant_name, 'category': category, 'active':False}
    restaurants.append(restaurant_data)
    print(f'The Restaurant {restaurant_name} was succesfully registered.')

    return_home()

def list_restaurants():
    show_subtitle('Listing the Restaurants')

    print(f'{'Restaurant name'.ljust(22)}' | {'Category'.ljust(20)} | 'Status' )
    for restaurant in restaurants:
        name_restaurant = restaurant ['name']
        category = restaurant['category']
        active = 'activated' if restaurant['active'] else 'deactivated'
        print(f'.{name_restaurant.ljust(20)} | {category.ljust(20)} | {active}')

    return_home()

def alternate_restaurant_status():
    show_subtitle('Changing restaurant Status')
    restaurant_name = input('Type the name of the restaurant you would like to change the status: ')
    found_restaurant = False

    for restaurant in restaurants:
        if restaurant_name == restaurant['name']:
            found_restaurant = True
            restaurant['active'] = not restaurant ['active']
            message = f'The restaurant {restaurant_name} was successfully activated.' if restaurant['active'] else f'The restaurant has been successfully deactivated.'
            print(message)

        if not found_restaurant:
            print('Restaurant was not found')

def choose_option ():
    try:
        chosen_number = int(input('Choose an Option: '))
        
        if chosen_number == 1:
            register_new_restaurant()
        elif chosen_number == 2:
            list_restaurants()
        elif chosen_number == 3:
            alternate_restaurant_status()
        elif chosen_number == 4:
            end_app()
        else:
            invalid_option()
    except:
        invalid_option()

def main():
    os.system('cls')
    show_program_name()
    show_options()
    choose_option()

if __name__=='__main__':
    main()
1 resposta

Olá, Amanda.

Tudo bem?

Vamos dar uma olhada no seu código. Notei que há alguns pontos que podem ser ajustados para garantir que ele funcione corretamente. Aqui estão algumas sugestões:

  1. Indentação e Formatação:

    • Certifique-se de que a indentação está correta, pois isso é crucial em Python.
    • Há um problema na função list_restaurants onde a formatação da string está incorreta.
  2. Correção na Função list_restaurants:

    • A linha que imprime os cabeçalhos está com a formatação errada. Deve ser corrigida para:
      print(f"{'Restaurant name'.ljust(22)} | {'Category'.ljust(20)} | Status")
      
  3. Função alternate_restaurant_status:

    • A mensagem "Restaurant was not found" está dentro do loop, então ela será impressa várias vezes se o restaurante não for encontrado. Vamos movê-la para fora do loop.

Aqui está o código ajustado:

import os

restaurants = [{'name': 'Praça', 'category': 'Japonesa', 'active': False},
               {'name': 'Supreme Pizza', 'category': 'Pizza', 'active': True},
               {'name': 'Cantina', 'category': 'Italian', 'active': False}]

def show_program_name():
    print ("""
Flavour Express
""")

def show_options():
    print('1. Register Restaurant')
    print('2. List Restaurant')
    print('3. Change Restaurant Status')
    print('4. Log Out\n')

def end_app():
    show_subtitle('Goodbye')

def return_home():
    input('\nSelect any key to return to main menu ')
    main()

def invalid_option():
    print('Invalid Option\n')
    return_home()

def show_subtitle(text):
    os.system('cls')
    line = '*' * (len(text))
    print (line)
    print(text)
    print(line)
    print()

def register_new_restaurant():
    show_subtitle('Registering Your Restaurant')
    restaurant_name = input('Type the name of the Restaurant you need to register: ')
    category = input(f'Type the name of the Category of Restaurant {restaurant_name}: ')
    restaurant_data = {'name': restaurant_name, 'category': category, 'active':False}
    restaurants.append(restaurant_data)
    print(f'The Restaurant {restaurant_name} was succesfully registered.')

    return_home()

def list_restaurants():
    show_subtitle('Listing the Restaurants')

    print(f"{'Restaurant name'.ljust(22)} | {'Category'.ljust(20)} | Status")
    for restaurant in restaurants:
        name_restaurant = restaurant ['name']
        category = restaurant['category']
        active = 'activated' if restaurant['active'] else 'deactivated'
        print(f"{name_restaurant.ljust(20)} | {category.ljust(20)} | {active}")

    return_home()

def alternate_restaurant_status():
    show_subtitle('Changing restaurant Status')
    restaurant_name = input('Type the name of the restaurant you would like to change the status: ')
    found_restaurant = False

    for restaurant in restaurants:
        if restaurant_name == restaurant['name']:
            found_restaurant = True
            restaurant['active'] = not restaurant ['active']
            message = f'The restaurant {restaurant_name} was successfully activated.' if restaurant['active'] else f'The restaurant has been successfully deactivated.'
            print(message)
            break

    if not found_restaurant:
        print('Restaurant was not found')

def choose_option ():
    try:
        chosen_number = int(input('Choose an Option: '))
        
        if chosen_number == 1:
            register_new_restaurant()
        elif chosen_number == 2:
            list_restaurants()
        elif chosen_number == 3:
            alternate_restaurant_status()
        elif chosen_number == 4:
            end_app()
        else:
            invalid_option()
    except:
        invalid_option()

def main():
    os.system('cls')
    show_program_name()
    show_options()
    choose_option()

if __name__=='__main__':
    main()

Veja se faz sentido, e testa novamente. Espero ter ajudado. Qualquer dúvida manda aqui. Bons estudos!