2016-09-14 2 views
0

나는 속성이있는 방의 양을 입력하라는 프로그램을 작성하고 while 루프는 각 방의 너비와 길이를 알아 낸다. 반복 할 때마다 너비와 길이를 저장하기 위해 두 개의 추가 변수를 만드는 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은 정의되지 않았습니다. 내가 어디로 잘못 갔니?

+3

':

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 

출력은/스크립트의 실행 사항은 다음과 같이 될 것이다 방 ("room", roomcount, "길이는 무엇입니까? : \ n")' 확실히 하나이기 때문에이 함수 호출입니다. 너 여기서 뭘하려고하는거야? – MooingRawr

+0

내 뇌가 제대로 작동하지 않습니다. 죄송합니다. 그것의 인쇄물을 말하려고합니다 – Student

+0

while 루프 때마다 'roomcount'를 늘리려고합니까? 만약 그냥 'roomcount + = 1'이 보일 경우 – MooingRawr

답변

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"당신입니다).당신이 이것을 실행하면

, 그것은 다음과 같이 (I 방 번호가 있었다 어떤 각 실의 길이)를 넣어 본다 : 내가 전에 말했듯이

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] 

는, 각 객실의 길이에 액세스하려면를 만들 확실히 당신은 당신이로 참조됩니다 의미 룸 "0"으로 방 "1"(길이 1)을 참조 :

print roomLengths[0] 

이 간단 할 수 있지만이 방법을 묻는 된 이후 나는 당신에게 분명히 확인하고 싶었 "변수 만들기"에 실제로 원하는 변수의 수를 알지 못하기 때문에 원하는 것은 목록입니다. 몹시 떠들어 대다; 그래서이리스트는 당신이 필요로하는 많은 룸 길이를 가질 수 있습니다.

방금과 같이 다른 목록 입력을 추가, 거기에 폭을 추가하려면 :

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] 
+0

각 방의 너비에 따라 객실 길이를 어떻게 곱합니까? 'floorArea = roomWidths [0] * roomLengths [0]'또는 이와 비슷한 것? – Student

+0

정확히 그런 것. –

+0

@PavelGurkov 그게 내가 지금 그것을 확인하는 방법이지만 모든 방을 어떻게 확인 할 수 있겠는가? – Student

0

당신이 방 번호가 저장되는 길이와 폭을하려는 생각, 내가 이런 짓을 할 것이다 : 그런 다음

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'], 등.

0

나는 Room 클래스로가는 것이 좋습니다. 그런 다음 area 메소드를 정의 할 수 있습니다.

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

    def area(self): 
     return self.width * self.length 

그런 다음 입력 사항을 목록에 저장하십시오. for-loop를 대신 사용하십시오. 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) 
0

이렇게하면됩니다. (특별히 수업을 연습하지 않으려면)

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) 

클래스 잔인한 같은 느낌, 그리고 사전은 여기에 적절한 외부 데이터 구조처럼 생각하지 않습니다.

필자의 겸허 한 의견 일 뿐이지 만 파이썬에서는 루프와 기본 데이터 구조에 대해 더 자세히 알아야합니다. 그것은이처럼 보인다 질문에서

+0

나는 동의하지만, 나는 단지 중학교에 다니고 있으며 지난 6 주 동안 전혀 코딩을하지 않았다. 죄송합니다 – Student

관련 문제