The method of programing(IPO):
What's IPO?
- I (Input) Put data into program.
- P (Process) The logic of processor.
- O (Output) Show data to users.
sample 1:
#Tempcover.py
TempStr = input("Please input the temperature with unit(C or F)")
if TempStr[-1] in ['F','f']:
C = (eval(TempStr[0:-1]) - 32)/1.8
print("result is {:.2f}C".format(C))
elif TempStr[-1] in ['C','c']:
F = 1.8*eval(TempStr[0:-1]) + 32
print("result is {:.2f}F".format(F))
else:
print("format error")
-
Indent
Indent is a measure that shows the relationship of statement. We can use a TAB or four SPACE to do a indent. It should be noted that we have to choose one way or the other.
-
Comment
- Single-Line Comment: start with #.
- Multi-Line Comments: start with ''' and end with same '''.
-
Variable
Regulation of names only use limited sign that contains letter,number,underline or characters,but cannot start with number.
-
String
-
serial number
id_1 id_2 id_3 id_4 id_5 -5 -4 -3 -2 -1 H E L L O 0 1 2 3 4 -
index
We can use method
to get single character,such as[index] "Hello"[0]
orTempStr[-1]
-
section
We can use method
to get a sub-string,such as[start:end] "Hello"[1:3]
orTempStr[0:-1]
-
eval()
Evaluation function: this function can execute string as code.
-
What's turtle?
Turtle is a principle library in Python.The turtle has three attributes: a location, an orientation (or direction), and a pen. The pen, too, has attributes: color, width, and on/off state.
sample 2:
#PythonDraw.py
import turtle as t
t.setup(650,350,200,200)
t.penup()
t.fd(-250)
t.pendown()
t.pensize(25)
t.seth(-40)
for i in range(4):
t.circle(40,80)
t.circle(-40,80)
t.circle(40,80/2)
t.fd(40)
t.circle(16,180)
t.fd(40 * 2/3)
t.done()
-
Window
The minimum unit of painting window is pixel.
-
turtle.setup(width,height,start_X,start_Y)
this function can set window's size and position,such as
turtle.setup(800,400,0,0)
orturtle.setup(800,400)
-
-
**Coordinate System **
-
absolute coordinate system
This is a rectangular coordinate system that take the center as the origin.
-
turtle.goto(x,y)
this function will let's turtle move to target position.
-
-
turtle coordinate system
This is a coordinate system that center as turtle self.
-
turtle.forward(distance)/turtle.fd(distance)
let's turtle forward some distance.
-
turtle.back(distance)/turtle.bk(distance)
let's turtle back some distance.
-
turtle.circle(radius,angle)
draw arc that take the left radius as the center of a circle.
-
-
-
Angle System
-
absolute angle system
This is a polar system that take the window's center as origin.
-
turtle.setheading(angle)/turtle.seth(a)
This function can alter turtle's orient.
-
-
turtle angle system
This is a angle system that center as turtle self.
- turtle.left(angle)
- turtle.right(angle)
-
-
Color Mode
-
turtle.colormode(mode)
if
mode = 1.0
means that use decimals color mode.if
mode = 255
means that use integer color mode.such as
import turtle as t t.colormode(1.0) # t.colormode(255)
-
-
Library Reference
-
import
,such as import turtle turtle.left(45)
-
from
import / import *,such as from turtle import * left(45)
-
import
as import turtle as t t.left(45)
-
-
Pen Controller
-
turtle.penup()/turtle.pu()
This function can make turtle fly - turtle can move but not drawing.
-
turtle.pendown()/turtle.pd()
This function can make turtle crawl - turtle can move and painting.
turtle.pensize(width)/turtle.width(w)
-
turtle.pencolor(color)
if we select decimals color mode , we should set color as decimals,such as
turtle.colormode(1.0) turtle.pencolor(0.63,0.13,0.94) # turtle.pencolor((0.63,0.13,0.94))
if we select integer color mode, we should set color as integer that not more than 255, such as
turtle.colormode(255) turtle.pencolor(255,255,255)
or we can use string of color name directly,such as
turtle.pencolor("purple")
-
Number's Type
- Decimal:such as
1010
or-216
... - Binary:start with 0b or 0B,such as
0b101
or-0B1100
... - Octonary:start with 0o or 0O,such as
0o123
or-0O456
... - hexadecimal:start with 0x or 0X,such as
0x9a
or-0X89
...
Complex Number
Complex number is made up of real number and imaginary number. In Python, imaginary unit is 'j'
i = 3 + 2j
i.real #3.0
i.imag #2.0
Number's Operator
Operator | Description |
---|---|
x +y | Plus |
x – y | Minus |
x *y | Multiply |
x /y | Divide,return is a float number |
x // y | Exact Division such as 10//3 is 3 |
x | x's self |
-y | negative y |
x %y | Modular,such as 10%3 is 1 |
x ** y | Power,x^y |
Number's Operate function
Fuction | Description |
---|---|
abs(x) | Absolution, abs( -10.01) is 10.01 |
divmod (x,y ) | get quotient and remainder at once |
pow(x, y[ , z]) | get power and remainder at once |
xround(x round(x [,d]) | round off with decimals |
max(x 1,x 2, … , , … xn) | return max number among parameters's list |
min(x 1,x 2, … , , … xn) | return min number among parameters's list |
int (x ) | change number type to Integer type |
float(x) | change number type to Float type |
complex(x) | change number type to Complex type |
Sample 3:Progress's power
code 1:
dayfactor = 0.005
dayup = pow(1+dayfactor, 365)
daydown = pow(1-dayfactor, 365)
print("Progress:{:.2f},Retrogress:{:.2f}".format(dayup, daydown))
code 2:
def dayUP(df):
dayup = 1
for i in range(365):
if i % 7 in [6,0]:
dayup = dayup*(1 - 0.01)
else:
dayup = dayup*(1 + df)
return dayup
dayfactor = 0.01
while dayUP(dayfactor) < 37.78:
dayfactor += 0.001
print("工作日的努力参数是:{:.3f} ".format(dayfactor))
Python's String
String is an orderly sequence of character, represent as a pair of single quote or double quote.The form that expression of string is:
- String of single line: represent as a pair of single quote or double quote.
- String of multi-line: represent as a triple of single quote or double quote. such as:
s1 = 'Hello world'
s2 = '''
line1,
line2'''
Usage of String
-
[M,N], cut string from M to N. such as:
"0123456789"[:3]
is"012"
-
[M,N,K], cut string from M to N with K step. such as:
"0123456789"[::2]
is"02468"
or
"0123456789"[:3:-1]
is"210"
String's Operator
Operator | Description |
---|---|
x+ y | connected with x and y |
n *x or x *n | copy string x n times |
x in s | if x is substring of x, return true |
String's Operate Function
Function | Description |
---|---|
len (x) | return string x's length |
str (x) | change any type to string |
hex(x) or oct (x) | return number's Octonary or hexadecimal type |
String's Function
Function | Description |
---|---|
str.lower () or str.upper () | return a copy of str that lower case or upper case |
str.split (sep =None) | return a list split with sep |
str.count (sub) | returns the number of occurrences of sub in str |
str.replace(old, new) | returns copy of str that all old substring replace with new |
Format of String
usage is:
Python Time Library
time is principle library in Python:
- Expression of represent in computer time.
- Get system time and output with format.
- Offer exact timer that system level to analyze program.
usage:
import time
time.()
-
time.time()
get current system time
-
time.ctime()
get current system time in readable, such as
'Fri Jan 26 12:11:16 2018'
-
time.gmtime()
get formatable time.
Branch Structures
single branch:
if :
double branch:
if :
else:
multi-branch structures:
if :
elif :
...
else:
Function is a group of statements that do appointed manner, a abstract of ability.
such as:
def fact(n):
s = 1
for i in range(1,n+1)
s *= i
return s
python's function define is
def ():
return
sample 7: Number Drawing
The idea and method of to drawing date:
- method 1: draw picture with corresponding number;
- method 2: change time's number to formated string of time;
- method 3: get system's time number.
Method Thought
- Hierachy: the system of designed should be divided by module;
- Modularity: there has definite function and interface in module;
- Regularity: the module of designed must be use repeatable.
How to Comprehend Method Thought
Take Number Drawing as an example, we should split complexed problems to smaller part of function as follows: Firstly, we should a function that named drawNumber to draw number in screen;Secondly,we also need a function that named drawDate to parse system's time string-deal number and text respectively.
The function and object are two main formation of code use repeatable: function is a prime abstraction in code level, and object is a high-level abstract that based on function.
The Divide-and-Conquer algorithm is an expression that divide sub-module in complex system with function or wrapper, and also is a designed thought to implement abstraction.
Collection
Collection is a group that contains elements. The property of collection is as follows: Firstly, the data cannot be repeatable in collection. Secondly, the type of collection's element is invariable.
How to represent collection in python
The collection in python represent in brace({}
), and elements in it split as comma(,
). If we want to build a collection type , we must use brace or function that named set(set(vargs...
). notice: build a empty collection must use set function.
sample:
collection = {1,"hello",3.1415}
empty_collection = set()
Operator in collection
Operator | Description |
---|---|
S|T | OR: this function will return all elements both Collection S and T. |
S-T | Minus: this function will return part of elements that contained in Collection S but not in T. |
S&T | Intersection: this function will return common elements that contained Collection S and T. |
S^T | Supplementary: this function will return part of elements that contained in Collection S and T, but not both contained in S and T. |
Sequence
Sequence is a group of elements that has relation of order.
List
List is a basic data structure in python. Every element in List was contributed a number - its site or index, first index is 0,second is 1 ,and so on. List and Tuple are common type of Sequence in Python. Common function in List contains that get index, split, plus and multiply. List is common type in Python, is represent as bracket, elements split in comma. Example as follows:
l1 = ['hello world', 3.1415, 2019]
l2 = [1, 2, 3, 4, 5 ]
Like String, the index of List started as 0.
Tuple
Like List, Tuple is common type of Sequence in Python. But the element in Tuple cannot be change. Tuple use parenthesis but List use bracket.
How to create a Tuple
It's very simple that create a object of Tuple in Python, just add element in parenthesis and split in comma. Example as follows:
t1 = ('Hello World!', 3.1415, 2019)
t2 = (1, 2, 3, 4, 5 )
Sample 10: Count Statistic of Character in Romance of the Three Kingdoms(《三国演义》)
APPENDIX A: Sample 7, Date Drawing
import turtle as tt
line_length = 14 #px
line_width = 2 #px
number_width = 20 #px
line_split = 3 #px
def isDraw(number):
list = []
if number == 0:
list = [True,True,True,True,True,True,False]
elif number == 1:
list = [False,False,True,True,False,False,False]
elif number == 2:
list = [False,True,True,False,True,True,True]
elif number == 3:
list = [False,True,True,True,True,False,True]
elif number == 4:
list = [True,False,True,True,False,False,True]
elif number == 5:
list = [True,True,False,True,True,False,True]
elif number == 6:
list = [True,True,False,True,True,True,True]
elif number == 7:
list = [False,True,True,True,False,False,False]
elif number == 8:
list = [True,True,True,True,True,True,True]
elif number == 9:
list = [True,True,True,True,True,False,True]
return list
def alterAngle(i):
angle = 0
if i == 0 or i == 5:
angle = 90
elif i == 1 or i == 6:
angle = 0
elif i == 2 or i == 3:
angle = -90
elif i == 4:
angle = 180
return angle
def drawNumber(number):
tt.pensize(line_width)
ids = isDraw(number)
for i in range(7):
tt.pu()
angle = alterAngle(i)
tt.seth(angle)
tt.fd(line_split)
if(ids[i]):
tt.pd()
tt.fd(line_length)
tt.pu()
tt.fd(line_split)
return
def drawDate(date):
#$date:date string
front = ("Arial",number_width*10,"normal")
tt.pencolor("red")
for i in date:
if i == '-':
tt.write('年',front)
tt.pencolor("blue")
elif i == '=':
tt.write('月',front)
tt.pencolor("green")
elif i == '+':
tt.write('日',front)
else:
drawNumber(int(i))
tt.fd(number_width/1.5)
return
import time
tt.pu()
tt.goto(-150,0)
tt.seth(0)
tt.pd()
tstr = time.strftime('%Y-%m=%d+',time.gmtime())
drawDate(tstr)
APPENDIX B Sample 10: Count Statistic of Character in Romance of the Three Kingdoms(《三国演义》)
#CalHamlete.py
import jieba as jb
txt = open("e://sg1.txt","r",encoding = "utf-8").read()
names = {"孔明":"诸葛亮",\
"诸葛亮":"诸葛亮",\
"孔明曰":"诸葛亮",\
"关公":"关羽",\
"云长":"关羽",\
"关羽":"关羽",\
"曹操":"曹操",\
"孟德":"曹操",\
"丞相":"曹操",\
"刘备":"刘备",\
"玄德":"刘备",\
"玄德曰":"刘备"}
words = jb.lcut(txt)
counts = {}
for word in words:
if word in names:
counts[names[word]] = counts.get(names[word],0) + 1
items = list(counts.items())
items.sort(key = lambda x:x[1],reverse = True)
for item in items:
word,count = item
print("{0:<10}{1:>5}".format(word,count))