Study Guide

6.5.7 Enter a Positive Number CodeHS Answers

6.5.7 Enter a Positive Number CodeHS Answers

The most common answer is:

def retrieve_positive_number():
while(True):
try:
x = int(input())
except ValueError:
print(“An error has occured”)
if(x>0):
return x
else:
print(“The value is not a zero”)
retrieve_positive_number()

To ensure your function retrieve_positive_number correctly prompts the user for a positive number, handles non-integer inputs gracefully, and repeats until a valid positive integer is entered, some adjustments are needed.

Specifically, the error handling and feedback messages could be improved for clarity, and the loop should continue prompting the user until a valid positive number is entered.

Here’s how we can revise your code:

def retrieve_positive_number():
    while True:
        try:
            x = int(input("Please enter a positive number: "))
            if x > 0:
                return x
            else:
                print("The value must be positive. Please try again.")
        except ValueError:
            print("An error has occurred. That's not an integer.")

positive_number = retrieve_positive_number()
print(f"You entered: {positive_number}")

Adjustments made in this version:

  • The input function now includes a prompt message for clarity, instructing the user to enter a positive number.
  • Moved the if x > 0: check inside the try block to directly return the positive number when a valid input is received.
  • The error message for a ValueError exception explicitly states that the input wasn’t an integer, aiming to guide the user towards correct input.
  • Added a message to prompt the user again if they enter a non-positive value.
  • After successfully retrieving a positive number, the function will return it, and the caller prints out the positive number that was entered.