Download Python3-Eng

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Introduction to
Python 3.x
Mikio Kubo
Why Python?
• We can do anything by
importing some modules
• Optimization
• Data Analysis
• Statistics
• Everything is included!
• Also fly!
import antigravity ?
• Programming becomes
fun again!
http://xkcd.com/353
/
Why Python?
• Most popular programming language
• Including MIT (Introduction to
Computer Science and Programming
Using Python)
Why Python?
• To get more money!
Average Initial
Salary in Japan
Python!
Why Python?
• To get more and more money!
Top 10 Programming Languages to Learn in 2014
No 1. Python
Average Salary: $93,000
Job Count: 24,533
Top Employers: Amazon, Dell, Google, eBay &
Yahoo, Instagram, NASA, Yahoo
Example Sites: Google.com, Yahoo Maps,
Reddit.com, Dropbox.com, Disqus.com
No 2. Java, No 3. Ruby, No. 4 C++, No5. JavaScript
No 6. C#, No. 7 PHP, No8. Perl ….
http://tech.pro/blog/1885/top-10-programming-languages-to-learn-in-2014
Some Remarks
• Python 3.x is not compatible to Python 2.x
• We use Python 3
• Install Anaconda (Python 3 Package)
https://store.continuum.io/cshop/anaconda/
Free version is enough
It includes more than 100 useful modules
It supports Mac, Linux, and Windows
How to print 'Hello, world!'
C++ (You need not remember this! )
#include <iostream>
int main() {
std::cout << 'Hello, world!' << std::endl;
return 0;
}
Python – Just use function print()
print ('Hello, world!')
Indent = Beauty
Indent = The way for grouping the sentences in Python
A bad C++ programmer may write...
if (x > 1) { y=x+1;
z=x+y; } else { y=0; z=0; }
In Python, anyone must write like this:
if x > 1:
y=x+1
# This is a comment part
z=x+y
# Here is the first block
else:
y=z=0
# Now the second block
If the indentation was wrong, it causes an error!
Why Python Again !
• Number of keywords to be remembered is much less
than other language (about 30! Java has more than 120!)
• Indentation helps to write a easy-to-read program
• Interpreter (You need not to compile)
• Need not to declare variables
• Need not to manage memory (automatic garbage
collection)
• Works on Windows, Mac, Linux (and also iphone and
ipad!)
• Object oriented
• Free!
Data Type (1): Number
• Number
–
–
–
–
int : integer number in unlimited range
bool : True or False
float: floating point number, i.e., 5.4 or 1.0
complex: complex number, i.e.,
z= 0 + 1j (real part and imaginary part)
z.real is 0
z.imag is 1
z*z
is -1+0j
because j*j is minus 1
Data Type (2): Sequence
• Sequence Type
– string : (immutable) sequence of unicodes, i.e., 'Mickey',
'Minny','Mickey's Birthday', and
''' We can write multiple lines
using triple quotes
like this'''
– list: (mutable) sequence of arbitrary objects generated
by brackets [ ], i.e., [1,2,3,'a'], [1,'b', [2,3,'c'], 6 ], [ ]
– tuple: (immutable) sequence of arbitrary objects
generated by parentheses ( ), i.e., (1,2,3,'a'), ( (1,2),
(2,'f','g'))
'Immutable' = cannot modify
String is immutable!
>>> a='Mickey'
>>> a[0]='D'
# a[0] is the first string
Traceback (most recent call last):
File '<pyshell#7>', line 1, in <module>
a[0]='D'
TypeError: 'str' object does not support item assignment
Tuple are immutable, while list is mutable!
• Set Type
Data Type (3)
– set : (mutable) set generated by braces { }, i.e.,
{1,2,3}, {'a', 'b', 'Mickey'}
– frozenset: (immutable) set
• Map Type
– dictionary: hash function that maps keys to values
composed generated by {key: value, ... }, i.e.,
{ 'Mary': 126, 'Jane': 156},
{ 'Hello': 'Konnnichiwa', 1: 'One', 2: 'Two'}
Function type( ) and type conversion
• To check the type of objects, use function type():
 type(124)
 type(3.1415)
 type(3+5j)
