Python while循环(编码练习,三个变量)

时间:2017-06-28 03:44:43

标签: python python-3.x debugging while-loop

由于我是一名全面的编程新手,我需要您就在线课程中需要完成的编码练习提出建议。

以下是指示:

mystery_int_1 = 3

mystery_int_2 = 4

mystery_int_3 = 5
 (这些将在我提交代码后更改,因此它只是一个示例)

以上是三个值。运行while循环,直到所有三个值都小于或等于0.每次更改三个变量的值时,都要在同一行上打印出新值,用单个空格分隔。例如,如果它们的值分别为3,4和5,则代码将打印:

2 3 4

1 2 3

0 1 2

-1 0 1

-2 -1 0

我试着这样写:

while not mystery_int_1 <= 0 and not mystery_int_2 <= 0 and not mystery_int_3 <= 0: 
    mystery_int_1 -= 1
    mystery_int_2 -= 1
    mystery_int_3 -= 1
    print(mystery_int_1, mystery_int_2, mystery_int_3) 

运行代码后,我意识到它有问题,但我无法弄清楚如何修改它。尝试了很多选择,但它们都没有像预期的那样工作......

提前谢谢大家!

5 个答案:

答案 0 :(得分:3)

您的循环当前循环,直到任何的数字小于或等于零。大声说出来,你的循环是“当mystery_int_1不小于或等于零 mystery_int_2不小于或等于零 ...”,因此,如果 小于或等于零,则循环停止。

你想要这个:

while not (mystery_int_1 <= 0 and mystery_int_2 <= 0 and mystery_int_3 <= 0):

或者这个:

while mystery_int_1 > 0 or mystery_int_2 > 0 or mystery_int_3 > 0:

或者可能这样,虽然我发现这个版本最令人困惑。 (也就是说,它与你已经拥有的最接近。)

while not mystery_int_1 <= 0 or not mystery_int_2 <= 0 or not mystery_int_3 <= 0:

答案 1 :(得分:0)

试试这个 -

while not mystery_int_1 <= 0 or not mystery_int_2 <= 0 or not mystery_int_3 <= 0: 
   mystery_int_1 -= 1
   mystery_int_2 -= 1
   mystery_int_3 -= 1
   print("{} {} {}".format(mystery_int_1, mystery_int_2, mystery_int_3))

Read python and AND `or

答案 2 :(得分:0)

你的条件while not mystery_int_1 <= 0 and not mystery_int_2 <= 0 and not mystery_int_3 <= 0说的是循环,而所有这些条件都是真的(因为和使用过。)

  • mystery_int_1大于0
  • mystery_int_2大于0
  • mystery_int_3大于0

当其中一个数字低于0时,一个条件变为false,但循环条件要求所有这些条件为真,因此它会停止执行。您可能希望将and替换为or。因此,循环继续,直到其中一个变量仍大于0。

答案 3 :(得分:0)

打开python解释器并尝试以下操作,

假设我有一个值为2

的数字
>>> number = 2
>>> number-=1  #2-1=1
>>> number
1

现在让我们检查数字是否> = 0

>>> number>=0
True

是的!是真的。因为数字大于0. 这就是你应该做的。检查数字是否> = 0。但相反你正在做,

>>> not number<=0
False

意味着你正在做与你应该做的完全相反的事情,

>>> number-=2
>>> number 
-1    #now number has become -1

>>> number>=0
False
>>> not number<=0
True

因此,通过添加额外的not,您只需要执行与您想要的完全相反的操作。所以在你的情况下,这就足够了:

while mystery_int_1 > 0 or mystery_int_2 > 0 or mystery_int_3 > 0:

看看这个:

value=1
value1=2
value2 =3
while value or value2 or value1:
    print("looop")

打印infinte times looop

value=0
value1=2
value2 =3
while value and value2 and value1:
    print("looop")

但是这不会执行,因为一个值是0。在python中,您不必检查是否value>=0。当值为0时,其本身被认为是假的。所以你可以这样做:

while mystery_int_1 or mystery_int_2 or mystery_int_3:

这里即使一个值为not 0,即>=0循环也会运行。只有在其中一个值为0时才会退出。

以下是完整的代码:

mystery_int_1 = 3
mystery_int_2 = 4
mystery_int_3 = 5 
while mystery_int_1 or mystery_int_2 or mystery_int_3: 
    mystery_int_1 -= 1
    mystery_int_2 -= 1
    mystery_int_3 -= 1
    print(mystery_int_1, mystery_int_2, mystery_int_3) 

输出:

2 3 4
1 2 3
0 1 2
-1 0 1
-2 -1 0

答案 4 :(得分:0)

您可以尝试以下代码:

 while not (mystery_int_1<=0 and mystery_int_2 <=0 and mystery_int_3<=0):

    mystery_int_1 -= 1
    mystery_int_2 -= 1
    mystery_int_3 -= 1

    print(mystery_int_1, mystery_int_2, mystery_int_3)
相关问题