2017-02-16 64 views
0

我是Python的新手,我即将到来的实验室要求我为平面上的对象(圆圈)的碰撞测试编写代码。对于两个圆圈,我提示用户输入x和y坐标的值以及两者的半径。目前,我已经设置了它,以便如果用户忽略为三个输入中的任何一个输入值,它将使用while循环返回一条错误消息。这工作正常。Python中嵌套while循环的两个条件?

但是,我也想设置它,使得半径不能小于或等于零。我使用了一个嵌套的while循环。这是我的代码:

while c_1_x=="" or c_1_y=="" or c_1_r=="": 
    print "Error: please enter a value for each field. If the value is 0, type 0." 
    c_1_x=raw_input("Enter the x coordinate of CIRCLE ONE center:") 
    c_1_y=raw_input("Enter the y coordinate of CIRCLE ONE center:") 
    c_1_r=raw_input("Enter the radius of CIRCLE ONE:") 
    while int(c_1_r<=0): 
     print "Error: radius of circle must be greater than zero." 
     c_1_r=raw_input("Enter the radius of CIRCLE ONE:") 

外环已满足后,我希望它分析内循环。如果半径的值是< = 0,我希望它返回一条错误消息。但是,当我运行它时,即使在输入值后(特别是半径值< = 0),它也会继续执行下一步。我不希望它继续下一步,直到符合BOTH标准。我怎样才能做到这一点?

非常感谢!我很感激!

+0

变化括号'而INT(c_1_r)<= 0:'! – schwobaseggl

+0

谢谢你的回答!虽然我更喜欢Martijn的方法,但这确实做了我想要的! –

回答

2

您的正整数测试是有缺陷的:

int(c_1_r<=0) 

此转换布尔结果<=运营商的整数。你永远不会将c_1_r转换成一个整数,所以你在那里比较字符串0。这将始终是假的,因为在Python 2,数字串排序前:

>>> 'Foobar' <= 0 
False 
>>> '-10000' <= 0 
False 

每个变量,而不是重复测试,使用一个单独的函数来处理的这些数字的任何输入。在所有条件都满足之前,不要再要求另一个号码。 (通过使用break或使用return从功能)当输入满足您的使用条件下无限while循环您摆脱:

def ask_for_positive_number(prompt): 
    while True: 
     try: 
      number = int(raw_input(prompt)) 
     except ValueError: 
      print('Please enter a valid positive integer') 
      continue 
     if number <= 0: 
      print('Please enter a valid positive integer') 
      continue 
     return number 

c_1_x = ask_for_positive_number("Enter the x coordinate of CIRCLE ONE center:") 
c_1_y = ask_for_positive_number("Enter the y coordinate of CIRCLE ONE center:") 
c_1_r = ask_for_positive_number("Enter the radius of CIRCLE ONE:") 

从什么时候开始已经进入了一个正整数的功能将只返回,没有必要测试所有3个变量是否具有赋值。

演示功能:

>>> ask_for_positive_number('Y0!: ') 
Y0!: -1 
Please enter a valid positive integer 
Y0!: foobar 
Please enter a valid positive integer 
Y0!: 42 
42 
+0

谢谢!在阅读您的评论并引用Python的网站之后,这是有道理的。这段代码体积小得多,完成了工作! –

+0

@Chrispy_Chreme一旦你做了同样的事情超过2次,它可能是一个更好的主意,做一个单独的功能,因为你可能会再次使用它。 – PinkFluffyUnicorn

+0

@Chrispy_Chreme:很高兴有帮助!如果您觉得它对您有用,请随时[接受我的回答](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 :-) –