If the user input of the following code is 5 for example. Then the output I get is 3 33 333 3333 33333 37035. How can I have my output be 3 33 333 3333 33333=37035.
I've tried sep, end, but can't seem to get it to print the as a separator and the = at the end before the result (=370350).
n = int(input('Enter a positive integer: '))
sequence_number=3
sums = 0
for i in range(n):
print(sequence_number, end=' ') with between each
sums = sums sequence_number # this will add the numbers
sequence_number = sequence_number * 10 3
print(sums)
If you have a better way to write this code im all ears!
CodePudding user response:
You have two options:
- Check if this is the last iteration, and use a space instead of
for i in range(n):
if i == n-1: end_char = ' '
else: end_char = ' '
print(sequence_number, end=end_char)
...
- Append all numbers to a list, and then join them with
lhs = []
for i in range(n):
lhs.append(sequence_number)
...
print(" ".join(lhs), f"= {sums}")
CodePudding user response:
It'd actually be easier to keep your sequence_number
as a string for repetition:
limit = 5
digit = '3'
sequence = [digit * count for count in range(1, limit 1)]
# ['3', '33', '333', '3333', '33333']
total = sum(map(int, sequence))
# 37035
print(f'{" ".join(sequence)}={total}')
# 3 33 333 3333 33333=37035
Some print
statements omitted for brevity.
CodePudding user response:
Use list comprehension and string operations:
lst = [str(sequence_number)*(i 1) for i in range(n)]
>>> "=".join([" ".join(lst),str(sum(map(int,lst)))])
'3 33 333 3333 33333=37035'
CodePudding user response:
Using join
and f-strings to build the actual string you want to print is almost always a better option than messing around with the print
parameters IMO; if nothing else, it makes it easier to reuse the string if you ever need to do something other than print it.
Some other answers have shown how to do this by building a list; I'll show a way to do it with inline generator expressions. Assigning the things you'll be using more than once (namely the stringified sequence_number
and the range
you need to iterate over) to short variable names makes it possible to express it very compactly:
n = range(1, int(input('Enter a positive integer: ')) 1)
s = "3"
print(f"{' '.join(s*i for i in n)}={sum(int(s*i) for i in n)}")
CodePudding user response:
This is a possible solution:
n = int(input('Enter a positive integer: '))
sequence_number = 3
sums = sequence_number
print(sequence_number, end='')
for i in range(1, n):
print(f' {sequence_number}', end='')
sums = sequence_number
sequence_number = sequence_number * 10 3
print(f'={sums}')
Another option:
n = int(input('Enter a positive integer: '))
sequence_number = 3
sums = 0
for i in range(n):
print(sequence_number, end=(' ' if i != n-1 else '='))
sums = sequence_number
sequence_number = sequence_number * 10 3
print(sums)