My code is here. I am new
what is wrong?
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])
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])
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.
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.