我仍然在尝试习惯Python中的课程,因为我在度假,我没有互联网,所以无法查找任何教程。因此,我正在努力教他们自己。我不久前问了一个与此相关的问题,并且几乎完全改变了我的代码并缩短了它的大部分,但它似乎仍然有错误。我已经尝试了所有我能想到的东西,但这很可能是我想念的一件简单的事情。代码和输出如下:
该计划正试图确定人们在飞机上想要的座位类型。
类别:
class SeatBooking:
def __init__(self, seat):
self.seat = seat
possible_types = ["Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"]
while True:
if self.seat.lower() not in possible_types:
print("Sorry, but this is not a valid answer. "
"Please try again!")
break
else:
continue
主要代码('调用'类或任何术语):
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"])
seat_type = input("What type of ticket would you like? The possible types "
"are: {}. ".format(possible_types))
type_seat.SeatBooking(seat_type)
print("You have chosen to book a {} ticket.".format(seat_type))
confirmation = input("Please confirm with 'Yes' or 'No': ").lower()
if confirmation == "yes":
print("Excellent decision! Ready to continue")
print("=" * 170)
elif confirmation == "no":
seat_type = str(input("What type of ticket would you like? The "
"possible types are: {} ".format(possible_types)))
type_seat.SeatBooking(seat_type)
else:
print("That doesn't seem to be a valid answer.")
输出(我输入的内容以斜体粗体显示):
我的问题:
请随意检查此代码的“旧”版本 - 它可能表明它无效的原因。但是,那个也有问题。 :(
答案 0 :(得分:0)
这个条件:
if self.seat.lower() not in possible_types:
您将座位转换为小写,但可能的类型:
possible_types.extend(["Low_Economy", "Standard_Economy", "High_Economy", "Business", "First", "Residence"])
也有大写字母,这会发生冲突。
不太相关的问题:
在创建时直接在列表中插入数据:
possible_types = ["Low_Economy","Standard_Economy","High_Economy","Business", "First", "Residence"]
我不明白为什么你需要使用extend,我不明白你为什么要声明它两次。
如果您让用户输入,他们可以输入类似的内容。
答案 1 :(得分:0)
此
possible_types = ["Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"]
while True:
if self.seat.lower() not in possible_types:
永远不会起作用,因为lhs上的值都是小写,而右侧的值是大小写混合。可能最容易在possible_types中输入也是小写的......
答案 2 :(得分:0)
您的示例中有几个问题。
in
,您将无限期循环,因为continue
不会破坏循环!还有一些轻微的低效率可以通过使用其他数据类型来解决:
possible_types
在类和代码中定义。你可以为两者使用一个变量。list
中的查询平均O(n)
次查询时间,您可以使用set
(或者如果他们不更改frozenset
),则{{1}查询时间。简而言之,我会按如下方式重写:
O(1)