Date post: | 05-Jan-2016 |
Category: |
Documents |
Upload: | matthew-cain |
View: | 231 times |
Download: | 1 times |
INTRODUCTION TO PYTHON-GETTING STARTED
WHAT IS PYTHON?
An elegant and robust programming language
which delivers powerful and general applicable traditional compiled languages with the used of simpler scripting and interpreted languages.
Running python: 3 ways
Starting the interpreter interactively , entering one line of Python at a time for execution
Running a script written in Python – this is done by invoking the interpreter on your script application
Run from graphical user interface (GUI) from within an integrated development environment (IDE/IDLE)
INTERACTIVE INTERPRETER FROM THE COMMAND LINE
Python can be start coded using an interactive interpreter by starting it from the command line.
This can be done from Unix, DOS etc. Unix
At the Unix prompt (% or $), the interpreter can be started by invoking the name python (jpython), as in the following $python
Once Python started, the interpreter startup message will indicate the version and platform and be given the interpreter prompt “>>>” to enter Python commands.
CONTINUE..
Windows/DOS From a DOS window (either DOS /Windows), the
command to start python is same as Unix, the difference is that the prompt is c:\>python
Command-Line Options Additional options may be provided to the
interpreter such as listed below: -d provide debug output -o generate optimized bytecode resulting in .pyo
files file Run Python script from given file - c cmd Run Python script sent in as cmd string Etc…
AS A SCRIPT FROM THE COMMAND LINE
Unix- a Python script can be executed by invoking the interpreter from the command line as in the following $ python script.py
Same as Unix
AN INTEGRATED DEVELOPMENT ENVIRONMENT (IDE)
Need GUI application on your system that supports Python.
Have graphical user interface (GUI), source code editor , trace and debugging facilities.
IDLE is the first Unix IDE for Python. PythonWin is the first Windows interface for
Python and is an IDE with a GUI. Usually installed in the same directory as
Python. PythonWin features a color editor, a new and
improved debugger, interactive shell window, COM (component object extensions and more.
CONTINUE..
Python extension is .py IDLE –also available on the Windows platform In windows, it look similar to Unix From Windows, IDLE can be found in the Lib\
idlelib subdirectory, where Python interpreter is found, c:\Python2x.
To start IDLE from a DOS command window, invoke idle.py
To start IDLE from a Windows environment, just double click on idle.pyw.
CONTINUE..
Files ending with .pyw will not open a DOS command window to run the script on it instead it is created a shortcut to c:\Python2x\Lib\idlelib\idle.pyw
Other IDEs and execution environment Open source
IDLE –http://python.org/idle/ PythonWin +Win32
Extensions-http://startship.python.net/crew/skippy/win32
Etc……
WRITING A SIMPLE PYTHON PROGRAM
Prompt in Python “>>>” primary prompt “…” secondary prompt Primary prompt – interpreter is expecting the
next python statement Secondary prompt – interpreter is waiting for
additional input to complete the current statement.
There are two primary ways that Python “does things”: 1. statements
2: expression – functions, equations, etc
A statement is a body of control which involved using keywords.
CONTINUE..
Statements may/may not lead to a result or output.
Example use print statement to print Hello World>>> print ‘Hello World!’Output – Hello world
Expressions – do not use keywords. Example of equations- simple equations that
comes together with mathematical operators, can be a functions which are called with parentheses.
They may/may not take input, and they may/may not return a meaningful value.
PROGRAM OUTPUT, THE PRINT STATEMENT, AND “HELLO WORLD!”
>>> myString = ‘Hello World!’>>> print myStringHello World!>>> myString‘Hello World!’
In this example, use a string variable, then use print to display its contents.
Given only the name reveals quotation marks around the string.
Why? This is to indicate that the value in the variable is a string.
If it print other than string the quotation marks will not be revealed.
CONTINUE..
Python’s print statement, paired with the string format (%), supports string substitution similar to printf() function in C.
>>> print “%s is number %d!” % (“python”,1)
Python is number 1 %s means to substitute a string while %d
indicates an integer should be substituted. %f is for floating point numbers. The print statement also allows its output
directed to a file. (will look into this matter later)
CONTINUE..
Program input and the raw_input() built-in function.raw_input – to get user input from the command line. read from standard input and assigns the string value to the variable you designate. function int() can be use to convert any numeric input string to an integer representation.
EXAMPLE
>>> user=raw_input(‘Enter login name: ‘)Enter login name: root>>> print ‘Your login is :’, userYour login is: root
This example is using text input
EXAMPLE 2- A NUMERIC STRING INPUT
>>> num=raw_input (‘Now enter a number:’)Now enter a number:1024>>> print ‘Doubling your number: ‘,
int(num)*2Doubling your number :2048
The int () function converts the string num to an integer so that the mathematical operation can be performed.
COMMENTS
Used the symbol (#) (hash or pound ) to indicate comments.
It begin with (#) and continue until the end of line.
>>># one comment ...print ‘Hello world!’ # another commentHello World!
OPERATORS-STANDARD MATHEMATICAL
Operators-symbol Operators-name
+ Addition
- Subtraction
* Multiplication
/ Division(classic division)
% Modulus
// For floor division (rounds down to the nearest whole number)
** Exponentiation
An operation that raises some given constant (base) to the power of other number (exponent).
CONTINUE..
Classic division means that if the operands are both integers, it will perform floor division
For floating numbers, it represents true division.
OPERATOR PRECEDENCE
**
Unary +/-
%
//
/
*
+/_
>>> print -2*4 +3**21In this example, 3**2 is calculated first followed by (-2*4).
STANDARD COMPARISON OPERATORS
This operators return a Boolean value indicating the truthfulness of the expression.
Operators (symbol)
<
<=
>
>=
==
!=
<>
EXAMPLE
>>> 2 < 4True>>> 2 == 4False>>> 2 > 4False6.2 <= 6.2True>>> 6.2 <= 6.20001True
CONJUNCTION OPERATORSOperators
and
or
not
• can use these operations to chain together arbitrary expressions and logically combine the Boolean results:
>>> 2 < 4 and 2 == 4False>>> 2 > 4 or 2 < 4True>>> not 6.2 <= 6 True>>> 3 < 4 < 5 True
>>> 3 < 4 < 5 is a short way of saying >>> 3<4 and 4<5
VARIABLES AND ASSIGNMENTS Variables in Python is similar to other high level
languages. Variables are simply identifier names with an
alphabetic first character , upper or lowercase letters including the underscore (_).
Other alphanumeric or underscore. Python is case sensitive means that “CASE” is not
same as “case”. Python is dynamically typed means that no pre-
declaration of a variable or its type is necessary. The type (and value) are initialized on assignment. Assignments are performed using the equal sign.
EXAMPLE
>>> counter =0 # the integer
>>> miles =1000.0 # the floating point
>>> name =‘Bob’ # string
>>> counter = counter +1 #an incremental statement for integer
>>>kilometers = 1.609*miles #floating point operation and assignment
>>> print “%f miles is the same as %f km’ %(miles,kilometers)
1000.000000 miles is the same as 1.609.000000 km
In this example, there are 5 variable assignments.
CONTINUE..
Python also supports augmented assignments – statement that both refer to and assign values to variables.
Example n =n *10 shortcut n *= 10 Python does not support
increment/decrement operators like in C : n++ /--n. Because +, -- are also unary operators, Python will interpret --n as -(-n) == n and the same is true for ++n.
NUMBERS
Python support 5 basic numerical types
int 0101, 84, -247, 0x80,017,-982
long 29979064258L,DECADEDEBEEF
bool True, false
float 3.1412,4.2E-10,-90. , 6.022
complex
6.23+1.5j, -1.23-875J
Boolean values are a special case of integer.If put in a numeric context such as addition with other numbers, true is treated as the integer with value 1 and false as value 0.
Complex number , number that involve the square root of -1, so called “imaginary” numbers.
More on numbers in later chapter
STRINGS
String in Python are identified as a contiguous set of characters in between quotation marks.
Python allows 8 pairs of single /double quotes. Triple quotes (three consecutive single/double
quotes) can be used to escape special characters.
Subsets of strings can be taken using the index ([ ] ) and slice ([ : ]) operators, which works with
indexes starting at 0 in the beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator, and the asterisk (*) is the repetition operator.
EXAMPLE>>> pystr = ’PYTHON’
>>> iscool = ‘is cool!’
>>> pystr[0]
‘P’
>>> pystr[2:5]
‘tho’ # the output start at 2 up to 4 not include the character at end.
>>> iscool[:2]
'is‘
>>> pystr + iscool
‘PYTHON is cool!'
>>> pystr*2
‘PYTHONPYTHON'
>>> iscool[-1]
'!‘
0 1 2 3 4 5
P Y T H O N
-6
-5 -4 -3 -2 -1
Counting forward
Counting backward
More on string in coming chapter
LISTS AND TUPLES Lists and tuples can be though of as generic “ arrays”
with which to hold an arbitrary number of arbitrary Python objects
The items are ordered and accessed via index offsets, similar to array except that lists and tuples can store different types of objects.
Lists are enclosed in brackets ([ ]) and their elements and size can be changed.
Tuples are enclosed in parentheses (()) and cannot be updated.
Tuples can be thought of for now as “read-only” lists. Subsets can be taken with the slice operator ([] and [ :
] in the same manner as string.
EXAMPLES
>>> alist =[1,2,3,4]
>>> alist
[1, 2, 3, 4]
>>> alist[0]
1
>>> alist[2:]
[3, 4]
>>> alist[:3]
[1, 2, 3]
>>> alist[1]=5
>>> alist
[1, 5, 3, 4]
EXAMPLES
>>> atuple=('robots',77,93,'try')
>>> atuple
('robots', 77, 93, 'try')
>>> atuple[:3]
('robots', 77, 93)
>>> atuple[1]=5 # not allowed to change the element in tuple
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
atuple[1]=5
TypeError: 'tuple' object does not support item assignment
CODE BLOCKS Code blocks are identified by indentation rather than using
symbols like {} Indentation clearly identifies which block of code a
statement belongs to.
if statementif expression :
if _suite If the expression is non-zero or true, then the statement
if_suite is executed, otherwise execution continues on the first statement after.
Suite is the term used in python to refer to a sub-block of code and can consists of single or multiple statements.
Example:
>>> if x < .0:
print '"x must be at least 10!'
CONTINUE..
Python also support an else statement that is used with if : if expression: if_suiteelse: else_suite
Python has an “else-if” spelled as elif : if expression1: if_suiteelseif expression2: elif_suiteelse: else_suite
WHILE LOOP
while expression:
while_suite
The statement while_suite is executed continuously in a loop until the expression becomes zero or false.
Execution then continues on the first succeeding statement.
>>> counter =0
>>> while counter <3:
print 'loop #%d'% (counter)
counter +=1
loop #0
loop #1
loop #2
FOR LOOP
Python’s for takes an iterable (such as sequence or iterator) and traverses each element once.>>> print 'i like to use the internet for:'i like to use the internet for:>>> for item in ['e-mail','net-surfing','homework','chat']:
print item
e-mailnet-surfinghomeworkchat
More on if and loops in coming chapter