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
Built-in functions in Python
The function, len(), gives the highest number of elements in the list.
For example,
b = "I spent money."
print len(b)
|
You can put a string directly into the function.
To sort the elements of a list, you will use sort command:
c=[1,3,2,4,0]
c.sort()
print c
|
To reverse the elements, use c.reverse().
The following is not exactly a built-in function, but
this arrangement makes sure if there is the
specified element in the array. The output is
either "True" or "False."
print 5 in c
print 3 in c
|
The arguments, 5 and 3, are possible elements in the list, c.
You can also specify a letter or sequence of letters by using find method:
val = "01234567"
print val.find("23")
print val.find("6")
|
The set() command excludes the repeated elements from the list.
aa4=set(["a","b","c","d","a","c"])
print aa4
|
$ set(['a', 'c', 'b', 'd'])
|
The set() enables the data set to be
manipulated by logical operations.
-, |, &, and ^ are difference, union,
intersection, and symmetric difference,
respectively. Define another set:
bb4=set(["a","b","f"])
print aa4-bb4, aa4|bb4, aa4&bb4, aa4^bb4
|
$ set(['c', 'd']) set(['a', 'c', 'b', 'd', 'f']) set(['a', 'b']) set(['c', 'd', 'f'])
|
The range() method creates a sequence of numbers.
$ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
The range() takes 3 arguments; for example,
you can make range(1,7,2). This gives a sequence of
numbers from 1 through 7 by increment 2.
The method, split(), makes a string data list
out of a sequence of letters. For example,
ss="2012/10/12"
aas=ss.split("/")
print aas
|
The method, join(), is an opposite command
to split():
ss1=["a","b","c"]
alle="-".join(ss1)
print alle
|
The tuple and list can be converted mutually by
using methods, list() and tuple().
aa3=(1,2,3)
aaa3=[1,2,3]
bb3=list(aa3)
cc3=tuple(aaa3)
print bb3, cc3
|
The map function is to operate on each element
of a list or a tuple. For example,
import math
print map(math.sin,[0,1,2])
print bb3, cc3
|
Import calls a math module here. The above
gives values of sine of each element.
$ [0.0, 0.8414709848078965, 0.9092974268256817]
|
Let's use the following dictionary data:
it={"p1":20,"p2":100,"p3":35}
|
The methods, keys(), values(), and items() extract
each into another list.
it.keys()
it.values()
it.items()
|
$ ['p2', 'p3', 'p1']
$ [100, 35, 20]
$ [('p2', 100), ('p3', 35), ('p1', 20)]
|
Back to Electronics Page
Back to Hiro's Physics Main