حسنًا ، إذا كنت ترغب في التحقق باستمرار من المدخلات الخاصة بك ، فسيتعين عليك استخدام حلقة. كما هو الحال في ، يجب أن يكون 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()