• To convert the type
– int( ) : convert to integer number
– float( ) : convert to floating number
– complex() : convert to complex number
 int(3.14)
 float(3)
 complex(1)
Bool and String: type conversion
• Check the type of objects
 type(True)
 type('Hello')
• Convert the type
– bool( ) : 0 is False,otherwise True
– str( ) : return string
 bool(3.14)
 bool(0)
 bool('0')
 str(3+5)
 str(True)
String (1)
'abc' or 'abc' or
''' .....
...... '''
Single (double) quote inside the double
(single) quotes is allows.
' My 'ideal' Place ' or 'My 'favorite' movie'
Triple quotes( ''' ) allows multiple lines
String (2)
• String is a sequence type index from 0
For x= 'abcd', x[1] returns 'b'
a b c d
x[0] x[1] x[2] x[3]
Slicing (1)
• slicing of sequence type
[i:j] means i≦k<j
[ :j] means 0≦k<j
[i: ] means i≦k
For x= 'abcd', x[1:3] returns 'bc'
x[1:] returns 'bcd'
a b c d
x[0] x[1] x[2] x[3]
Slicing (2)
• len() returns the size of the object
len(x[i:j]) is equal to j-i
• The negative indices mean the index from the last.
The last character is x[-1]. The slicing is the strings
between the number i and j.
0
1
2
3
4
a b c d
-4
-3
-2
-1
x[0] x[1] x[2] x[3]
String Methods (1)
• Method (function associated with object using '.'
notation)
Example: s='abABBaac'
s.count(x):returns how many times x occurs in string s
s.count('a') -> 3
s.index(x):returns the first index x occurs in string s
s.index('A') -> 2
s.upper():converts all the characters in string s to
uppercase
s.upper() -> 'ABABBAAC'
s.islower(): returns True iff all the characters in sting s
are lowercased
s.islower() -> False
String Methods (2)
• Example: s='abABBaac'
s.replace(old, new): returns a string by substituting
string <old> to <new> in string s
s.replace('AB','Mickey') -> 'abMickeyBaac'
s.split(d): returns a list of strings using d as the
separator
s.split('a')| -> [' ', 'bABB', ' ', 'c']
s.join(L): returns a string that concatenates all the
string in list L using s as the separator
':'.join(['a','b','c'])| -> |'a:b:c'|
s.format(args): formats the string s using argument
args
'My friends are {0}, {1} and {0}'.format('Bob','Pedro','Bob)
-> 'My friends are Bob, Pedro and Bob'
List
• list: sequence of arbitrary objects
• Use bracket [] and separate the objects by
comma (,). i.e., [1,2,3,'a'],['a',['b',5,5],'c']
• mutable: can modify the items
For L=[1,1,5,4] , L[1]=100 => L=[1,100,5,4]
• Modify the elements by slicing
For L=[1,1,5,4] , L[1:3]=[100,200,300] =>
L=[1,100,200,300,4]
List Methods
• Method (function associated with object using '.'
notation)
Example: L=[1,1,5,4]
L.count(x):returns how many times x occurs in list L
L.count(1) -> 2
L.index(x):returns the first index x occurs in L
L.index(5) -> 2
L.reverse(): reverses the order of items in L
L.reverse() -> L=[4,5,1,1]
L.sort(): sorts the items in L
L.sort()-> L=[1,1,4,5]
Tuple
• tuple:sequence type of arbitrary objects
• Just separate the objects by comma (,) like
a,b
or use parentheses. i.e., (1,2,3,'a')
• Parentheses are necessarily for nested tuples
((1,5),('a','b',6))
• immutable: cannot modify
• Usage: a,b = b,a
Dictionary
• dictionary: map type composed of keys and values
• Use braces { } and input 'key : value' pairs separated
by comma, i.e.,
D={ 'Mary': 126, 'Jane': 156, 'Sara': 170}
• Same dictionary can be generate using dict() function
D=dict(Mary=126, Jane=156, Sara=170)
• D['Sara'] returns 170
• Keys must be immutable
• Dictionary is mutable:
D['Sara']=130 =>
{ 'Mary': 126, 'Jane': 156, 'Sara': 130}
Set
• set and frozenset: set type composed of
arbitrary objects
• Use braces S = {1,2,'Candy'}
• Use function set (or frozenset)
S=set( [1,2,'Candy'])
• set methods such as union, intersection,
difference,symmetric difference
• set is mutable
• fronzenset is immutable
Operation (1)
• Priority of operations
1. Parentheses ()
2. Exponential **
3. Multiply * or Division / or Integer Division // or
Mod (Division Remainder) %
4. Add + or Subtract -
• Comparison (returns Boolean)
<= less than or equal to
>= greater than or eqial to
== equal
!= not equal
Operator (2)
• 'in' and 'not in'
– True if an element is in the object (string, list,
tuple, set, dictionary)
– True if an element is not in the object
• Boolean operators
and
or
(1<4) or (5<4)
('a' in 'banana') and ('c' in [1,5,'c'])
If /else statesment
if <True or False Expression 1>:
Expression 1 is True
elif if <True or False Expression 2>:
Expression 1 is False and Expression 2 is True
else:
Expression 1 is False and Expression 2 is False
Example:
if x<0:
print ( 'Negative Number' )
else:
print ( 'Non-negative' )
for-loop
for <element> in <iterative object such as list or dict>:
Loop Block
range(i,j): generator function that returns integers k such that
i ≦k < j
Example: print 0,1,2,3,4
for x in range(5):
print(x)
Comprehension (1)
List comprehension:
generate a list using 'for' within [ ]
Example:
A list that contains tuples
2
x, x ,2
x
[ (x, x**2, 2**x) for x in range(5)]
>>>
[(0, 0, 1), (1, 1, 2), (2, 4, 4), (3, 9, 8), (4, 16, 16)]
Comprehension (2)
Generator comprehension:
'for' loop within ( )
Example using 'sum' function
sum(x for x in range(11))
>>>
55
while-loop
while <True or False Expression>:
Loop Block
Example: print 2*x while x is positive
x=10
while x>0:
print (2*x)
x =x-1
break and continue
• Keywords to escape from a loop
– break: finish the loop
– continue: jump to the next iteration
Example: print 2*x while x is positive and x is odd
x=10
while True:
x =x-1
if x%2==0:
continue # do not print when x is even
print (2*x)
if x<=0:
break
# finish the loop when x reaches 0
for-else
When for (or while) loop is not finished by 'break',
execute 'else' block after the loop
Example: check whether y is a prime number
y=11
for x in range(2,y):
if y % x==0:
# if y is divisible by x, y is a composite number
break
else:
print ('Prime Number' )
Function
• To define a fuction ...
def <name of function>( arguments ):
function block
return <return value> # optional
Example: Concatenate given two strings and repeat three
times.
def concatenate3(a,b):
c=a+b
return 3*c
concatenate3('a','b') returns 'ababab'
Recursion (1)
• Recursion = function that calls itself
Example: factorial n! =n×(n-1) ×・・・×2×1
that can be defined recursively :
n!=n × (n-1)! and the initial condition 0!=1
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)
Recursion (2)
• Fibonacci number defined by:
F(0)=1, F(1)=1, F(n)=F(n-1)+F(n-2)
def fibonacci (n):
if n == 0 or n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
Module
• Module is a library to be imported;
that is just a program named <filename.py> written in Python
Method 1: import module
import <filename>
Example: import 'math' module and use square root function 'sqrt'
import math
print math.sqrt(2)
Method 2: import function (and/or class) in module
from <filename> import <function/class name> or wildcard (*)
from math import *
print sqrt(2)
(Pseudo) Random Number
Generator Module
• import random or from random import *
random(): returns a uniform random number in [0.0, 1.0)
Example: random() -> 0.48777947886
randint(i,j): returns a uniform random integer in i ≦k <=j
Example: randint(-5,1) -> -3
shuffle(L): mix list L randomly.
Example: L=[1,2,3,4], shuffle(L) -> L=[4, 1, 3, 2]
choice(L): Choose one item from list L randomly
Example: L=[1,2,3,4], choice(L) -> 3
Exercises
• CodingBat
http://codingbat.com/python/
• PySchool
http://www.pyschools.com/
(requires a google account)