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
Data expressions
There is a tuple consisting of a number of values
separated by commas. The set of the values
are bundled by parentheses.
Each element can be displayed, but it cannot be
replaced by another value.
The following is an example of tuple:
There is another type that is called list.
An element of a list can be replaced by
another value. That is bundled by square brakets.
Each element of a list is independent. Let us perform following:
a=[4,"t",8.3e-2]
b=[7,"u",2.6e2]
print a,b,a+b,a[1]
|
The output is:
$ [4, 't', 0.083] [7, 'u', 260.0] [4, 't', 0.083, 7, 'u', 260.0] t
|
There is also a convenient expression. Suppose you have
a string:
The numbers and collon specify the sequence of the data.
The result is:
The other cases are:
print s[:4]
print s[1]
print s[1:-1]
print s[1:]
print s[1:4]
|
Each output is:
$ abcd
$ b
$ bcdefgh
$ bcdefghi
$ bcd
|
There is a dictionary that can register two elements as an item.
Each element is called key and value, respectively. The data set
is bundled by curly brakets:
aa5={"value":200,"price":300,"quality":350}
|
Once you specify one of the keys, the value will be returned
automatically. Note that you have to use square brakets for this
command:
A value of the key can be replaced as follows:
aa5["price"]=150
print aa5
|
$ {'price': 300, 'quality': 150, 'value': 200}
|
Let's prepare for 3 types of data:
aa6=80.5
bb6="Hiro"
cc6={"Hiro":100,"physics":120}
|
The print command has format options.
%d, %f, %s and %x format integer, float,
string, and hexadecimal respectively.
For example,
print "I weigh %f kilograms." %aa6
print "My name is %s." %bb6
print "%s has %d dollars." %(bb6,aa6)
|
The above returns:
$ I weigh 80.500000 kilograms.
$ My name is Hiro.
$ Hiro has 80 dollars.
|
You can also extract a value from the dictionary data
for output:
To format the number of figures you want to display,
print "I drive at %0.8f miles/h." %(80.0/2.2)
|
This gives 8 digits after the decimal point as follows:
$ I drive at 36.36363636 miles/h.
|
Back to Electronics Page
Back to Hiro's Physics Main