A programmer wants one function that can validate many different whole-number inputs, for example month = getNumber(1, 12) or day = getNumber(1, 31).
Write a function called getNumber that takes a lowest and a highest allowed value as parameters. It should ask the user for a whole number, keep asking until the number is from the lowest to the highest value inclusive, and then return it.
You may assume that the user always types a whole number.
Write the function using OCR Exam Reference Language or a high-level programming language.
Model answer
function getNumber(low, high)
num = int(input("Enter a number from " + str(low) + " to " + str(high)))
while num < low OR num > high
print("Out of range")
num = int(input("Enter a number from " + str(low) + " to " + str(high)))
endwhile
return num
endfunction
Explanation
Using parameters for the limits means one range check can be reused for any input, which is better than writing a separate loop each time. The function must return the number so the calling code can store it, as in month = getNumber(1, 12). Check the boundaries: num < low OR num > high accepts both low and high.