任何人都能看到我的代码中的缺陷吗?

时间:2018-03-04 21:57:22

标签: python

我的代码存在一些问题我需要帮助解决问题。

  1. 如何让标题仅在结果上方打印一次,如果没有满足标准则根本不打印?
  2. 我的代码的else组件不再有效,如果没有其他方案都是真的那么它只用于打印但我更新了它,现在它每次都保持打印。有谁能发现这个问题?
  3. 代码:

    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')
    

2 个答案:

答案 0 :(得分:1)

在不知道Hotels模块的情况下,我相信这种语法是正确的。为了使else只在没有if语句都为真时激活,你需要将它们更改为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))

答案 1 :(得分:0)

您需要将if更改为elif,并将标题打印代码移至if块。