Home > Mobile >  Program that prompts the user to input 5 integers and outputs these integers in reverse order
Program that prompts the user to input 5 integers and outputs these integers in reverse order

Time:10-29

I need help with this Python program.

With the input below:

Enter number: 1​
Enter number: 2​
Enter number: 3​
Enter number: 4​
Enter number: 5​

the program must output:

Output: 54321​

My code is:

n = 0
t = 1
rev = 0
 
while(t <= 5):
    n = int(input("Enter a number:"))
    t =1
    a = n % 10
    rev = rev * 10   a
    n = n // 10
print(rev)

Its output is "12345" instead of "54321".
What should I change?

CodePudding user response:

try this:

t = 1
rev = ""
 
while(t <= 5):
    n = input("Enter a number:")
    t =1
    rev = n   rev

print(rev)

CodePudding user response:

Try:

x = [int(input("Enter a number")) for t in range(0,5)]
print(x[::-1])

CodePudding user response:

There could be an easier way if you create a list and append all the values in it, then print it backwards like that:

my_list = []
while(t <= 5):
    n = int(input("Enter a number:"))
    t =1
    my_list.append(n)
my_list.reverse()
for i in range(len(my_list)):
    print(my_list[i])

CodePudding user response:

You can try this:

n = 0
t = 1
rev = []
 
while(t <= 5):
    n = int(input("Enter a number:"))
    t =1
    rev.append(n)
rev.reverse()
rev = ''.join(str(i) for i in rev)
print(rev)

CodePudding user response:

Use operator "10 to the t power"
This code is not very different from your solution because it works on the integer numbers and return rev as an integer:

t = 0
rev = 0

while (t < 5):
    n = int(input("Enter a number:"))
    # ** is the Python operator for 'mathematical raised to'
    rev  = n * (10 ** t)
    t  = 1
print(rev)

(10 ** t) is the Python form to do 10^t (10 raised to t); in this context it works as a positional shift to left.

With this program happens that: if you insert integer 0 as last value, this isn't present in the output.

Example: with input "12340" the output is "4321".

  • Related