Table of Contents• Introduction • The “Not-So-Full” Monty – Mechanics of using Python – Variables, Data Types and Operators... To use Python: Interactive• Type python in a shell window a
Trang 1Python Programming
Science & Technology
Trang 3Table of Contents
• Introduction
• The “Not-So-Full” Monty
– Mechanics of using Python
– Variables, Data Types and Operators
Trang 4What is Python?
• NOT an acronym (Thank goodness!) Named after Monty Python
• A compiled/interpreted mid-level language
– Not only used for scripting tasks
• Extremely useful for a huge variety of programming tasks (Modules)
• Easy to “glue” with other languages (C, C++, Java …)
• Under the hood: Object Oriented
• Commonly in use: Versions 2.3 and 2.4
– Use python –V to see the version
• Python is portable
• Python is free!
• Home Page: www.python.org
Trang 5Basic Operation
• Python is both an interpreted and a compiled language
• When run, the program is first read and “compiled” in memory
– Not a true compilation to native machine instructions
– Python source code converted to byte code (platform-independent)
– Some optimizations are performed, e.g.
• eliminating unreachable code
• reducing constant expressions
• loading library definitions
• Second stage is line-by-line execution via the interpreter PVM (Python Virtual
Trang 6Running Python
Trang 7To use Python: Interactive
• Type python in a shell window and start typing in commands at the Python prompt >>> The results of the commands will be seen immediately
• Workshop examples will be for Python on Unix/Linux system
[piv-login1]% python
Python 2.2.3 (#1, Feb 2 2005, 12:20:51)
[GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-49)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> print "Hello World! (with respect)“ #Basic output command
Hello World! (with respect)
>>> a=34.5 # No variable type declaration
>>> a # To see contents of variable, type its name
Trang 8Ways to use Python: Shell Scripts
• A shell script is just a series of python commands entered line-by-line into a file
By typing the name of the shell script after the python executable, all the
commands will be run in order
• By convention files composed of Python commands have the suffix py Let’s say all the commands on the previous slide have been put into a file rabbit.py Here’s how it would be run:
Notice that only the text directly written out to stdout will appear on your monitor
$ python rabbit.py Hello World! (with respect)
1.04
$
Trang 9Ways to use Python: Executable Scripts
• Say you want to run your Python script directly at the system prompt (Just like an operating system command) This requires two steps
– Make the first line in the rabbit.py file
#!<full pathname of Python executable>
– Second, give rabbit.py executable permission
$ chmod u+x rabbit.py
• Now the rabbit file looks like this:
• To run the commands in the rabbit.py file, just type its name at the system
prompt
#!/usr/local/bin/python print "Hello World! (with respect)"
a=34.5 a
a*5.6 z=a/33.3 print '%7.2f' %(z)
Trang 10Variables, Data Types and Operators
Trang 11• Pick any name you want as long as it begins with a letter or underscore
• Don’t have to declare the variable name or type
• Variable “comes into existence” when it is assigned a value
• Case-sensitive
• Actually much more to variable assignments Fascinating approach when
we get to objects …
Trang 12Data Types
• Python has five built-in, core data types Listed here in the order in which they will be covered
Numbers Strings Lists Dictionaries
Tuples
Trang 14Numerical Operators
• The table below shows the numeric operators with precedence going from high
to low Due to operator overloading, these symbols can also be used with
other types
x*y x%y x/y x//y Multiplication, modulus,
normal division, truncating division
x + y x-y Addition, Subtraction
Trang 15Operator Precedence & Parenthetical Override
$ python
Python 2.2.3 (#1, Oct 26 2004, 17:11:32)
[GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-47)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Trang 16Python Division
Python 2.2.3 (#1, Oct 26 2004, 17:11:32)
[GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-47)] on linux2
Type "help", "copyright", "credits" or "license" for more
Trang 17Alternative Integer Bases
Trang 18Python Long Integers
• Long integers marked with a trailing L They can have unlimited size but at the price of poor performance.
Trang 19Displaying Floating-Point Numbers
• A fundamental point of computers: word length used in hardware on a
specific machine determines actual precision.
>>> power=2.0**0.3
>>> power
1.2311444133449163 #Echoing of variable results always
#returns the real precision In this
#case ~15 decimal places (8 byte word)
Trang 20• A feature* of some implementations of complex numbers in python is
that the coefficient must be represented in decimal format, i.e 5.0j not 5j
*feature is a term used by programmers to make excuses for programs which produce bogus results
Trang 21The “Amazing” Assignment Operator
• We have been blithely using = (the assignment operator) to assign
variables names to numeric values It has other interesting properties
• Multiple assignments: single statement
– The statement x = y = z =25 will assign all three variables to 25
– Handy shortcut
• Combined assignment and operation
– The statement x = x + 2.34 can be replaced with x+=2 34 (Taken form C)
– The <operator>= syntax can be used for all the numerical operators discussed
in this section (and more)
– Again, less typing involved (always nice) but more advantages
– Only need to evaluate LHS (variable name) once, not twice We will see later that some Python variables can are quite large
– This shortened syntax will cause the compiler to automatically pick the
optimized technique for performing the combined operations This advantage will have a greater effect on the more sophisticated data types to come.
Trang 23String Data Type
• Some key points:
– Proper perspective: Ordered Collection of Characters
– No character data type; just one element strings
– SINGLE and DOUBLE quotes work the same
– New operand : triple quotes ‘’’ (Block Strings)
– Strings are “immutable sequences”
• Immutable => individual elements cannot be assigned new values
• Sequence => positional ordering (i.e., indexed) – Since strings are character arrays, can use array operations on them
– Special actions encoded as escape sequences (\n)
– “Raw” strings will not recognize escape sequences
– Strings can be converted to other types and vice versa
Trang 24Making Strings (I)
>>> s='Galaxy Formation Era'; print s # Single Quote
Galaxy Formation Era
>>> d="Star Formation Era"; print d # Double Quote
Star Formation Era
>>> maybe="liberty, equality, fraternity‘ # Mixing?
File "<stdin>", line 1
maybe="liberty, equality, fraternity'
^ SyntaxError: invalid token
>>> meryl="Sophie's Choice"; print meryl # Quote in string
Sophie's Choice3
>>> streep='Sophie"s Choice'; print streep #Quote in string
Sophie"s Choice
>>> phrase="Shoot out" 'the lights'; print phrase #Concatenation
Shoot outthe lights
>>> empty="Shoot out" '' "the lights"; print empty
Shoot outthe lights
>>> spaced="Shoot out" ' ' "the lights"; print spaced
Shoot out the lights
>>>
Trang 25Making String (II)
>>> totab="Dalton\tEnnis"; print totab #Escape Character
Trang 26String Operators
str1 + str2 Concatenation
str *n n*str Replication (n is an integer)
str[i] String element with index i
str[i:j] Substring of consecutive elements
(i to j-1) len(str) Number of characters in a string
max(str) Maximum element (ASCII value) min(str) Minimum element (ASCII value)
Trang 27Working with Strings
>>> one="Vaya "; two='con '; three="Dios"
>>> goodbye=one+two+three; print goodbye # + is concatenation
Vaya con Dios
>>> byrds='Turn '
>>> lyric=byrds * 3; print lyric # * is replication
Turn Turn Turn
Trang 29Strings playing well with others …
• The addition symbol ‘+’ is overloaded: it can add two integer operands, two floating point operands, and (as we have just seen) two string operands And this is just the beginning of the overloading …
• If you try to add a string to an integer directly you have mixed operands and the compiler doesn’t know what to do Same vice versa
• Need to use built in type conversion operators
Trang 30Basic String Conversion
>>> lic="APN" + 9253 # DANGER:Mixing operand types
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects
>>> lic="APN" + str(9253); lic #int-to-string
>>> defn="Planck's constant-> "+str(h); defn
"Planck's constant-> 6.63e-34"
Trang 31Interlude: Printing to the Standard Output
• We have been using the Python print command without giving a
proper explanation of its use This interlude should remedy the situation
– Takes a list of strings as argument, and sends each to STDOUT in turn
– Adds a space amid items separated by commas
– Adds a linefeed at the end of the output To prevent this, put a comma at the end of the last string in the list
Trang 32Printing Formatted Strings
• For formatted output, use print control_string %
(variable_list)
– Works just like the C function printf
– The control_string has the text you want outputted along with format_identifiers.
– A format_identifier begins with the % sign, has optional numbers, and ends with a letter
code standing for the type of variable to be printed out.
– For example %d stands for a decimal number, %f stands for a floating point number, %s stands for a string, etc.
– As the print function moves from left to right, when it encounters a format_identifier it substitutes in the corresponding value of the variable from the variable_list.
– Example:
– See printf man page for further details
print ”Out %15s %5d %10.2f\n” % (a,b,c)
Control string List of items to be printed
>> man printf
Trang 33Interlude: Can we provide input to Python programs?
• Yes The most basic of reading commands is called (aptly enough)
Prompting and input can be done at the same time A string argument
given to raw_input() will printed to stdout and the function will then wait for input
Clever way of encouraging prompts
Prompts are optional, though
All input entered will be treated as a string by your Python program
Must use the conversion commands on the previous slide for other types
Trang 34The read.py Script
#!/usr/bin/python
year=raw_input("Please enter a year:")
ten=year+10
print "A decade later will be", ten
x=raw_input("Enter x coord: ") #prompt along with input
Trang 35An Input Session
$ read.py
Please enter a year:1963
A decade later will be 1973
Enter x coord: 3.0
Enter y coord: 4.0
Distance from origin is 5.0
$ read.py
Please enter a year:2260
A decade later will be 2270
Enter x coord: 13.4
Enter y coord: 56.2
Distance from origin is 57.7754273026
Trang 36More Refined Input
• There is a close cousin to the raw_input() function called simply
input()
• It works in the same manner and has all the properties of raw_input()except for one important distinction
• input() will not read in all input as strings (resulting in possible
subsequent conversion) It will read input and give it the appropriate
built-in type Here are some examples of its use:
>>> year=input("Please enter a year: ")
Please enter a year: 2001
>>> year
2001
>>> x=year*5; x
10005
>>> money=input("Please enter the amount in your wallet: ")
Please enter the amount in your wallet: 13.00
>>> add_Grant=100.00+money; add_Grant
113.0
Trang 37Immutable Strings????
• Can you really not change a string after it is created?
• No, it can be changed What is not allowed is to change individual
elements by assigning them new characters
• We can use all the string manipulation techniques seen so far to change a string
• We can also use the % sign as an operator that allows a string to have any
appearance desired (string formatting) The % operator acts like the C
function sprintf()
• We can also change strings by using a set of special functions associated
with strings called methods String methods is our next section.
Trang 38Changing Strings
>>> cheer="Happy Holidays!"; cheer
'Happy Holidays!'
>>> cheer[6]=‘B’ #Cannot do
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
>>> cheer[6:11]
'Holid'
>>> cheer[6:11]="Birth“ #Still cannot do
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support slice assignment
>>> cheer=cheer[0:6] + "Birthday" + cheer[-1]
>>> cheer
'Happy Birthday!‘
Trang 39String Methods
• As was mentioned previously, string methods are special functions
designed to work only with strings
• To find out what methods there are and how to use them use the Python help command
– help(str), help(int), help(float),
– help argument can also be the name of any variable of a certain type
• To use a method on a string, the string must first exist
• The syntax for using the method uses the “dot” operator (‘.’) The syntax
is as follows:
String_name.Method_name(args)
• The full story of methods will be presented later
Trang 40Using String Methods
• The executable python script strmeth.py contains examples of commands that use string methods Here is its contents:
#!/usr/bin/python hollow='There is the Shadow' song="Me and my Shadow"
Trang 41Running strmeth.py
$ strmeth.py
The starting index of 'the' in 'There is the Shadow' is 9 The index of the first 'a' in 'Me and my Shadow' is 3
A hopeful message: There is the Light
Enter your name: robson green
Hello Robson green, welcome to the party, pal
Uppercase: ME AND MY SHADOW
$
Trang 42List Data Type
• Like arrays
– Ordered collection of data
– Composed of elements that can be accessed by indexing
– Can create sublists by specifying an index range (“slicing”)
• Unlike arrays
– Elements can be of different types (heterogeneous)
– List can grow and shrink during program execution (“flexible”)
– You can change individual elements directly (“mutable”)
– Nesting allowed: lists of lists, …
– Can be concatenated together
• Lists have operators, built-in functions, and methods
• List creation operator [ ] , elements inside separated by commas
Trang 43Basic List Operations
>>> mix=[3,'tree',5.678,[8,4,2]]; mix #List creation
Trang 44Changing the lengths of Lists
• A powerful feature of lists is their flexibility: their size can change
• At a low level, list lengths can be changed with element/slice
reassignment and the use of built-in list operators
• At a higher – and easier – level is the use of length-changing list methods:
• Note that with proper use of list operators/functions/methods, lists can
become many interesting “containers” of data
– Stack, queue, array(normal), jagged matrix, dequeue, etc
append() append argument to end of list
extend(list) extend list with values in the list argument
insert(index,variable) insert variable contents before
index
pop() remove and return last list element remove() remove first occurrence of argument