有人能看到我代码中的缺陷吗?

2024-09-29 22:35:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码有几个问题需要帮助解决

  1. 如何使标题只在结果上方打印一次,如果没有任何内容符合标准,则根本不打印
  2. 我的代码的else组件不再工作了,以前如果其他场景都不是真的,它只会打印,但是我更新了它,现在它每次都会打印。有人能发现这个问题吗

代码:

import Hotels

htl_1= Hotels.Hotels(111,100,1,1)
htl_2= Hotels.Hotels(112,200,2,1)
htl_3= Hotels.Hotels(113,250,2,2)
htl_4= Hotels.Hotels(114,300,3,2)
htl_5= Hotels.Hotels(115,350,3,3)


feeInput=input('Enter maximum per night fee: ')
roomInput=input('Enter minimum number of bedrooms: ')
bathInput=input('Enter minimum number of baths: ')


header='{:10} {:10} {:10} {:10}'.format('Room#','Cost','Rooms','Bathrooms')

print(header)

if int(feeInput)>= htl_1.fee and int(roomInput)<= htl_1.rooms and int(bathInput)<= htl_1.bath:
    print(htl_1.gethtl())
if int(feeInput)>= htl_2.fee and int(roomInput)<= htl_2.rooms and int(bathInput)<= htl_2.bath:
    print(htl_2.gethtl())
if int(feeInput)>= htl_3.fee and int(roomInput)<= htl_3.rooms and int(bathInput)<= htl_3.bath:
    print(htl_3.gethtl())
if int(feeInput)>= htl_4.fee and int(roomInput)<= htl_4.rooms and int(bathInput)<= htl_4.bath:
    print(htl_4.gethtl())
if int(feeInput)>= htl_5.fee and int(roomInput)<= htl_5.rooms and int(bathInput)<= htl_5.bath:
    print(htl_5.gethtl())

else:
    print('Sorry, no rooms available that meet that criteria')

Tags: and代码inputifintprintfeerooms
2条回答

您需要将if更改为elif,并将头打印代码移动到if

在不了解Hotels模块的情况下,我相信这个语法是正确的。为了使else只在那些if语句都不为true时激活,您需要将它们更改为elif(在第一个if语句之后),如图所示。您使用的.format只在打印语句中起作用,如图所示。谢谢

import Hotels

htl_1= Hotels.Hotels(111,100,1,1)
htl_2= Hotels.Hotels(112,200,2,1)
htl_3= Hotels.Hotels(113,250,2,2) 
htl_4= Hotels.Hotels(114,300,3,2)
htl_5= Hotels.Hotels(115,350,3,3)

feeInput = int(input('Enter maximum per night fee: '))
roomInput = int(input('Enter minimum number of bedrooms: '))
bathInput = int(input('Enter minimum number of baths: '))

header = True

if feeInput >= htl_1.fee and roomInput <= htl_1.rooms and bathInput<= htl_1.bath: 
    print(htl_1.gethtl())
elif feeInput >= htl_2.fee and roomInput <= htl_2.rooms and bathInput <= htl_2.bath: 
    print(htl_2.gethtl()) 
elif feeInput >= htl_3.fee and roomInput <= htl_3.rooms and bathInput <= htl_3.bath: 
    print(htl_3.gethtl()) 
elif feeInput >= htl_4.fee and roomInput <= htl_4.rooms and bathInput <= htl_4.bath: 
    print(htl_4.gethtl()) 
elif feeInput >= htl_5.fee and roomInput <= htl_5.rooms and bathInput <= htl_5.bath: 
    print(htl_5.gethtl())
else: 
    print('Sorry, no rooms available that meet that criteria')
    header = False

if header == True:
    print('{0} {1} {2} {3}'.format(RoomVar,CostVar,RoomsVar,BathroomsVar))

相关问题 更多 >

    热门问题