Introduction to Python

What is Python?

Lightweight scripting programming language

Characteristic

Lightweight, interactive

Download

Official

Installation

  • Windows environment variable setting (automatic setting selectable)
  • Confirmation: python in cmd
C:\Users\rakuf\Desktop\wk>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

hello world (interactive mode)

>>> print ("hello world !!!")
hello world !!!

Exit interactive mode

>>> quit ()
C: \ Users \ rakuf \ Desktop \ wk>

Indent

※ Note: You can not recognize without indentation for each block.

Japanese correspondence

code specification required

# test.py
# - * - coding: utf - 8 - * -
# Can use Japanese

variable

# test.py
# - * - coding: utf - 8 - * -
# Definition
a = 1 # number
b = 'ABC' # character string
c = [1, 2, 3, 4, 5] # list
d = {'apple': 10, 'orange': 20, 'banana': 30} # dictionary
# Output
print (a)
print (b)
print (c)
print (d)

result

1
ABC
[1, 2, 3, 4, 5]
{'apple': 10, 'orange': 20, 'banana': 30}

Number

test.py
# - * - coding: utf - 8 - * -
# Definition
a = 1 # int
b = 2.0 # float
c = 3 + 4 j # complex
d = complex (5, 6) # complex
# Output
print (a)
print (b)
print (c.real)
print (d.imag)

result

1
2.0
3.0
6.0
bool
test.py
# - * - coding: utf - 8 - * -
# Definition
a = True # Uppercase is required at the beginning
b = False # First capital required
# Output
print (a)
print (b)

result

True
False

String

# test.py
# - * - coding: utf - 8 - * -
# Definition
# ''
str_1 = 'this is a string.'
# ""
str_2 = "this is a string."
# 'in string
str_3 = 'we can use \' in a string. '
# "in string
str_4 = "we can use \" in a string. "
Edit with # / with newline
str _ 5 = "word 1 \
word 2 "
How to use # r
str_6 = "aaa \ nbbb"
str - 7 = r "aaa \ nbbb"
# Output
print (str - 1)
print (str - 2)
print (str - 3)
print (str - 4)
print (str - 5)
print (str - 6)
print (str - 7)

result

this is a string.
this is a string.
we can use 'in a string.
we can use "in a string.
word 1 word 2
aaa
bbb
aaa\nbbb

String format (%)

# test.py
# - * - coding: utf - 8 - * -
errmsg = "Can not open file"
errcode = 12345
msg = "ERROR:% s (% d)"% (errmsg, errcode)
print (msg)

result

ERROR: Can not open file (12345)

constant

python does not support constants.

Collective type

list

# test.py
# - * - coding: utf - 8 - * -
A 6 ',' A 7 ',' A 8 ',' A 9 '], and A =' 'A 0', 'A 1', 'A 2', 'A 3', 'A 4'
print (a [0])
print (a [3])
print (a [3: 5])
print (a [3:])
print (a [: 5])
for n in a:
     print (n)

result

A0
A3
['A3', 'A4']
['A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9']
['A0', 'A1', 'A2', 'A3', 'A4']
A0
A1
A2
A3
A4
A5
A6
A7
A8
A9

tuple

# test.py
# - * - coding: utf - 8 - * -
A 6 ',' A 7 ',' A 8 ',' A 9 '), that is, a = (A 0', A 1 ', A 2', A 3 ', A 4', A 5 '
a [0] = 'A00' # Can not change

result

Traceback (most recent call last):
   File "test.py", line 5, in <module>
     a [0] = 'A00'
TypeError: 'tuple' object does not support item assignment

dictionary

# test.py
# - * - coding: utf - 8 - * -
# Definition
d = {'key 1': 'value 1', 'key 2': 'value 2', 'key 3': 'value 3'}
# Output
print (d ['key 1'])
for k, v in d.items ():
     print (k, v)
for k in d.keys ():
     print (k, d [k])
for v in d.values ():
     print (v)

result

value1
key1 value1
key2 value2
key 3 value 3
key1 value1
key2 value2
key 3 value 3
value1
value2
value 3

