Home > Mobile >  Refactoring While & If loop of a code with Python?
Refactoring While & If loop of a code with Python?

Time:10-21

Hi I'm learning Python by myself and I'm tying to refactor this code. I need to use declaration and invoke of the function.

So the original code is:

while True:
    length = int(input("Enter the length of your room: "))
    if length > 0:
        break

while True:
    width = int(input("Enter the width of your room: "))
    if width > 0:
        break

while True
    height = int(input("Enter the height of your room: "))
    if height > 0:
            break
print("The volume of your room is", length * width * height)

What I'm doing so far (I'm not sure if it's good or not). Any suggestions?:

def volume(length, width, height)
    length= int(input("Enter the length of your room: "))
       while (length = 0):
         print(f"The length of your room is invalid)
         return

    width = int(input("Enter the width of your room: "))
       while (width = 0):
         print(f"The width of your room is invalid)
         return
    height = int(input("Enter the height of your room: "))
       while (height = 0):
         print(f"The height of your room is invalid)
         return
    print("The volume of your room is", length * width * height)
    return

volume(length*width * height)

CodePudding user response:

Code:

def volume(lenght, width, height):
    if lenght > 0 and width > 0 and height > 0:
        room_volume = lenght*width*height
        return room_volume
    return 'wrong input'

room_volume = volume(input('Length: '), input('Width: '), input('Height: '))
print(f'Room volume: {room_volume}')

You can check if argument value is greater than 0 just by one simple if statement, no need for these while loops.

  • Related