如果用户输入不在范围内,如何使用while循环?

2024-09-30 18:15:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个我很难完成的家庭作业。问题是:

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. :-(
>>>

这是我尝试的代码。我要做的是请求用户输入x。如果x < -10 or x > 10,我希望函数一直请求输入,直到满足参数。一旦建立了x坐标,我想对y做完全相同的事情。我的第一个while循环会无限重复,如果我猜一个超出范围的数字。例如,如果我猜-13它会重复,但是如果我猜4.5它仍然会重复。你知道吗

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. :-(")

Tags: andoftheininputthatisit
2条回答

在验证检查while循环中,没有将新输入分别分配给x和y。所以你想:

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

也就是说,你总是循环输入而不更新退出条件。这就是为什么它第一次起作用,但之后就不起作用了。你知道吗

应该在while循环中为x和y赋值

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. :-(")

相关问题 更多 >