Python Forum

Full Version: Back to loops question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys,

I want to write a program which takes a series of numbers finishing the process with 0. The program results should be as follow:

Enter the first number: 3
Enter the next number: 5
Enter the next number: 4
Enter the next number: 4
Enter the next number: 6
Up Down Same Up

However, I don't know how to write the code which produces the above result (Up Down Same Up) at the end.

Could anyone help me with this question please?

The following is my current code:

print("Enter the first number: ", end='')
s=input()
number1=int(s)
finished=False
while not finished:
   print("Enter the next number: ", end='')
   a=input()
   number2=int(a)
   if number2!=0:
       if number1>number2:
           print("Down")
       if number1==number2:
           print("Same")
       if number1<number2:
           print("Up")
       number1=number2
   else:
       finished=True
You pretty much have it, you just need to save the up/down/sames until the end. What I would do is start with an empty list. Each time you are print a word, append it to the list instead:

>>> count = [1, 2]
>>> count.append(5)
>>> count
[1, 2, 5]
Then you need to print the words. You could just loop through them, printing each one with end = ' ', or you could join them and print once:

>>> ' '.join(['spam', 'spam', 'eggs'])
'spam spam eggs'


I would also change your if's for same and up to elif (short for else if). Then they will only be checked if none of the previous conditions have been met. This is more efficient, and is necessary if you conditions overlap and you only want one to execute.