Introduction to Python


Contents

How to install Python on Linux
How to run a Python program
The basic of Python codes
Data expressions
Built-in functions in Python
Interactive input/output
Conditional statement for Python
Loop structure for Python
Creating your own functions
Python modules
Reading/writing files for Python
Error handling code
Object Oriented Programming (OOP)
Tkinter package for GNU programming


Loop structure for Python

The loop structure for Python is as follows:
sum0=0
for i in [1,3,5,7,9,11,13]:
   sum0 += i
print "The sum is %d.\n", sum0
$ The sum is 49.
This is an equivalent code with above:
sum0=0
for i in range(1,15,2):
   sum0 += i
else:
   print "The sum is %d.\n", sum0
As stated, the indent makes the program different. The following displays the summation each time.
sum0=0
for i in range(1,15,2):
   sum0 += i
   print "Each sum is %d.\n", sum0
$ Each sum is 1.
$ Each sum is 4.
$ Each sum is 9.
$ Each sum is 16.
$ Each sum is 25.
$ Each sum is 36.
$ Each sum is 49.
The command, continue, is used to skip; and break is to go out of the loop:
for k in range(10):
   if k==3:
      continue    print k
$ 0
$ 1
$ 2
$ 3
$ 4
$ 5
$ 6
$ 7
$ 8
$ 9
With dictionary-type data, the method, iteritems(), is to get all of the keys and values; iterkeys() is to get all of the keys; and itervalues() is to get all of the values for the loop process.
d5={"A":100,"B":300,"C":150}
for k,v in d5.iteritems():
   print "key: %s value: %d" %(k,v)
$ key: A value: 100
$ key: C value: 150
$ key: B value: 300
d5={"A":100,"B":300,"C":150}
for k in d5.iterkeys():
   print "key: %s " %k
$ key: A
$ key: C
$ key: B
The command, while, is used as follows:
n=0
while n<10:
   print n
   n += 1
else:
   print "end"
$ 0
$ 1
$ 2
$ 3
$ 4
$ 5
$ 6
$ 7
$ 8
$ 9
$ end



Back to Electronics Page

Back to Hiro's Physics Main