This introduces a whole lot of new ideas that I shall briefly point out.#!/usr/bin/python3.5for i in range(10):print ("Hello World")
- It is a for loop. Put simply, a for loop goes through a set of instructions a certain number of times. The i is a variable that here simply stands for each time the loop is repeated. Think of it as standing for instance or iteration.
- The in keyword tells Python this is the list or range of items that the for loop is working through
- range is another keyword that tells Python a range of numbers is coming up or to create a range of numbers. In this case range(10) tells it to create the range of integers (whole numbers) up to 10.
- The colon and the indent are important parts of Python syntax - unlike a lot of programming languages such as Perl or Java where indenting the script is purely for human benefit, in Python the indents tell the interpreter where the instructions to be run for each cycle of the loop start and end.
>>>And hey presto, we have instructed the computer to print "Hello World" out 10 times!
RESTART: C:\Users\John\Dropbox\Misc Programming\Python\python3\test02_for_loop.py
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
>>>
There is something this script doesn't show - namely that the range of numbers created is not actually 1 to 10, but 0 to 9. This can catch a lot of new programmers out (including myself). By default, Python lists and ranges start at 0 rather than 1. This can be demonstrated by modifying the final line of the script so that it prints out i with each iteration of the loop:
gives the output in IDLE:#!/usr/bin/python3.5for i in range(10):
print (i, "Hello World")
>>>
RESTART: C:/Users/John/Dropbox/Misc Programming/Python/python3/test02a_for_loop.py
0 Hello World
1 Hello World
2 Hello World
3 Hello World
4 Hello World
5 Hello World
6 Hello World
7 Hello World
8 Hello World
9 Hello World
>>>
No comments:
Post a Comment