Вы находитесь на странице: 1из 33

Outline

Why Use Python?


Running Python
Types and Operators
Basic Statements
Functions
Scope Rules (Locality and Context)
Some Useful Packages and Resources
Why Use Python? (1)
Python is object-oriented
Structure supports such concepts as polymorphism, operation
overloading, and multiple inheritance
It's free (open source)
Downloading and installing Python is free and easy
Source code is easily accessible
Free doesn't mean unsupported! Online Python community is huge
It's portable
Python runs virtually every major platform used today
As long as you have a compatible Python interpreter installed, Python
programs will run in exactly the same manner, irrespective of platform
It's powerful
Dynamic typing
Built-in types and tools
Library utilities
Third party utilities (e.g. Numeric, NumPy, SciPy)
Automatic memory management
Why Use Python? (2)
It's mixable
Python can be linked to components written in other languages easily
Linking to fast, compiled code is useful to computationally
intensive problems
Python is good for code steering and for merging multiple
programs in otherwise conflicting languages
Python/C integration is quite common
WARP is implemented in a mixture of Python and Fortran
It's easy to use
Rapid turnaround: no intermediate compile and link steps as in C or C++
Python programs are compiled automatically to an intermediate form
called bytecode, which the interpreter then reads
This gives Python the development speed of an interpreter without the
performance loss inherent in purely interpreted languages
It's easy to learn
Structure and syntax are pretty intuitive and easy to grasp
Running Python (1)
In addition to being a programming language, Python is also an interpreter.
The interpreter reads other Python programs and commands, and
executes them. Note that Python programs are compiled automatically
before being scanned into the interpreter. The fact that this process is
hidden makes Python faster than a pure interpreter.

How to call up a Python interpreter will vary a bit depending on your


platform, but in a system with a terminal interface, all you need to do is
type “python” (without the quotation marks) into your command line.

Example:
# From here on, the $ sign denotes the start of a terminal command line,
and the # sign denotes a comment. Note: the # sign denotes a comment
in Python. Python ignores anything written to the right of a # sign on a
given line
$ python # Type python into your terminal's command line
>>> # After a short message, the >>> symbol will appear. This
signals
# the start of a Python interpreter's command line
Running Python (2)

Once you're inside the Python interpreter, type in commands at will.

Examples:
>>> print (“Hello world”)
Hello world
# Relevant output is displayed on subsequent lines without the >>> symbol
>>> x = [0,1,2]
# Quantities stored in memory are not displayed by default
>>> x
# If a quantity is stored in memory, typing its name will display it
[0,1,2]
>>> 2+3
5
>>> # Type ctrl-D to exit the interpreter
$
Running Python (3)
Python scripts can be written in text files with the suffix .py. The scripts
can be read into the interpreter in several ways:

Examples:
$ python script.py
# This will simply execute the script and return to the terminal afterwards
$ python -i script.py
# The -i flag keeps the interpreter open after the script is finished running
$ python
>>> execfile('script.py')
# The execfile command reads in scripts and executes them immediately,
as though they had been typed into the interpreter directly
$ python
>>> import script # DO NOT add the .py suffix. Script is a module
here
# The import command runs the script, displays any unstored outputs, and
creates a lower level (or context) within the program. More on contexts
later.
Running Python (4)
Suppose the file script.py contains the following lines:
print 'Hello world'
x = [0,1,2]
Let's run this script in each of the ways described on the last slide:

Examples:
$ python script.py
Hello world
$
# The script is executed and the interpreter is immediately closed. x is
lost.
$ python -i script.py
Hello world
>>> x
[0,1,2]
>>>
# “Hello world” is printed, x is stored and can be called later, and the
interpreter is left open
Running Python (5)
Examples: (continued from previous slide)
$ python
>>> execfile('script.py')
Hello world
>>> x
[0,1,2]
>>>
# For our current purposes, this is identical to calling the script from the
terminal with the command python -i script.py
$ python
>>> import script
Hello world
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'x' is not defined
>>>
# When script.py is loaded in this way, x is not defined on the top level
Running Python (6)
Examples: (continued from previous slide)
# to make use of x, we need to let Python know which module it came
from, i.e. give Python its context
>>> script.x
[0,1,2]
>>>
# Pretend that script.py contains multiple stored quantities. To promote x
(and only x) to the top level context, type the following:
$ python
>>> from script import x
Hello world
>>> x
[0,1,2]
>>>
# To promote all quantities in script.py to the top level context, type
from script import * into the interpreter. Of course, if that's what
you want, you might as well type python -i script.py into the
terminal.
In Python 3.3
• Open the code in Idle IDE
• You can run the program using two options
run module
use python shell
If you are using python shell the use the
following command
>>>exec(open("first.py").read())
if the file is in first.py file
Accessing individual elements of file
• Consider To execute:(In python shell)
first.py >>> exec(open("first.py").read())
• print("Hello World") To get individual item
• x=[5,6,7] >>> from first import x
• a=10 >>>x
• b=2 [5,6,7]
• c1=a**b >>> from first import c1
Error….
>>> from first import *
>>>c1
100
Python Build-in types
Numbers 3.1415
Strings “Hello World”
Lists [1,2,3,4]
Dictionaries {‘test’: ‘yum’}
Files input=open(‘file.txt’, ‘r’)
Variables and Types
 Objects always have a type
 >>> a = 1
