2

I'm trying to write Python code for the above problem and getting an error code. I would appreciate help:

num = list(range(10))
previousNum = 0
for i in num:
    sum = previousNum + i
    print('Current Number '+ str(i) + 'Previous Number ' + str(previousNum) + 'is ' + str(sum)
    previousNum=i

This is the error I get:

File "<ipython-input-40-6f1cd8f8f1d7>", line 6
    previousNum=i
              ^
SyntaxError: invalid syntax
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Haseeb Haque
  • 25
  • 1
  • 1
  • 5

4 Answers4

1

Looks to be a simple syntax error in line 5.

You're missing a closing parenthesis ")" at the end of your print function.

For example:

num = list(range(10))
previousNum = 0
for i in num:
    sum = previousNum + i
    print('Current Number '+ str(i) + 'Previous Number ' + str(previousNum) + 'is ' + str(sum)) # <- This is the issue.
    previousNum=i

Also, here are 3 pointers to improve your code that might be useful for you:

  1. First off, Python uses snake case for it's language as described in PEP8, so instead of typing "previousNum" you should use "previous_num", so we'll start with that.

  2. Storing list(range(1)) in this instance isn't needed. You can just use the ```range(10)''' function in place of having a stored list of ranges.

  3. f strings are much more readable ways of doing String Concatenation (adding strings together).

With these your code will look like this:

previous_num = 0
for i in range(10):
    sum = previous_num + i
    print(f'Current number {i} Previous Number {previous_num} is {sum}')
    previous_num = i

Happy coding!

Zack Plauché
  • 3,307
  • 4
  • 18
  • 34
0
sum = 0
for idx in range(10):
    print(f'current number = {idx}')
    if idx != 0:
        sum += idx
        print(f'cumul. sum = {sum}')
  • 3
    Please don't post only code as an answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually of higher quality, and are more likely to attract upvotes. – ilke444 Apr 13 '20 at 06:42
0

Welcome to Stackoverflow. There's always functional python:

>>> list(map( lambda x: x[0] + x[1], zip(range(0,10), range(1,11))))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Or if you meant a cumulative sum of predecessors, like a reduce:

>>> [sum(range(xs)) for xs in range(1,11)]
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]

This used to be easier in python 2, before range, filter, and map were turned into iterators.

Mittenchops
  • 18,633
  • 33
  • 128
  • 246
0
for i in range(1,10+1):
   print(i+i-1, end=' ')

Here it iterates from 1 to 10 inclusively. It prints the value of sum of current value of i and the previous value that is i-1