0

My code is here. I am new

what is wrong?

  • Almost all programming languages indexes start with 0 and last this makes last element n-1'th – ikibir Feb 04 '20 at 16:55

4 Answers4

0

The problem is, for a string you also have position 0, what you should be doing is looping from 0,7 and then it should output properly.

str = 'abcdefg'
for i in range(0,7):
    print(str[i])
pm980
  • 123
  • 11
  • In case you didnt know, a is positions 0, b 1, c 2, and so on. This is how it is for strings, lists, etc. – pm980 Feb 04 '20 at 16:55
0

Like many programming languages, index starts from 0 on python. So your code must be:

str = 'abcdefg'
for i in range(0,7):
    print(str[i])
nitnjain
  • 511
  • 3
  • 8
0

As it is already mentioned, in programming, indexing starts at 0. In your code above, having range from 1 to 8 means that you start from the second element (that is b) until the ninth element (which does not exists as your string has a length of 7, from 0 to 6 and thus the error). If you want to print all characters in the string, Python has a built-in len function which takes a variable as an argument and prints its length. So taking into consideration that indexing starts at 0 and the len function, you could modify your range function as following:

str = 'abcdefg'
for i in range(0,len(str)):
    print(str[i])

Note: By convention, when your starting value in range function is 0, you can omit it and write only the end value:

for i in range(len(str)):

Same goes for the step argument, if it's equal to 1. You can read more about range here.

Keep in mind that str is a reserved Python keyword and you should avoid using it.

Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
0
str = 'abcdefg'
for i in range(7):
    print(str[i])

OR

str = 'abcdefg'
for i in range(len(str)):
    print(str[i])

OR

str = 'abcdefg'
for i in str:
    print(i)

Be careful, you'd better not use str as a variable name.

ErnestBidouille
  • 1,071
  • 4
  • 16