As with all other scripting languages, Python has its own set of control structures that allow you to determine a path thru which the execution of a script will proceed:
if 1 == 2 :
print 'One equals two'
print 'One does not equal two'
As you can see, no braces are used -- just indenting. This promotes readable code:
if 1 < 2 :
print 'One is lesser than two'
elif 1 > 2 :
print 'One is greater than two'
Loops allow you to iterate (repeat) a set of commands using a different set of values each time that command is executed. A simple loop looks like this in Python:
for i in range(0, 10) :
if i % 2 == 0 :
print i, 'is an even number'
print i, 'is an odd number'
This example will loop through the numbers from 0 to 10 and test if the number is odd or even. The modulus operator (%) is used to calculate the remainder left after dividing the number by two.
This same example can also be rewritten as a while loop.
i = 0
while i <= 10 :
if i % 2 == 0 :
print str(i) + ' is an even number'
print str(i) + ' is an odd number'
i += 1
i = 'Hello world'
This example also shows that even though Python's variables are loosely typed (you can assign any type of data to a single variable), you do have to convert them to a single type if you want to operate on different kind of variables.
To save the space that print adds between different parameters passed to it, you also have to add it to the string (when using string concatenation).
If you want to pass parameters from the command line to your Python script, then you will need the sys module, which is imported on the first line of the example shown below. The module defines the argv list, which, as all of you C/C++ programmers will know, contains the arguments that are passed from the command-line to the script:
print sys.argv # prints the filename of your script
print sys.argv # and the first parameter
print sys.argv[1:] # or all parameters
blog comments powered by Disqus