列表有问题吗?错误检查不起作用 [英] Issues with lists? Error checking not working

查看:56
本文介绍了列表有问题吗?错误检查不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对python来说还比较陌生,我才刚刚开始学习如何使用类.这是我制作的第一个程序,试图将它们集成在一起,但是我遇到了一个似乎无法解决的小问题,我认为它与列表有关.代码如下: (主题是让用户选择要购买的座椅类型.)

I am relatively new to python, and I just started learning how to use classes. This is the first program I've made where I've tried to integrate them, but I'm coming up with a small issue I can't seem to fix, and I think it has to do with lists. The code is as follows: (The topic is getting the user to choose what type of seat to purchase).

class SeatBooking:
    def __init__(self, seat):
        self.seat = seat
        possible_types = []
        possible_types.extend(["Low_Economy", "Standard_Economy", "High_Economy",
                        "Business", "First", "Residence"])
        possible_types = " ".join(possible_types)
        while True:
            if self.seat not in possible_types:
                print("Sorry, but this is not a valid answer. Please try again!")
                self.seat = str(input("What type of ticket would you like? The possible types are: {} "
                            .format(possible_types)))
            else:
                print("You have chosen to book a {} ticket.".format(self.seat))
                confirmation = str(input("Please confirm with 'Yes' or 'No': ")).lower()
                if confirmation == "yes":
                    print("Excellent decision! Ready to continue")
                    print("=" * 170)
                    break
                elif confirmation == "no":
                    self.seat = str(input("What type of ticket would you like? The possible types are: {} "
                                .format(possible_types)))
                else:
                    print("That doesn't seem to be a valid answer.")

这是主文件(用于执行我将要创建的不同类):

Here is the main file (to execute the different classes I'll make):

import type_seat
# Choose the seat to book
print("=" * 170)
print("Welcome to Etihad! This program can help you organize your       flight, payments and usage of miles!")
possible_types = []
possible_types.extend(["Low_Economy", "Standard_Economy", "High_Economy",
                   "Business", "First", "Residence"])
possible_types = " ".join(possible_types)
seat_type = str(input("What type of ticket would you like? The possible     types are: {}. "
                      .format(possible_types)))

type_seat.SeatBooking(seat_type)

我的问题是,我似乎能够输入某些字母,即使它们不是可用座位之一,也不会将它们视为错误.例如,当我输入字母"h"或"s"时,我的代码检查部分将不响应它,但是当我输入字母"b"或诸如"try"之类的随机单词时,它会响应.不过,它似乎并不是完全随机的,并且似乎只发生在可能性列表[]列表中的字母或前3个项目"的一部分中.但是,我尚未对此进行全面测试.这就是为什么我认为它与列表有关,所以如果有人知道是什么原因造成的,那么如果他们能帮助我解决这个问题,或者将来帮助我避免再次出现此错误,我将不胜感激!

The problem I have is that I seem to be able to enter certain letters and it doesn't count them as an error even though they're not one of the available seats. For example, when I enter the letters "h" or "s", my error checking part of the code doesn't respond to it, but when I enter the letter "b" or random words like "try" it does. It doesn't seem to be completely random though, and it seems to only happen with letters or parts of the first 3 'items' in the possible_types[] list. However, I haven't tested this fully. This is why I thought it had something to do with lists, so if anyone knows what's causing this, I'd really appreciate it if they could help me resolve this and perhaps help me from repeating this mistake in the future!

注意,对于列表,我正在使用.join,但是我也尝试了str().

Note, for the lists I am using .join, but I also tried str().

推荐答案

您没有拥有列表,您正在针对一个长字符串测试字符:

You don't have a list, you are testing characters against one long string:

possible_types = " ".join(possible_types)

该字符串中的字母hs(分别为单词High_EconomyBusiness),但是序列try并未出现在字符串中的任何地方.

The letters h and s are in that string (in the words High_Economy and Business, respectively), but the sequence try doesn't appear anywhere in the string.

如果只想让整个单词匹配,则需要留下possbile_types列表,或者理想情况下将其转换为 set (因为集合允许进行快速成员资格测试).您可以在此处定义列表,无需list.extend():

If you only wanted to allow whole words to match, you'd need to leave possbile_types a list, or ideally convert it to a set (as sets allow for fast membership testing). You can define the list, no need for list.extend() here:

possible_types = ["Low_Economy", "Standard_Economy", "High_Economy",
                   "Business", "First", "Residence"]

或使用{...}将其设为集合:

possible_types = {"Low_Economy", "Standard_Economy", "High_Economy",
                   "Business", "First", "Residence"}

不要将其连接到字符串中,只需直接针对对象进行测试:

Do not join this into a string, just test directly against the object:

if self.seat not in possible_types:

如果您仍然需要在错误消息中向用户显示值,请先将值 then 联接起来,或将str.join()结果存储在不同的变量中.

If you still need to show the values to a user in an error message, join the values then, or store the str.join() result in a different variable for that purpose.

请注意,您不应在类__init__方法中处理用户输入验证.将用户交互操作留给单独的代码段,并在验证后的之后创建类的实例.这样一来,您可以轻松换出用户界面,而不必也调整所有数据对象.

Note that you shouldn't deal with user input validation in the class __init__ method. Leave user interaction to a separate piece of code, and create instances of your class after you validated. That way you can easily swap out user interfaces without having to adjust all your data objects too.

这篇关于列表有问题吗?错误检查不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