用Python重构代码的while&if循环?



嗨,我正在自学Python,我打算重构这段代码。我需要使用函数的声明和调用。

所以原始代码是:

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)

到目前为止我在做什么(我不确定它是否好(。有什么建议吗?:

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)

代码:

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

您可以通过一个简单的if语句来检查参数值是否大于0,而不需要这些while循环。

最新更新