For Loop
For Loop
Here, variable is a name that you can choose, and sequence is an object that can be
iterated over, such as a list, a tuple, a range, or a string. (The # symbol indicates a
comment, which is ignored by Python.)
The for loop works by assigning the first item of the sequence to the variable,
then executing the block of code inside the loop. Then, it assigns the next item of the
sequence to the variable, and repeats the process until there are no more items left
in the sequence.
Here, i is the variable name that we chose, and range(6) is a built-in function
that returns a sequence of numbers from 0 to 5 (remember that index always starts
at 0). The print(i) statement inside the loop prints the value of i on each iteration.
Additional:
1. I know, most of you have a boyfriend or girlfriend, so how about your gf/bf wants
you to message "I miss you!" 12 times? So here it is.
The output is:
2.
So
what if your gf/bf is in doubt, asking if it's really 12/100? You can put numbers before
the message.
4. If you really want it to start with 1, you can add “+ 1” after the “number”.
You can also use a for loop to iterate over a list of strings:
Example:
So here, what it should print is 1, 2, 3, 4, 5, but since there is "number * 2" written on
it, it times 1, 2, 3, 4, 5 by 2, so 2, 4, 6, 8, 10 is the result.
You can also use a for loop to iterate over the characters of a string:
Example:
The output is:
So here, it will print the value (Python) but each character in each line.
Example 2:
You can print random letters.
3. You can create a word with your value (which is the random letter) as long as the
words you chose are only different in the first letter. For example - cat, bat, rat, etc.