-1

eg.

name = 'python'
length = len(name)
i = 0
for n in range(-1,(-length-1), -1):
    print( name[i], '\t', name[n])
    i+ = 1

I remove the i+ = 1 which generates a semantic error. I'm a beginner and am using the python tutorial provided by the python website. Basically I'm practicing forward and backward indexing.

name = 'python'
length = len(name)
i = 0
for n in range(-1,(-length-1), -1):
    print( name[i], '\t', name[n])
    i+ = 1

I'm expecting it to run an output of the name forward then backwards

GBlodgett
  • 12,704
  • 4
  • 31
  • 45
  • The loop is irrelevant. This program fails: `i = 0; i+ = 1`. So what should `i+ = 1` be changed to *validly* "increment the value of a variable"? - https://stackoverflow.com/a/1485854/2864740 – user2864740 May 08 '19 at 16:08
  • 6
    Do `i += 1` instead – mickey May 08 '19 at 16:09
  • 1
    Davis, next time try to isolate your problems. Simply typing ```i+ = 1``` on python interpreter gives you the same error, and you already knew the problem was somewhat related to that. This is a good technique to find where the real problem is. – Lovato May 08 '19 at 16:38
  • Apart from `i += 1`, you can also simplify for for loop a lot @DavisPaggett – Devesh Kumar Singh May 09 '19 at 14:42

5 Answers5

2

Your error lies in your i+ = 1 statement, which should be i += 1

Try this:

name = 'python'
length = len(name)
i = 0
for n in range(-1,(-length-1), -1):
    print( name[i], '\t', name[n])
    i += 1
artemis
  • 6,857
  • 11
  • 46
  • 99
2

There should be no blank space between the + and =.

i += 1
Amir H. Bagheri
  • 1,416
  • 1
  • 9
  • 17
0

You can not arbitrarily spread spaces through your code. Certain tokens that Python recognizes have to be written exactly as they are documented. This is true for e.g. class that you can't write cl a ss, and it's also true for what you are using here wich is called an operator. It needs to be written +=, the same way == can't have a space in it etc.

deets
  • 6,285
  • 29
  • 28
0

As other commenters have already pointed out, the += is used as a += b and not a+ = b, which the case you have when you do i+ = 1
For simplicity, and since you say you are a beginner, might I suggest using i = i+1 instead.

In addition, you can also simplify your for loop by using length attribute to calculate the index from the end of the string. range(length) is the same as doing range(0,length,1)

name = 'python'
length = len(name)

i = 0
for i in range(length):
    print(name[i], '\t', name[length-i-1])
    i += 1

The output will be

p    n
y    o
t    h
h    t
o    y
n    p
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
-1

avoid space between + and =

use i+=1 instead i+ =1

refer here: Behaviour of increment and decrement operators in Python

Shiva
  • 476
  • 3
  • 15