Traverse a string in Python using while loop is simple, see below code. It’s making sure that the condition is correct in every iteration.
j = 0 while j < len(string): j += 1 print(string[0:j])
Example traversal through a string with a loop in Python
Simple example code. While loop will run until a condition is true, so when
i is equal to the length of the string, the condition is false, and the body of the loop is not executed.
fruit = "Apple" i = 0 while i < len(fruit): print(fruit[i]) i = i + 1
Find out How many times is the letter o printed by the following statements?
s = "python rocks" idx = 1 while idx < len(s): print(s[idx]) idx = idx + 2
Do comment if you have any doubts and suggestions on this Python while loop topic.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.