introduction to python-getting started cmpd 124 introduction to programming and problem solving...

35
Introduction to Introduction to python-getting started python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Upload: prosper-lane

Post on 29-Dec-2015

251 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Introduction to python-Introduction to python-getting startedgetting started

CMPD 124INTRODUCTION TO PROGRAMMING

AND PROBLEM SOLVING TECHNIQUES

Page 2: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

What is python?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)

Page 3: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Interactive interpreter from Interactive interpreter from the command linethe command linePython 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.

Page 4: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Continue..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…

Page 5: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

As a Script from the As a Script from the Command LineCommand LineUnix- a Python script can be

executed by invoking the interpreter from the command line as in the following ◦$ python script.py

Same as Unix

Page 6: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

An integrated development An integrated development environment (IDE)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.

Page 7: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Continue..Continue..Python extension is .pyIDLE –also available on the Windows

platformIn 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.

Page 8: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Continue..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……

Page 9: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Writing a simple python Writing a simple python programprogramPrompt in Python “>>>” primary

prompt “…” secondary prompt Primary prompt – interpreter is expecting

the next python statementSecondary 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.

Page 10: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Continue..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.

Page 11: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Program Output, the print Program Output, the print statement, and “Hello statement, and “Hello World!”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 allow objects other than strings to be displayed in the same manner as this string.

Means that using the name of the variable, you can print/display a printable string representations of any object not just strings.

Page 12: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Continue..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)

Page 13: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Continue..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. fucntion int() can be use to convert any numeric input string to an integer representation.

Page 14: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

exampleexample

>>> user=raw_input(‘Enter login name: ‘)

Enter login name: root>>> print ‘Your login is :’, userYour login is: root

This example is using text input

Page 15: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Example 2- a numeric string Example 2- a numeric string inputinput>>> num=raw_input (‘Now enter a

number:’)Now enter a number:1024>>> print ‘Doubling your number: %d’

%(intnum)*2)Doubling your number :2048

The int () function converts the string num to an integer so that the mathematical operation can be performed.

Page 16: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

commentscommentsUsed 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!Special comments called

documentation strings or “doc strings”Unlike regular comments, doc strings

can be accessed at runtime and used to automatically generate documentation.

Page 17: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Operators-standard Operators-standard mathematical 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).

Page 18: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Continue..Continue..Classic division means that if the

operands are both integers, it will perform floor division

For floating numbers, it represents true division.

If true division is enabled, then the division operator will always perform that operator, regardless of operand type.

More on this later.

Page 19: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Operator precedenceOperator precedence

**

Unary +/-

%

//

/

*

+/_

>>> print -2*4 +3**21In this example, 3**2 is calculated first followed by (-2*4).

Page 20: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Standard comparison Standard comparison operatorsoperatorsThis operators return a Boolean

value indicating the truthfulness of the expression.Operators

(symbol)

<

<=

>

>=

==

!=

<>

Page 21: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

exampleexample>>> 2 < 4True>>> 2 == 4False>>> 2 > 4False6.2 <= 6.2True>>> 6.2 <= 6.20001True

Page 22: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Conjunction operatorsConjunction 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

Page 23: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Variables and Variables and assignmentsassignments 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.

Page 24: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

exampleexample>>> 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.

Page 25: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Continue..Continue..Python also supports augmented

assignments – statement that both refer to and assign values to variables.

Example n =n *10 shortcut n *= 10Python 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.

Page 26: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

numbersnumbers

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

Page 27: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Strings 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.

Page 28: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

exampleexample>>> 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

Page 29: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Lists and tuplesLists 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.

Page 30: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

examplesexamples>>> 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]

Page 31: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

examplesexamples>>> 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

Page 32: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Code blocksCode 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!'

Page 33: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

Continue..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

Page 34: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

While loopWhile loopwhile 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 #0loop #1loop #2

Page 35: Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

For loopFor loopPython’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