1

This is a homework assignment I'm having trouble on. Here's the problem:

Implement a function dartGame() that requests the user to enter x and y coordinates (each between -10 & 10) of a dart and computes whether the dart has hit the dartboard, a circle with center(0,0) and radius 8. If so, a string ‘It is in! :-)’ is printed, else ‘It isn’t in. :-(’ is printed. Note that the equation for a circle is x2 + y2 = r2; to make certain that the dart hits the board, the formula is x2 + y2 <= 82

>>> dartGame()
Enter x: 4
Enter y: 2.5
It is in! :-)
>>> dartGame()
Enter x: 9.9
Enter y: -9.9
It isn't in. :-(
>>>

Here's the code I've attempted. What I'm trying to do is ask the user for an input x. If x < -10 or x > 10 I want the function to keep asking for input until the parameters are met. Once an x coordinate is established I want to do the exact same thing with y. I'm having an issue where my first while loop repeats infinitely if I guess a number out of range once. For instance, if I guess -13 it repeats, but then if I guess 4.5 it still repeats.

def dartGame():
    x = float(input("Enter  x: ", ))
    while x < -10 or x > 10:
            float(input("Out of range. Please select a number between -10 and 10: ", ))        
    y = float(input("Enter y: ", ))
    while y < -10 or y > 10:
            float(input("Out of range. Please select a number between -10 and 10: ", ))
    dartboard = x**2 + y**2
    if dartboard <= 8**2:
        print("It is in!")
    else:
        print("It isn't in. :-(")
c4llmeco4ch
  • 311
  • 2
  • 11
Pallu08
  • 25
  • 6
  • Because you never reassign `x` or `y` within the `while` loop. They still retain their original values. – Selcuk Oct 10 '19 at 05:35
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – rdas Oct 10 '19 at 05:39

2 Answers2

0

Inside your validation check while loops, you aren't assigning your new inputs to x and y respectively. So you'd want:

while x < -10 or x > 10:
    x = float(input('''stuff'''))

And the same with y. In other words, you are constantly just looping an input without updating the exit conditions. It's why it works for the first time but no time after.

c4llmeco4ch
  • 311
  • 2
  • 11
0

You should assign the value for x and y inside the while loop

def dartGame():
    x = float(input("Enter  x: ", ))
    while x < -10 or x > 10:
            x = float(input("Out of range. Please select a number between -10 and 10: ", ))        
    y = float(input("Enter y: ", ))
    while y < -10 or y > 10:
            y = float(input("Out of range. Please select a number between -10 and 10: ", ))
    dartboard = x**2 + y**2
    if dartboard <= 8**2:
        print("It is in!")
    else:
        print("It isn't in. :-(")
MagnumCodus
  • 171
  • 1
  • 11