Как напечатать список строк в несколько строк?Как я могу предотвратить преждевременный выход из моей программы? - PullRequest
0 голосов
/ 25 февраля 2019

Я кодирую проект, который просит пользователей заполнить места для самолета с 10 пассажирами.У меня есть вся эта программа, и она работает так, как я хочу, однако есть две маленькие детали, которые я не могу устранить самостоятельно.Во-первых, самолет может вместить до 10 пассажиров.Я использовал список строк, чтобы иметь возможность вместить всех разных пассажиров.Однако из-за того, как я его настроил, после ввода 10-го пассажира программа выходит из-за того, как я настроил свой код.(Я уверен, что использовать петли было бы проще, но я не знал, как это сделать).Как только вы увидите код ниже, вы поймете, что я имею в виду.После ввода 10-го пассажира я смогу запустить все опции экрана дисплея.

Во-вторых, мне нужно иметь возможность отображать список пассажиров в виде вертикального списка отображения, однако каждый раз, когда я пытаюсь разбить мой список строк, используя \ n, он отображается как каждая буква в новой строке.Вывод должен выглядеть следующим образом: Пассажир № 1 = Имя Пассажир № 2 = Имя и т. Д.

Тем не менее, мой отображается как Пассажир № 1 = Имя Пассажир № 2 = Имя и т. Д.

Буду признателен за любую помощь в устранении этих проблем.

# Seating List

Seating_Chart = ["Seat #1 = Empty", "Seat #2 = Empty", "Seat #3 = Empty", "Seat #4 = Empty", "Seat #5 = Empty", "Seat #6 = Empty", "Seat #7 = Empty", "Seat #8 = Empty", "Seat #9 = Empty", "Seat #10 = Empty"]
Seating_Chart = ' '.join(Seating_Chart)

# Display Menu

Display_Menu = """1. Assign Seat.
2. Print Seat Map.
3. Print Boarding Pass.
-1. Quit"""
print(Display_Menu)
print()

# Gets User Input

User_Input = input("")

# If/Else Statements
while User_Input != "-1":
    if User_Input == "1":
        name = input("Please enter your first name: ")
        Seating_Chart = Seating_Chart.replace("Empty", name, 1)
        Split_List = Seating_Chart.split(" ")
        if "Empty" not in Seating_Chart:
            print("Next flight leaves in 3 hours.")
        print()
    elif User_Input == "2":
        print("***************************************")
        print(Seating_Chart)
        print("***************************************")
        print()
    elif User_Input == "3":
        print("""Type 1 to get Boarding Pass by Seat Number
Type 2 to get Boarding Pass by name""")
        print()
        User_Choice = input("")
        while User_Choice != "1" and User_Choice != "2":
            User_Choice = input("""Type 1 to get Boarding Pass by Seat Number
Type 2 to get Boarding Pass by name""")
            print()
        if User_Choice == "1":
            Seat_Number = int(input("What is the seat number: "))
            if Seat_Number > 10:
                print("Invalid number--no boarding pass found")
            print()
            print("======= Boarding Pass =======")
            print("     Seat #:", Seat_Number)
            print("     Passenger Name:", Split_List[((Seat_Number * 4) - 1)])
            print("=============================")
            print()
        elif User_Choice == "2":
            Passenger_Name = input("Enter passenger name: ")
            if Passenger_Name in Split_List:
                print(Split_List)
                Passenger_Name_Index = Split_List.index(Passenger_Name)
                print(Passenger_Name_Index)
                Passenger_Name_Method_Two = Split_List[Passenger_Name_Index]
                Seat_Index = Passenger_Name_Index - 2
                if Seat_Index >= 0 and Seat_Index <= 3:
                    Printed_Seat = 1
                elif Seat_Index >= 4 and Seat_Index <= 7:
                    Printed_Seat = 2
                elif Seat_Index >= 8 and Seat_Index <= 11:
                    Printed_Seat = 3
                elif Seat_Index >= 12 and Seat_Index <= 15:
                    Printed_Seat = 4
                elif Seat_Index >= 16 and Seat_Index <= 19:
                    Printed_Seat = 5
                elif Seat_Index >= 20 and Seat_Index <= 23:
                    Printed_Seat = 6
                elif Seat_Index >= 24 and Seat_Index <= 27:
                    Printed_Seat = 7
                if Seat_Index >= 28 and Seat_Index <= 31:
                    Printed_Seat = 8
                if Seat_Index >= 32 and Seat_Index <= 35:
                    Printed_Seat = 9
                if Seat_Index >= 36 and Seat_Index <= 39:
                    Printed_Seat = 10
                print()
                print("======= Boarding Pass =======")
                print("     Seat #:", Printed_Seat)
                print("     Passenger Name:", Passenger_Name_Method_Two)
                print("=============================")
                print()
            else:
                print("No passenger with that information could be found.")
    print(Display_Menu)
    User_Input = input("")
