Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Back to loops question
#1
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
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Old brain - New Language - Question on loops sailingbikeruk 6 3,984 Oct-03-2018, 08:27 PM
Last Post: nilamo
  Question on runtime and improving nested for loops ackmondual 1 3,042 Jun-13-2017, 11:11 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020