Home > database >  Problems with the formatting
Problems with the formatting

Time:11-09

Write a program that requires users to enter integers, each in a separate line. The user indicates the end of the entry in a blank line. The program prints negated values. The program prints values ​​in the same line separated by a space.

n = input()
while n != "":
    n = int(n)
    print(-n, end=" ")
    n = input()
print(-n, end=" ")

This code works, but it needs help with the formatting. The input should look like this:

  • 5
  • 0
  • -11

The output should look like this: -5 0 11 -2

CodePudding user response:

Since you want to input all values first and then print you need save them all to a list. Then, print them out after you're doing inputting. You can do this by using join(), but note that you must convert from str to int and back to str with this.

all_nums = []
n = input()
while n != "":
    all_nums.append(str(-int(i)))
    n = input()
print(" ".join(all_nums))

Instead, if you would like to print the numbers out with a normal loop you can do this

all_nums = []
n = input()
while n != "":
    all_nums.append(-int(i))
    n = input()
for i in all_nums:
    print(i, end=" ")
  • Related