Set

# test.py
# - * - coding: utf - 8 - * -
# Definition
a = set (['red', 'yellow', 'blue'])
b = set (['green', 'white'])
# Output, computable
print (a)
print (b)
print (a - b)
print (a | b)
print (a & b)
print (a ^ b)
print ('red' in a)
a.add ('black')
print (a)

result

{'blue', 'yellow', 'red'}
{'white', 'green'}
{'blue', 'yellow', 'red'}
{'blue', 'green', 'yellow', 'red', 'white'}
set ()
{'blue', 'red', 'green', 'yellow', 'white'}
True
{'blue', 'yellow', 'black', 'red'}

Control statement

if else

# test.py
# - * - coding: utf - 8 - * -
a = 10
# if statement Note: indentation match
if a> 10:
     print ('big')
elif a == 10:
     print ('10')
else:
     print ('small')

result

Ten
while
test.py
# - * - coding: utf - 8 - * -
n = 0
# while
While n <5:
     print (n)
     n + = 1
else:
     print ('end')

result

0
1
2
3
Four
end

for, range

# test.py
# - * - coding: utf - 8 - * -
for a in [1, 2, 3]:
     print (a)
print ('---')
for b in {'one': 1, 'two': 2, 'three': 3}:
     print (b)
print ('---')
for c in "123":
     print (c)
print ('---')
# range
for d in range (3): From # 0
     print (d)

result

1
2
3
- -
one
two
three
- -
1
2
3
- -
0
1
2

break

# test.py
# - * - coding: utf - 8 - * -
# break
for n in range (5):
     if n == 3:
         break
     print (n)

result

0
1
2

continue

# test.py
# - * - coding: utf - 8 - * -
# continue
for n in range (5):
     if n == 3:
         continue
     print (n)

result

0
1
2
4

Exception handling

# test.py
# - * - coding: utf - 8 - * -
# Exceptions
str = '123'
try:
     IndexError occurs because c = str [10] # 10
except IOError:
     print ('IOError')
except IndexError:
     print ('IndexError')
except: # other exceptions
     print ('UnknownError')
else: # if the exception does not occur
     print ('Other')
finally: # Always run
     print ('Finally')

result

IndexError
Finally

function

no return

# test.py
# - * - coding: utf - 8 - * -
# method definition
def printAdd (x, y):
    print (x + y)
Run # method
printAdd (1, 2)

result

3

return

# test.py
# - * - coding: utf - 8 - * -
# method definition
def add (x, y):
    return x + y
Run # method
print (add (1, 2))

result

3

default parameter

# test.py
# - * - coding: utf - 8 - * -
# method definition
def repeat_output (msg, n = 3):
    for i in range (n):
        print (msg)
Run # method
repeat_output ('test1',)
print ('-----')
repeat_output ('test2', 5)

result

test1
test1
test1
-----
test2
test2
test2
test2
test2

[*]argument

# test.py
# - * - coding: utf - 8 - * -
# method definition
def method A (x, y, * args):
    print (x)
    print (y)
    print (args)
    print (args [0])
    print (args [1])
Run # method
method A ('x 1', 'y 1', 'Z 1', 'Z 2')

result

x1
y1
('Z1', 'Z2')
Z1
Z2

[**]argument

# test.py
# - * - coding: utf - 8 - * -
# method definition
def method A (x, y, ** args): # also receive dictionary type
    print (x)
    print (y)
    print (args)
    print (args ['k1'])
    print (args ['k2'])
Run # method
args = {'k1': 'v1', 'k2': 'v2'}
method A ('x1', 'y1', ** args) # also receive a dictionary type

result

x1
y1
{'k1': 'v1', 'k2': 'v2'}
v1
v2

Multiple return values

# test.py
# - * - coding: utf - 8 - * -
# method definition
def plusOne (x, y):
    return x + 1, y + 1
Run # method
x, y = plusOne (2, 4)
print (x, y)

result

3 5
Reference to global variable
test.py
# - * - coding: utf - 8 - * -
g = 100
def method_global ():
    print (g)
