0

I am creating a script that calculates the area of a circle from a user input diameter. The input value should be within a defined range.

Is it possible to simplify my script to avoid using multiple while loops, yet still prompt the user for an input until one is given within the acceptable range, while having custom output "errors" based on if the input is negative or too large? Possibly by using while diameter:?

This question is different than the linked duplicate because I would like the user to be reprompted for an acceptable input rather than stopping after a single error.

from math import pi
dlist = (range(1,1000))

diameter = int(input("Please enter a diameter between 0 and 1000: "))

while diameter <= 0:
    print ("Diameter must be positive")
    diameter = (int(input("Please enter a new diameter: ")))

while diameter not in dlist:
    print ("Diameter must be less than 1000")
    diameter = int(input("Please enter a new diameter: "))

else:
    area = (pi*(diameter*0.5)**2)
    print ("diameter:", diameter,"area:",area)
sjosida
  • 1
  • 1
  • Use `while diameter <= 0 or diameter not in dlist: ...` using the or keyword will re-trigger the loop on either condition, I believe that's what you're wanting to do? – mhodges Nov 02 '16 at 20:46
  • 1
    This works if I have a catch-all output as `print ("Diameter must be between 0 and 1000")` Though I would like to have personal outputs depending on which condition it fails (ex. negative or too large) – sjosida Nov 02 '16 at 20:54
  • Yeah, you can either put logic in for your error message output, or you can make a generic error message that states both error conditions: "Diameter must be positive and less than 1000", or something to that effect – mhodges Nov 02 '16 at 20:56
  • Try this: https://repl.it/ENJS/2 – mhodges Nov 02 '16 at 21:14
  • Thank you @mhodges for the link. This is what I was envisioning. For posterity I will state what I did incorrectly when attempting the same solution earlier: line6 I typed `while diameter <=0 or not in dlist:` instead of `while diameter <=0 or diameter not in dlist:` I also put `diameter = int(input("Please enter a new diameter: "))` in line11 instead of line7. – sjosida Nov 02 '16 at 21:15
  • FYI check the edited link above. I modified it slightly to include the error handling that the linked question mentioned – mhodges Nov 02 '16 at 21:19

0 Answers0