1

This is my code for my Computer Science class. I added a feature to make sure the user does not enter a non-int/float. I am trying to access what the users entry to repeat it so it goes like this:

Enter your first number:
> not_a_valid_float_or_int
"not_a_valid_float_or_int" is not a valid number, try again.

So basically I am trying to replace "What you have entered" with what the user had entered.

print("Hello!\n")
while True:
    try:
        firstnumber = float(input("Enter your first number:\n"))
    except ValueError:
        print("\nWhat you have entered is not a valid number, try again.")
    else:
        break
print()
while True:
    try:
        secondnumber = float(input("Enter your second number:\n"))
    except ValueError:
        print("\nWhat you have entered is not a valid number, try again.")
    else:
        break
print("\nThe first number is:", str(firstnumber).rstrip("0").rstrip(".") , "\nThe second number is:", str(secondnumber).rstrip("0").rstrip("."), "\nThe sum is:", str(firstnumber + secondnumber).rstrip("0").rstrip("."), "\nThe product is:", str(firstnumber * secondnumber).rstrip("0").rstrip("."))

Thanks a lot!

David

P.S. please know that I am very knew to the coding scene.

1
  • Store the input string as a variable outside the try/except blocks, then try to use float(), and if an error is caught then you can use that string in the error printing. Commented Oct 12, 2018 at 0:01

1 Answer 1

1

To give you an idea of what the comment means,

while True:
    firstnumber_raw = input("Enter your first number:\n")
    try:
        firstnumber = float(firstnumber_raw)
    except ValueError:
        print("\n'" + firstnumber_raw "' is not a valid number, try again.")
    else:
        break

As a side note, since you tagged Python 3.7, f-string is your friend.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.