【问题标题】:How do I use a while loop to add a variable every time it loops?如何在每次循环时使用 while 循环添加变量?
【发布时间】:2016-09-15 05:51:05
【问题描述】:

我正在编写一个程序,告诉用户输入一个属性的房间数量,然后一个 while 循环找出每个房间的宽度和长度。我觉得我需要while循环来创建两个额外的变量来存储每次迭代时的宽度和长度,但是我不知道如何。 到目前为止,这是我的代码:

roomCount = 1
print("Please answer the questions to find the floor size.")
rooms = int(input("How many rooms has the property got?:\n"))
while roomcount >= rooms:
    print("For room", roomcount,", what is the length?:\n")

不多,但我一直在网上搜索,但没有找到方法。

我希望程序做的是询问用户该物业有多少个房间,然后对于每个房间,它应该询问房间的宽度和长度。然后,程序应该以用户友好的格式显示建筑空间的总面积

更新代码:

currentRoomNumber = 0
currentRoomNumber2 = 0
floorspace = 0
whileLoop = 0
print("Please answer the questions to find the floor size.")
numberOfRooms = int(input("How many rooms has the property got?: "))
roomWidths= list()
roomLengths = list()
while currentRoomNumber < numberOfRooms:
    roomWidths.append(int(input("For room " + str(currentRoomNumber + 1) + ", what is the width?: ")))
    roomLengths.append(int(input("For room " + str(currentRoomNumber + 1) + ", what is the length?: ")))
    currentRoomNumber += 1

while whileLoop < numberOfRooms:
    floorspace += (roomLengths[(currentRoomNumer2)] * roomWidths[(currentRoomNumber2)])
    currentRoomNumber2 += 1
    whileLoop += 1

print(floorspace)

但是,在输入房间尺寸的值后,它在第 15 行给我一个回溯错误,并说 currentRoomNumber2 未定义。我哪里出错了?

【问题讨论】:

  • room("For room", roomcount,", what is the length?:\n") 这是一个函数调用吗,因为它看起来很像。你想在这里做什么?
  • 这是我的大脑工作不正常,抱歉。它的意思是打印
  • 您是否尝试在每次循环时增加roomcount?如果是这样就去roomcount += 1
  • 你还有两个不同的变量,roomCountroomcount,我认为你的 while 表达式应该看起来像 roomcount &lt;= rooms。另外,不要忘记在每次迭代后增加 roomcount
  • 给我们一个测试用例,并清楚地解释你想要什么。

标签: python variables while-loop


【解决方案1】:

从你的问题看来,这就是你想要的:

    print("Please answer the questions to find the floor size.")
    numberOfRooms = int(input("How many rooms has the property got?: "))
    currentRoomNumber = 0
    roomLengths = list()
    while currentRoomNumber < numberOfRooms:
        roomLengths.append(int(input("For room " + str(currentRoomNumber + 1) + ", what is the length?: ")))
        currentRoomNumber += 1
    print roomLengths

这会将每个房间的长度放入一个列表中(记住房间“1”根据用户是房间“0”给你)。

当你运行它时,它看起来像这样(我把每个房间的长度作为房间号):

    Please answer the questions to find the floor size.                                                                                                                                                  
    How many rooms has the property got?: 5                                                                                                                                                              
    For room 1, what is the length?: 1                                                                                                                                                                   
    For room 2, what is the length?: 2                                                                                                                                                                   
    For room 3, what is the length?: 3                                                                                                                                                                   
    For room 4, what is the length?: 4                                                                                                                                                                   
    For room 5, what is the length?: 5                                                                                                                                                                   
    [1, 2, 3, 4, 5] 

如我之前所说,要访问每个房间的长度,请确保将房间“1”(长度 1)引用为房间“0”,这意味着您将其引用为:

    print roomLengths[0]

这可能很简单,但我想向您说明一下,因为您问的是如何“创建变量”,实际上您想要的是一个列表,因为您不知道要创建多少个“变量”创造;所以这个列表可以有你需要的房间长度。

