[英]Error with code, I am unsure of what the problem is but it seems to be looping
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")
for elem in name:
print("- " + elem)
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():
print("Name: ", name[i])
print("Capacity: ", cap[i])
print("Off Peak Rate: 0" + str(offpeak[i]))
print("Peak Rate: 0" + str(peak[i]))
exit
print("Invalid Room Name Entered Try Again")
desired_room = (str(input("Enter The Name Of The Room You Would Like To Book: "))).lower()
week = int(input("Enter The Week Your Stay Starts "))
This is my code. 这是我的代码。 When the user inputs the the name of the room it works but then for some reason it loops and asks the user which room they want to book. 当用户输入房间名称时,它会起作用,但是由于某种原因,它会循环并询问用户他们想要预订哪个房间。 How can I fix it so "Enter The Week Your Stay Starts " is asked instead of the room that the user wants to book is inputted? 如何解决此问题,而不是输入用户要预订的房间,而要求输入“输入您的住宿开始一周”? Picture reference https://imgur.com/a/QAtnHT9 图片参考https://imgur.com/a/QAtnHT9
The first problem is that you want break
, not exit
. 第一个问题是您想break
而不是exit
。
The break
statement breaks out of a loop, which is what you want to do. break
语句会跳出循环,这是您想要执行的操作。
exit
is not a statement. exit
不是声明。 It's the name of a function, which you aren't calling, so it doesn't do anything, any more than just writing sorted
would. 它是函数的名称,您不需要调用它,因此它什么也没做,只不过是编写sorted
的函数而已。 Also, it isn't intended to be used except in interactive mode; 另外,除在交互模式下外,不打算使用它。 if you need to exit a script in the middle of the script, you use sys.exit()
. 如果需要在脚本中间退出脚本,请使用sys.exit()
。 Also, you don't want to exit the whole script here anyway, just the loop. 另外,您还是不想在这里退出整个脚本,而只是退出循环。
But you've got another problem beyond that: You have one loop nested inside another one. 但是除此之外,您还有另一个问题:您在另一个循环中嵌套了一个循环。 Breaking out of the first one won't break out of the second one. 突破第一个不会脱离第二个。
You need to reorganize your logic in some way that it's easy to get out of this code where you want to, and the cleanest way to do that is usually by writing a function, which you can return
from: 您需要以某种方式重组逻辑,以便轻松地从所需代码中删除该代码,而最简单的方法通常是编写一个函数,该函数可以从以下代码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()
And now, you can just call that function: 现在,您可以调用该函数:
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]))
While we're at it, you can simplify this code in a number of ways. 在我们讨论过程中,您可以通过多种方式简化此代码。 You can just ask for the input
at the top of the loop instead of doing it twice; 您可以只在循环的顶部请求input
,而不必重复两次; you don't need to call str
on something that's already a string; 您不需要在已经是字符串的东西上调用str
; you can use string formatting instead of manually converting things to strings and concatenating… 您可以使用字符串格式设置,而不必手动将其转换为字符串并进行串联…
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]}")
While the points raised in @abarnert's answer are valid, you can use a for-else
construct like the following instead to avoid using a separate function to break out of a nested loop: 虽然@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
Solution 解
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 "))
It would make your code easier to work with, if you just split what you are trying to do there up a little. 如果您只是将要尝试的内容稍微拆分一下,它将使您的代码更易于使用。 If you make a while
loop that checks to make sure the desired_room
exists first then you can enter your next loop knowing that desired_room
is a valid entry. 如果您创建一个while
循环,以检查是否首先要确定所需的desired_room
,那么您可以知道desired_room
是有效条目,然后进入下一个循环。
Also by transforming inputs into title
instead of lower
you can check with your name
quicker since you know all entries are in title case format. 同样,通过将输入转换为title
而不是lower
title
,您可以更快地检查name
因为您知道所有条目都采用标题大小写格式。
Thoughts 思考
The way you are, you are matching all the indices for each list to get the proper info ( name[0], cap[0], peak[0],... give us
Hetty`'s information). 按照您的方式,您将匹配每个列表的所有索引以获得正确的信息( name[0], cap[0], peak[0],... give us
Hetty的信息)。 This is fine but what happens when you have 100 rooms and you entry number 67 is off, its going to be rough going through each list and checking index 67. Instead you could use a list of dictionaries to keep each rooms information together. 很好,但是当您有100个房间并且您关闭了条目号67时会发生什么,通过每个列表并检查索引67会很困难。相反,您可以使用词典列表将每个房间的信息保持在一起。 Just trying to give some ideas, threw in some print formatting ideas as well, 只是想提出一些想法,也提出一些印刷格式的想法,
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 "))
Output 产量
(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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.