Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Other answers have already given you the code you need to iterate though a string using a <code>while</code> loop (or a <code>for</code> loop) but I thought it might be useful to explain the difference between the two types of loops.</p> <p><code>while</code> loops repeat some code until a certain condition is met. For example:</p> <pre><code>import random sum = 0 while sum &lt; 100: sum += random.randint(0,100) #add a random number between 0 and 100 to the sum print sum </code></pre> <p>This code will keep adding random numbers between 0 and 100 until the total is greater or equal to 100. The important point is that this loop could run exactly once (if the first random number is 100) or it could run forever (if it keeps selecting 0 as the random number). We can't predict how many times the loop will run until after it completes.</p> <p><code>for</code> loops are basically just while loops but we use them when we want a loop to run a preset number of times. Java <code>for</code> loops usually use some sort of a counter variable (below I use <code>i</code>), and generally makes the similarity between <code>while</code> and <code>for</code> loops much more explicit.</p> <pre><code>for (int i=0; i &lt; 10; i++) { //starting from 0, until i is 10, adding 1 each iteration System.out.println(i); } </code></pre> <p>This loop will run exactly 10 times. This is just a nicer way to write this:</p> <pre><code>int i = 0; while (i &lt; 10) { //until i is 10 System.out.println(i); i++; //add one to i } </code></pre> <p>The most common usage for a for loop is to iterate though a list (or a string), which Python makes very easy:</p> <pre><code>for item in myList: print item </code></pre> <p>or</p> <pre><code>for character in myString: print character </code></pre> <p>However, you didn't want to use a <code>for</code> loop. In that case, you'll need to look at each character using its index. Like this:</p> <pre><code>print myString[0] #print the first character print myString[len(myString) - 1] # print the last character. </code></pre> <p>Knowing that you can make a <code>for</code> loop using only a <code>while</code> loop and a counter and knowing that you can access individual characters by index, it should now be easy to access each character one at a time using a <code>while</code> loop.</p> <p><strong>HOWEVER</strong> in general you'd use a <code>for</code> loop in this situation because it's easier to read.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload