【发布时间】:2016-12-17 14:21:44
【问题描述】:
我对 python 比较陌生,我刚刚开始学习如何使用类。这是我尝试整合它们的第一个程序,但我想出了一个我似乎无法解决的小问题,我认为它与列表有关。代码如下: (主题是让用户选择要购买的座位类型)。
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.")
这是主文件(用于执行我将创建的不同类):
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”这样的随机词时它会响应。不过,它似乎并不是完全随机的,而且它似乎只发生在 possible_types[] 列表中的前 3 个“项目”的字母或部分中。但是,我还没有完全测试这一点。这就是为什么我认为它与列表有关,所以如果有人知道是什么原因造成的,如果他们能帮助我解决这个问题,或许能帮助我在未来避免重复这个错误,我将不胜感激!
注意,对于我正在使用.join 的列表,但我也尝试了 str()。
【问题讨论】:
-
h是在你的possible_types中;那只是一个包含一系列字符的字符串,而字符h是其中的一部分(在单词High_Economy中)。序列try不是。为什么你使用" ".join()来创建这个字符串而不是列表? -
天哪,你是对的!我删除了它并且它起作用了。我认为我必须在 str() 之前使用 .join ,因为我一直遇到问题,但我猜不是。另外,我不是最好的;)。无论如何,一个问题。你知道为什么这行: self.seat = str(input("What type of ticket you like? The possible types are: {} " .format(possible_types))) 给我一个键盘中断?
-
1) 你不需要调用
str(),在 Python 3 中input()总是 返回一个str。input()需要一个支持用户输入响应的控制台;我猜您可能是在 IDE 控制台或类似的没有输入的地方运行此代码?这可能会导致 EOF 被引发或键盘中断。否则,不知道。 -
等待新版本由于某种原因似乎不起作用..没关系。当我尝试输入某些内容时,没有任何效果。
-
我正在使用 Pycharm
标签: python list python-3.x