>>> type(a)
<type 'int'>
<class 'int'> //In python 3
>>> a = "Hello"
>>> type(a)
<type 'string'>
<class ‘str’> //In python 3
>>> type(1.0)
<type 'float'>
<class ‘float’> //In python 3
Types and Operators: Types of Numbers (1)
Python supports several different numeric types
Integers
Examples: 0, 1, 1234, -56
Integers are implemented as C longs
Note: dividing an integer by another integer will return only the integer
part of the quotient, e.g. typing 7/2 will yield 3
Long integers
Example: 999999999999999999999L
Must end in either l or L
Can be arbitrarily long
Floating point numbers
Examples: 0., 1.0, 1e10, 3.14e-2, 6.99E4
Implemented as C doubles
Division works normally for floating point numbers: 7./2. = 3.5
Operations involving both floats and integers will yield floats:
6.4 – 2 = 4.4
Types and Operators: Types of Numbers (2)
Other numeric types:
Octal constants
Examples: 0177, -01234
Must start with a leading 0
Hex constants
Examples: 0x9ff, 0X7AE
Must start with a leading 0x or 0X
Complex numbers
Examples: 3+4j, 3.0+4.0j, 2J
Must end in j or J
Typing in the imaginary part first will return the complex number in the
order Re+ImJ
In Python 3
• int (signed integers) − They are often called
just integers or ints. They are positive or
negative whole numbers with no decimal
point. Integers in Python 3 are of unlimited
size. Python 2 has two integer types - int and
long. There is no 'long integer' in Python 3
anymore.
• hexa-decimal or octal form
• >>> number = 0xA0F #Hexa-decimal
• >>> number
2575
• >>> number = 0o37 #Octal
• >>> number
31
Types and Operators: Operations on Numbers
Basic algebraic operations
Four arithmetic operations: a+b, a-b, a*b, a/b
Exponentiation: a**b
Other elementary functions are not part of standard Python, but included
in packages like NumPy and SciPy

Comparison operators
Greater than, less than, etc.: a < b, a > b, a <= b, a >= b
Identity tests: a == b, a != b

Bitwise operators
Bitwise or: a | b
Bitwise exclusive or: a ^ b # Don't confuse this with exponentiation
Bitwise and: a & b
Shift a left or right by b bits: a << b, a >> b
Number Type Conversion
• If you have >>> x=3.3
• int(x) to convert x to a plain integer.
• long(x) to convert x to a long integer.// not there
in python 3
• float(x) to convert x to a floating-point number.
• complex(x) to convert x to a complex number
with real part x and imaginary part zero.
• complex(x, y) to convert x and y to a complex
number with real part x and imaginary part y. x
and y are numeric expressions
Mathematical Functions
• 1 abs(x) The absolute value of x: the (positive) distance between x
and zero.

• 2 ceil(x) The ceiling of x: the smallest integer not less than x.

• 3 cmp(x, y)
• -1 if x < y, 0 if x == y, or 1 if x > y. Deprecated in Python 3. Instead
use return (x>y)-(x<y).

• 4 exp(x) The exponential of x: ex

• 5 fabs(x) The absolute value of x.

• 6 floor(x) The floor of x: the largest integer not greater than x.

• 7 log(x) The natural logarithm of x, for x > 0.


• 8 log10(x) The base-10 logarithm of x for x > 0.

• 9 max(x1, x2,...) The largest of its arguments: the value closest to


positive infinity

• 10 min(x1, x2,...) The smallest of its arguments: the value closest to


negative infinity.

• 11 modf(x) The fractional and integer parts of x in a two-item tuple.


Both parts have the same sign as x. The integer part is returned as a
float.

• 12 pow(x, y) The value of x**y.

• 13 round(x [,n]) x rounded to n digits from the decimal point.


