Question: We'll need some prompt validation. ( Validating input means checking that it matches some criterion. ) Write a function below that prompts a user for
We'll need some prompt validation. Validating input means checking that it matches some criterion.
Write a function below that prompts a user for a positive floating point number. If the user enters zero or a negative number, print a brief error message, then repeat the prompt for a positive value.
When the user responds with a positive number, return the value of that number as a floating point number.
Your function should have:
No parameters. In other words, if the function were named f you would call it like this: f
Return value should be the positive floating point number entered by the user.
Choose a good descriptive name for your prompt function, again written in snake case. Dont use f
:
# Write your prompt function definition
def promptforpositivefloat:
while True:
try:
userinput floatinputEnter a positive floating point number:
if userinput :
return userinput
else:
printPlease enter a positive number."
except ValueError:
printInvalid input. Please enter a valid number."
We will also need to test this function.
In the cells below, test your function with:
A positive number given on the first try
A positive number given on the second try
A positive number given on the fourth try
Be sure that your test in some way reports on the return value of the function. An easy way to do this would be to assign the result to a variable, eg
returnedvalue myfunction printfValue returned: returnedvalue:f
But you could also just display the value by evaluating returnedvalue, if that is the last expression in the cell you are running below.
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
