Home > Blockchain >  Printed the code insufficient number of times
Printed the code insufficient number of times

Time:10-01

so I am a total beginner in programming and and I use Pycharm and when i put the following:

ListName = "hello world"
for i in ListName:
    print(ListName) 

code gave me "hello world" but repeated it 11 times, and when i tried the same with another variable, it got repeated 13 times, i do not know if its a setting problem because when i tried simple

print("hello world") it was the usual response. If someone is familiar with Pycharm, please enlighten me as your newbie junior

CodePudding user response:

it should not be depended on the variable you using only on the value of it. check out below codes how does they run.

ListName = "hello world"
count = 0
for i in ListName:
   count = count 1
   print(ListName,count)

x = "Hello world"
count = 0
for i in x:
   count = count 1
   print(i,count)

CodePudding user response:

When you type for i ListName:, python treats the string that ListName is holding as an iterable. It iterates through the string letter by letter. The variable i will store the corresponding letter at each iteration. However, the line print(listName) does not reference the variable i which is holding a single letter. Instead it simply prints the entire string stored in listName at each iteration. And since there are 11 characters in the string "hello world", the loop runs 11 times.

As pointed out in the comment, it will help you to understand what is going on if you run:

for i in listName:
    print(i)
  • Related