Python rounds away from zero as a tie-breaker: round(0.5) is 1.0
and round(-0.5) is -1.0.

• 14 sqrt(x) The square root of x for x > 0.


MathFunctionsOnNumbers.py
• import math

• x=3.7
• y=4.4
• print("the absolute value of x is : " + str(abs(x)))

• print("the ceil value of x is : " + str(math.ceil(x)))

• print("the exponent value of x is : " + str(math.exp(x)))

• print("the floor value of x is : " + str(math.floor(x)))

• print("the fabs value of x is : " + str(math.fabs(x)))


• print("the log value of x is : " + str(math.log(x)))

• print("the log10 value of x is : " + str(math.log10(x)))

• print("the max value of x is : " + str(max(x,y)))

• print("the min value of x is : " + str(min(x,y)))

• print("the modf value of x is : " + str(math.modf(x)))

• print("the pow value of x is : " + str(math.pow(x,y)))

• print("the round value of x is : " + str(round(x,0)))

• print("the sqrt value of x is : " + str(math.sqrt(x)))


Output
• the absolute value of x is : 3.7
• the ceil value of x is : 4
• the exponent value of x is : 40.4473043600674
• the floor value of x is : 3
• the fabs value of x is : 3.7
• the log value of x is : 1.308332819650179
• the log10 value of x is : 0.568201724066995
• the max value of x is : 4.4
• the min value of x is : 3.7
• the modf value of x is : (0.7000000000000002, 3.0)
• the pow value of x is : 316.291547358931
• the round value of x is : 4.0
• the sqrt value of x is : 1.9235384061671346
Random Number Functions
• 1 choice(seq) A random item from a list, tuple,
or string.

• 2 randrange ([start,] stop [,step]) A randomly


selected element from range(start, stop, step).

• 3 random() A random float r, such that 0 is less


than or equal to r and r is less than 1
• 4 seed([x]) Sets the integer starting value used
in generating random numbers. Call this
function before calling any other random
module function. Returns None.

• 5 shuffle(lst) Randomizes the items of a list in


place. Returns None.

• 6 uniform(x, y) A random float r, such that x is


less than or equal to r and r is less than y.
RandomFunctionsOnNumbers.py
• import random

• #for choice function

• print ("returns a random number from range(100) : ",random.choice(range(100)))


• print ("returns random element from list [1, 2, 3, 5, 9]) : ", random.choice([1, 2, 3,
5, 9]))
• print ("returns random character from string 'Hello World' : ",
random.choice('Hello World'))

• # randomly select an odd number between 1-100


• print ("randrange(1,100, 2) : ", random.randrange(1, 100, 2))

• # randomly select a number between 0-99


• print ("randrange(100) : ", random.randrange(100))
• # random number
• print ("random() : ", random.random())

• # random seed function


• random.seed()
• print ("random number with default seed",
random.random())
• random.seed(10)
• print ("random number with int seed", random.random())
• random.seed("hello",2)
• print ("random number with string seed",
random.random())
• # random shuffle function
• list = [20, 16, 10, 5];
• random.shuffle(list)
• print ("Reshuffled list : ", list)

• # random uniform function


• print ("Random Float uniform(5, 10) : ",
random.uniform(5, 10))

• print ("Random Float uniform(7, 14) : ",


random.uniform(7, 14))
Output
• returns a random number from range(100) : 7
• returns random element from list [1, 2, 3, 5, 9]) : 1
• returns random character from string 'Hello World' : W
• randrange(1,100, 2) : 89
• randrange(100) : 46
• random() : 0.5843943845590819
• random number with default seed 0.3973586167252473
• random number with int seed 0.5714025946899135
• random number with string seed 0.3537754404730722
• Reshuffled list : [10, 16, 5, 20]
• Random Float uniform(5, 10) : 5.255433459829996
• Random Float uniform(7, 14) : 9.600739998040153
Trigonometric Functions

• 1 acos(x) Return the arc cosine of x, in radians.


• 2 asin(x) Return the arc sine of x, in radians.
• 3 atan(x) Return the arc tangent of x, in radians.
• 4 atan2(y, x) Return atan(y / x), in radians.
• 5 cos(x) Return the cosine of x radians.
• 6 hypot(x, y) Return the Euclidean norm, sqrt(x*x +
y*y).
• 7 sin(x) Return the sine of x radians.
• 8 tan(x) Return the tangent of x radians.
• 9 degrees(x) Converts angle x from radians to degrees.
• 10 radians(x) Converts angle x from degrees to radians.
Mathematical Constants

• pi
The mathematical constant pi.
• e
The mathematical constant e.

Вам также может понравиться