Reputation: 435
I want to print "Same number" if the new number value equals to the last one(same number), else print number variable value if it has changed. How can I do that?
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)
Upvotes: 1
Views: 15616
Reputation: 1
I have a different method:
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
Output:
Diffrent (Last: 6 Now: 9)
Diffrent (Last: 9 Now: 0)
Diffrent (Last: 0 Now: 2)
Same number (2)
Diffrent (Last: 2 Now: 6)
Same number (6)
Diffrent (Last: 6 Now: 7)
Diffrent (Last: 7 Now: 4)
Same number (4)
Diffrent (Last: 4 Now: 10)
Upvotes: 0
Reputation: 99
You just need a third variable. Within the "else" after the print statement, set this third variable to "number".
Upvotes: 0
Reputation: 604
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)
Upvotes: 0
Reputation: 42678
Just save the last one:
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)
Upvotes: 0
Reputation: 11477
You can chage last number in the while loop:
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
Output:
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
Upvotes: 1