代码错误,我不确定是什么问题,但似乎在循环

时间:2018-09-10 00:49:15

标签: python loops

-1

这是我的代码。当用户输入房间名称时,它会起作用,但是由于某种原因,它会循环并询问用户他们想要预订哪个房间。如何解决此问题,而不是输入用户要预订的房间,而要求输入“输入您的住宿开始一周”? 图片参考 https://imgur.com/a/QAtnHT9

3 个答案:

答案 0 :(得分:0)

第一个问题是您想要break,而不是exit

break语句会跳出循环,这是您想要做的。

exit不是语句。它是函数的名称,您不需要调用它,因此它什么也没做,只不过是编写sorted而已。另外,除在交互模式下外,不打算使用它。如果需要在脚本中间退出脚本,请使用sys.exit()。此外,无论如何,您都不会想要在这里退出整个脚本,而只是退出循环。


但是除此之外,您还有另一个问题:您有一个循环嵌套在另一个循环中。脱离第一个不会脱离第二个。

您需要以某种方式重新组织逻辑,以便轻松地从您想要的位置离开此代码,而最简单的方法通常是编写一个函数,您可以return从以下位置进行:

def book_room():
    desired_room = (str(input("Enter The Name Of The Room You Would Like To Book: "))).lower()

    while True: 
        for i in range (0,10):
            if desired_room == name [i].lower():
                return i
        print("Invalid Room Name Entered Try Again")
        desired_room = (str(input("Enter The Name Of The Room You Would Like To Book:   "))).lower()

现在,您可以调用该函数:

room = book_room()
print("Name: ", name[room])
print("Capacity: ",  cap[room])
print("Off Peak Rate: 0" + str(offpeak[room]))
print("Peak Rate: 0" + str(peak[room]))

我们正在使用它,您可以通过多种方式简化此代码。您只需在循环的顶部请求input即可,而不必两次。您不需要在已经是字符串的内容上调用str;您可以使用字符串格式设置,而不必手动将其转换为字符串并进行串联……

def book_room():
    while True: 
        desired_room = input("Enter The Name Of The Room You Would Like To Book: ")).lower()
        for i in range(0,10):
            if desired_room == name[i].lower():
                return i
        print("Invalid Room Name Entered Try Again")

room = book_room()
print(f"Name: {name[room]}")
print(f"Capacity: {cap[room]}")
print(f"Off Peak Rate: 0{offpeak[room]}")
print(f"Peak Rate: 0{peak[room]}")

答案 1 :(得分:0)

虽然@abarnert答案中提出的要点是有效的,但您可以使用类似以下内容的for-else构造,以避免使用单独的函数打破嵌套循环:

while True: 
    for i in range (0,10):
        if desired_room == name[i].lower():
            print("Name: ", name[i])
            print("Capacity: ",  cap[i])
            print("Off Peak Rate: 0" + str(offpeak[i]))
            print("Peak Rate: 0" + str(peak[i]))
            break
    else:
        print("Invalid Room Name Entered Try Again")
        desired_room = (str(input("Enter The Name Of The Room You Would Like To Book:   "))).lower()
        continue
    break

答案 2 :(得分:0)

解决方案

name = [ 
    "Hetty", "Poppy", "Blue Skies", "Bay View", "Happy Days", "Summer Joy", 
    "Walkers Rest", "Bertie", "Green Forest Lodge", "Coppice Lodge" 
]
cap = [4, 4, 4, 6, 6, 6, 8, 8, 10, 10] 
peak = [400, 400, 500, 650, 695, 800, 950, 1050, 1200, 1500]
offpeak = [250, 250, 350, 500, 550, 600, 750, 850, 950, 1150]
onoff = False
cost = 0 

print("Here are our avaliable lodges")
[print(f"-{elem}") for elem in name]

desired_room = input("Enter The Name Of The Room You Would Like To Book: " \
    ).title()