要在其中添加宽​​度,您只需添加另一个列表并像这样输入:

    print("Please answer the questions to find the floor size.")
    numberOfRooms = int(input("How many rooms has the property got?: "))
    currentRoomNumber = 0
    roomWidths= list()
    roomLengths = list()
    while currentRoomNumber < numberOfRooms:
        roomWidths.append(int(input("For room " + str(currentRoomNumber + 1) + ", what is the width?: ")))
        roomLengths.append(int(input("For room " + str(currentRoomNumber + 1) + ", what is the length?: ")))
        currentRoomNumber += 1
    print "Room widths:"
    print roomWidths
    print "Room lengths:"
    print roomLengths

脚本的输出/运行将是这样的:

    Please answer the questions to find the floor size.                                                                                                                                                  
    How many rooms has the property got?: 3                                                                                                                                                              
    For room 1, what is the width?: 1                                                                                                                                                                    
    For room 1, what is the length?: 2                                                                                                                                                                   
    For room 2, what is the width?: 3                                                                                                                                                                    
    For room 2, what is the length?: 4                                                                                                                                                                   
    For room 3, what is the width?: 5                                                                                                                                                                    
    For room 3, what is the length?: 6                                                                                                                                                                   
    Room widths:                                                                                                                                                                                         
    [1, 3, 5]                                                                                                                                                                                            
    Room lengths:                                                                                                                                                                                        
    [2, 4, 6]  

【讨论】:

  • 我如何将每个房间的长度乘以宽度? floorArea = roomWidths[0] * roomLengths[0] 或类似的东西?
  • 完全一样。
  • @PavelGurkov 我知道我现在会这样检查,但我要如何让它检查每个房间?
  • @Student 您需要遍历每个 roomWidths 和相应的 roomLengths,如下所示:for i in range(len(roomWidths)): floorArea = roomWidths[i] * roomLengths[i]for index, width in enumerate(roomWidths): floorArea = width * roomLengths[index]
【解决方案2】:

认为您希望通过房间号来保存长度和宽度,我会这样做:

rooms = {}

print("Please answer the questions to find the floor size.")

rooms = int(input("How many rooms has the property got?:\n"))

for room_num in range(1, rooms+1):
    length = int(input("What is the lenth of room number {}: ".format(room_num)))
    width = int(input("What is the lwidth of room number {}: ".format(room_num)))
    rooms[room_num] = {'length': length, 'width': width}

然后要获得房间 1 的长度,只需查找:rooms[1]['length'],宽度:rooms[1]['width'] 等。等等

【讨论】:

    【解决方案3】:

    我建议参加 Room 课程。然后你可以在上面定义一个area 方法。

    class Room():
        def __init__(self, w, l):
            self.width = w
            self.length = l
    
        def area(self):
            return self.width * self.length
    

    然后,对于您的输入,将它们存储到一个列表中。请改用 for 循环。不需要while循环。

    print("Please answer the questions to find the floor size.")
    
    roomCount = int(input("How many rooms does the property have?\n"))
    
    rooms = []
    for roomNum in range(roomCount):
        l = float(input("For room {} what is the length?\n".format(roomNum + 1)))
        w = float(input("For room {} what is the width?\n".format(roomNum + 1)))
        rooms.append(Room(w, l))
    

    完成后,您只需遍历对象并将区域相加即可。

    size = sum(r.area() for r in rooms)
    print(size)
    

    【讨论】:

      【解决方案4】:

      我会这样做。

      rooms_total = int(input('How many rooms?'))
      rooms_info = list()
      
      for i in range(rooms_total):
          length = int(input('Length for room #{}?'.format(i)))
          width = int(input('Width for room #{}?'.format(i)))
          rooms_info.append({'length': length, 'width': width})
      
      space = sum([x['length'] * x['width'] for x in rooms_info])
      print(space)
      

      类感觉有点矫枉过正(除非你特别想练习类),而字典在这里感觉不像是一个合适的外部数据结构。

      这只是我的拙见,但您需要阅读更多关于 Python 中的循环和基本数据结构的信息。

      【讨论】:

      • 我同意你的观点,但我只是在中学,在过去的 6 周里根本没有做任何编码。对不起
      猜你喜欢
      • 1970-01-01
      • 2016-01-12
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 2014-12-12
      • 2021-11-03
      • 1970-01-01
      • 2020-04-07
      相关资源
      最近更新 更多