Python如何检查值是否更改

时间:2017-03-10 08:16:34

标签: python

我想要打印#34;相同数字"如果新的数字值等于最后一个(相同的数字),否则打印数字变量值(如果已更改)。我怎么能这样做?

from random import randint
x=0
number=(randint(0,9))
while(x<10):
    x+= 1
    if(number=="""LAST PRINTED VALUE NUMBER"""):
        print ("Same number")
    else:
        print(number)

5 个答案:

答案 0 :(得分:1)

您可以在while循环中查找最后一个数字:

x, last = 0, -1
while (x < 10):
    number = randint(0, 9)
    if (number == last):
        print ("Same number")
    else:
        print("Last number is {0} now it is {1}".format(last,number))
    last = number
    x += 1

输出:

Last number is -1 now it is 1
Last number is 1 now it is 2
Last number is 2 now it is 4
Same number
Last number is 4 now it is 2
Last number is 2 now it is 6
Last number is 6 now it is 7
Same number
Last number is 7 now it is 2
Same number

答案 1 :(得分:0)

只保存最后一个:

from random import randint
x=0
old = number= randint(0,9)
while(x<10):
    x+= 1
    if(number==old and x > 0):
        print ("Same number")
    else:
        print(number)
    old = number
    number = randint(0,9)

答案 2 :(得分:0)

from random import randint
x = 0
number = -1
while(x < 10):
    y = number
    number=(randint(0,9))
    x+= 1
    if(number== y):
        print ("Same number")
    else:
        print(number)

答案 3 :(得分:0)

您只需要第三个变量。在print语句后的“ else”中,将第三个变量设置为“ number”。

答案 4 :(得分:0)

我有另一种方法:

pub run build_runner test

输出:

from random import randint
new = randint(0, 10)
old = new
for i in range(10):
    new = randint(0, 10)
    if new == old:
        print("Same number  ({0})".format(new))
    else:
        print("Diffrent     (Last: {0} Now: {1})".format(old, new))
        old = new