우선 입력을 지속적으로 확인하려면 루프를 사용해야합니다. 에서와 마찬가지로 알고리즘의 psuedocode는 다음과 같습니다.
Loop Begin
Check the value of a and b
If a or b is less than 0 then ask for input again
Otherwise, continue
알고리즘에 유의하십시오 가지다 실행하려면 적어도 한 번.
그것이 기본적으로 psuedocode의 방법입니다 ~해야 한다 보입니다. 그래서 이것은 당신이 사용할 수있는 경우입니다. do-while
루프 구성. 파이썬에는 이와 같은 것이 없으므로 우리는 에뮬레이션 그것:
import math
def take_in():
a = raw_input("Enter the value of side a -> ")
b = raw_input("Enter the value of side b -> ")
# Trying to convert to a float
try:
a, b = float(a), float(b)
# If successfully converted, then we return
if a > 0 and b > 0:
return a, b
except ValueError:
pass
# If we cannot return, then we return false, with a nice comment
print "Invalid input"
return False
def main():
# Calling the function at least once
valid = take_in()
# While we are not getting valid input, we keep calling the function
while not valid:
# Assigning the value to valid
valid = take_in()
# Breaking the return tuple into a and b
a, b = valid
print math.sqrt(a ** 2 + b ** 2)
if __name__ == '__main__':
main()