method_global ()
print (g)

result

100
100

Change global variable failed

# test.py
# - * - coding: utf - 8 - * -
g = 100
def method_global ():
    g = 200 # Overwrite method
    print (g)
method_global ()
print (g)

result

200
100

Successful change of global variable

# test.py
# - * - coding: utf - 8 - * -
g = 100
def method_global ():
    After declaring global g #global, it will be recognized.
    g = 200 # change global variable
    print (g)
method_global ()
print (g)

result

200
200

Class

Definition of class

# test.py
# - * - coding: utf - 8 - * -
# Definition of class
class SampleClass:
    "" "this is doc" "" # for doc
    def getName (self):
        return self.name
    def setName (self, name):
        self.name = name
# Create instance
a = SampleClass ()
a.setName ('luohao')
print (a.getName ())

result

luohao

class variable, instance variable

# test.py
# - * - coding: utf - 8 - * -
# Definition of class
class SampleClass:
    "" "this is doc" "" # for doc
    count = 0 #class variable
    def __init __ (self): # constructor
        SampleClass.count + = 1
    def getName (self):
        return self.name # instance variable
    def setName (self, name):
        self.name = name # instance variable
# Create instance
a = SampleClass ()
a.setName ('luohao 1')
print (a.getName (), SampleClass.count)
b = SampleClass ()
b.setName ('luohao 2')
print (b.getName (), SampleClass.count)

result

luohao 1 1
luohao 2 2

Access restriction (__)

# test.py
# - * - coding: utf - 8 - * -
# Definition of class
class SampleClass:
    "" "this is doc" "" # for doc
    def __init __ (self): # constructor
        self .__ name = 'privateName'
    def __getName (self):
        return self .__ name
# Create instance
a = SampleClass ()
print (a .__ name) # error
print (a .__ getName ()) # error

result

AttributeError: 'SampleClass' object has no attribute '__name'

init and del

# test.py
# - * - coding: utf - 8 - * -
# Definition of class
class SampleClass:
    def __init __ (self):
        print ('INIT!')
    def __del __ (self):
        print ('DELETE!')
x = SampleClass ()
del x

result

INIT!
DELETE!

Class inheritance

# test.py
# - * - coding: utf - 8 - * -
# Definition of class
class FatherClass:
    def sayFather (self):
        print ('im father')
# Definition of class
class SonClass (FatherClass): Inherit #father class
    def saySon (self):
        print ('im son')
# Create instance
son = SonClass ()
son.sayFather ()
son.saySon ()

result

im father
im son

class inheritance override

# test.py
# - * - coding: utf - 8 - * -
# Definition of class
class FatherClass:
    def sayFather (self):
        print ('im father')
# Definition of class
class SonClass (FatherClass): Inherit #father class
    def sayFather (self): #override
        print ('im son')
# Create instance
son = SonClass ()
son.sayFather ()

result

im son

Multiple inheritance of class

# test.py
# - * - coding: utf - 8 - * -
# Definition of class
class FatherClass:
    def sayFather (self):
        print ('im father')
class MotherClass:
    def sayMother (self):
        print ('im mother')
# Definition of class
class SonClass (FatherClass, MotherClass): Inherit #father class
    pass # Do nothing.
# Create instance
son = SonClass ()
son.sayFather ()
son.sayMother ()

result

im father
im mother

Model

# modelTest.py
# - * - coding: utf - 8 - * -
# model
# Definition of class
class ModelClass:
    def printModel (self):
        print ('im from model')
# test.py
# - * - coding: utf - 8 - * -
import modelTest #import
# instance generation from # model
a = modelTest.ModelClass ()
a.printModel ()

result

im from model

Package

# modelTest.py
# - * - coding: utf - 8 - * -
# model
# Definition of class
class ModelClass:
    def printModel (self):
        print ('im from model')
# test.py
# - * - coding: utf - 8 - * -
import modelTest #import
print (__ package__) # package name
print (__ file__) # File name
print (__ name__) # module name

result

None
test.py
__main__

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?