if User_Input == "-1":
    print("Have a nice day!")

1 Ответ

0 голосов
/ 25 февраля 2019

Пожалуйста, ознакомьтесь с приведенным ниже решением, вы можете использовать счетчик для подсчета количества пассажиров и добавления проверки.2) Вы можете разделить список и добавить новые строки.

Seating_Chart = ["Seat #1 = Empty", "Seat #2 = Empty", "Seat #3 = Empty", "Seat #4 = Empty", "Seat #5 = Empty", "Seat #6 = Empty", "Seat #7 = Empty", "Seat #8 = Empty", "Seat #9 = Empty", "Seat #10 = Empty"]
Seating_Chart = ' '.join(Seating_Chart)

# Display Menu

Display_Menu = """1. Assign Seat.
2. Print Seat Map.
3. Print Boarding Pass.
-1. Quit"""
print(Display_Menu)
print()

# Gets User Input

User_Input = input("")
count = 0
# If/Else Statements
while User_Input != "-1":
    if User_Input == "1":
        count = count + 1

        if (count <=10):
            name = input("Please enter your first name: ")
            Seating_Chart = Seating_Chart.replace("Empty", name, 1)
            Split_List = Seating_Chart.split(" ")
            if "Empty" not in Seating_Chart:
                print("Next flight leaves in 3 hours.")
            print()
        else:
            print("The plane cannot hold more passengers.")
    elif User_Input == "2":
        print("***************************************")

        for item in Seating_Chart.split("Seat #"):
            if (str(item)!=""):
                print ("Seat #"+str(item))


        print("***************************************")
        print()
    elif User_Input == "3":
        print("""Type 1 to get Boarding Pass by Seat Number
Type 2 to get Boarding Pass by name""")
        print()
        User_Choice = input("")
        while User_Choice != "1" and User_Choice != "2":
            User_Choice = input("""Type 1 to get Boarding Pass by Seat Number
Type 2 to get Boarding Pass by name""")
            print()
        if User_Choice == "1":
            Seat_Number = int(input("What is the seat number: "))
            if Seat_Number > 10:
                print("Invalid number--no boarding pass found")
            print()
            print("======= Boarding Pass =======")
            print("     Seat #:", Seat_Number)
            print("     Passenger Name:", Split_List[((Seat_Number * 4) - 1)])
            print("=============================")
            print()
        elif User_Choice == "2":
            Passenger_Name = input("Enter passenger name: ")
            if Passenger_Name in Split_List:
                print(Split_List)
                Passenger_Name_Index = Split_List.index(Passenger_Name)
                print(Passenger_Name_Index)
                Passenger_Name_Method_Two = Split_List[Passenger_Name_Index]
                Seat_Index = Passenger_Name_Index - 2
                if Seat_Index >= 0 and Seat_Index <= 3:
                    Printed_Seat = 1
                elif Seat_Index >= 4 and Seat_Index <= 7:
                    Printed_Seat = 2
                elif Seat_Index >= 8 and Seat_Index <= 11:
                    Printed_Seat = 3
                elif Seat_Index >= 12 and Seat_Index <= 15:
                    Printed_Seat = 4
                elif Seat_Index >= 16 and Seat_Index <= 19:
                    Printed_Seat = 5
                elif Seat_Index >= 20 and Seat_Index <= 23:
                    Printed_Seat = 6
                elif Seat_Index >= 24 and Seat_Index <= 27:
                    Printed_Seat = 7
                if Seat_Index >= 28 and Seat_Index <= 31:
                    Printed_Seat = 8
                if Seat_Index >= 32 and Seat_Index <= 35:
                    Printed_Seat = 9
                if Seat_Index >= 36 and Seat_Index <= 39:
                    Printed_Seat = 10
                print()
                print("======= Boarding Pass =======")
                print("     Seat #:", Printed_Seat)
                print("     Passenger Name:", Passenger_Name_Method_Two)
                print("=============================")
                print()
            else:
                print("No passenger with that information could be found.")
    print(Display_Menu)
    User_Input = input("")
if User_Input == "-1":
    print("Have a nice day!")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...