while desired_room.title() not in name:
    print("Invalid Room Name Entered Try Again")
    desired_room = input("Enter The Name Of The Room You Would Like To" + 
        " Book:").title()

for i in range(len(name)) :
    if desired_room == name [i]:
        print("Name: ", name[i])
        print("Capacity: ",  cap[i])
        print("Off Peak Rate: 0" + str(offpeak[i]))
        print("Peak Rate: 0" + str(peak[i]))

week = int(input("Enter The Week Your Stay Starts "))

如果您只是将要尝试的内容分开一点,它将使您的代码更易于使用。如果您进行while循环检查以确保首先存在desired_room,则可以知道desired_room是有效条目,然后进入下一个循环。

通过将输入转换为title而不是lower,您也可以更快地查看name,因为您知道所有条目都是标题大小写格式。

想法

您的方式是,您要匹配每个列表的所有索引以获取正确的信息(name[0], cap[0], peak[0],... give us Hetty`s信息)。很好,但是当您有100个房间并且您关闭了条目号67时会发生什么,通过每个列表并检查索引67会很困难。相反,您可以使用词典列表将每个房间的信息保持在一起。只是想提出一些想法,也提出一些印刷格式的想法,

def print_info(something):
    r_width = len(something['name'])
    print("-"*15 + "-"*(r_width+1))
    print("Name:".ljust(15), f"{something['name']}".rjust(r_width))
    print("Capacity:".ljust(15), f"{something['cap']}".rjust(r_width))
    print("Off Peak Rate:".ljust(15), f"{something['offpeak']}".rjust(r_width))
    print("Peak Rate:".ljust(15), f"{something['peak']}".rjust(r_width))
    print("-"*15 + "-"*(r_width+1))

rooms = [
    {'name': 'Hetty', 'cap': 4, 'peak': 400, 'offpeak': 250},
    {'name': 'Poppy', 'cap': 4, 'peak': 400, 'offpeak': 250},
    {'name': 'Blue Skies', 'cap': 4, 'peak': 500, 'offpeak': 350},
    {'name': 'Bay View', 'cap': 6, 'peak': 650, 'offpeak': 500},
    {'name': 'Happy Days', 'cap': 6, 'peak': 695, 'offpeak': 550},
    {'name': 'Summer Joy', 'cap': 6, 'peak': 800, 'offpeak': 600},
    {'name': 'Walkers Rest', 'cap': 8, 'peak': 950, 'offpeak': 750},
    {'name': 'Bertie', 'cap': 8, 'peak': 1050, 'offpeak': 850},
    {'name': 'Green Forest Lodge', 'cap': 10, 'peak': 1200, 'offpeak': 950},
    {'name': 'Coppice Lodge', 'cap': 10, 'peak': 1500, 'offpeak': 1050}
]

onoff = False
cost = 0

room_avail = []
for i in rooms:
    room_avail.append(i['name'])

print("Here are our avaliable lodges")
for i in rooms:
    print(f"-{i['name']}")

desired_room = input("Enter The Name Of The Room You Would Like To Book: " \
    ).title()

while desired_room not in room_avail:
    print("Invalid Room Name Entered Try Again")
    desired_room = input("Enter The Name Of The Room You Would Like To" +
        " Book:").title()

for i in rooms:
    if desired_room == i['name']:
        print_info(i)

week = int(input("Enter The Week Your Stay Starts "))

输出

(xenial)vash@localhost:~/python$ python3.7 hotel.py
Here are our avaliable lodges
-Hetty
-Poppy
-Blue Skies
-Bay View
-Happy Days
-Summer Joy
-Walkers Rest
-Bertie
-Green Forest Lodge
-Coppice Lodge
Enter The Name Of The Room You Would Like To Book: coppice lodge
-----------------------------
Name:           Coppice Lodge
Capacity:                  10
Off Peak Rate:           1050
Peak Rate:               1500
-----------------------------
Enter The Week Your Stay Starts