# Chapter 10 Introducing Python Statements

Python Program Structure Revisited

At its core, Python syntax is composed of statements and expressions. Expressions
process objects and are embedded in statements. Statements code the larger logic of a
program’s operation—they use and direct expressions to process the objects we studied
in the preceding chapters. Moreover, statements are where objects spring into existence
(e.g., in expressions within assignment statements), and some statements create entirely new kinds of objects (functions, classes, and so on). Statements always exist in
modules, which themselves are managed with statements.

This chapter climbs the hierarchy to the next level:
1. Programs are composed of modules.
2. Modules contain statements.
3. Statements contain expressions.
4. Expressions create and process objects.

# A Few Special Cases

As mentioned previously, in Python’s syntax model:
• The end of a line terminates the statement on that line (without semicolons).
• Nested statements are blocked and associated by their physical indentation (without braces).

```python
a = 1; b = 2; print(a + b) # Three statements on one line
```

    3

```python
mlist = [111,
         222,
         333]
```

```python
print(mlist)
```

    [111, 222, 333]

Parentheses are the catchall device—because any expression can be wrapped up in
them, simply inserting a left parenthesis allows you to drop down to the next line and
continue your statement:

```python
from sympy import *
```

```python
A, B, C, D = symbols('A, B , C , D')
```

```python
X = symbols('X')
```

```python
X = A + B + C + D
```

```python
if (A == 1 and
    B == 2 and
    C == 3):
    print('spam'*3)
```

    spamspamspam

```python
A, B, C = 1, 2, 3
```

```python
exec('print("spam");'*3)
```

    spam
    spam
    spam

An older rule also allows for continuation lines when the prior line ends in a backslash:

```python
X = A + B + \
C + D
```

```python
X
```

$\displaystyle D + 6$

This alternative technique is dated, though, and is frowned on today because it’s difficult to notice and maintain the backslashes, and it’s fairly brittle—there can be no
spaces after the backslash, and omitting it can have unexpected effects if the next line
is mistaken to be a new statement. It’s also another throwback to the C language, where
it is commonly used in “#define” macros; again, when in Pythonland, do as Pythonistas
do, not as C programmers do.

# Block rule special case

```python
x, y = 26,57
if x > y: print(x)
```

# A Simple Interactive Loop

# Doing Math on User Inputs

```python
while True:
    reply = input('Enter text:')
    if reply == 'stop': break
    print(int(reply) ** 2)
print('Bye')
```

    Enter text: 4546

    20666116

    Enter text: 2313213

    5350954383369

    Enter text: 4545

    20657025

    Enter text: 54545

    2975157025

    Enter text: 4545

    20657025

    Enter text: 4545

    20657025

    Enter text: 48636

    2365460496

    Enter text: stop

    Bye

# Handling Errors by Testing Inputs

```python
S = '123'
T = 'xxx'
S.isdigit(), T.isdigit()
```

    (True, False)

```python
while True:
    reply = input('Enter text:')
    if reply == 'stop':
        break
    elif not reply.isdigit():
        print('Bad!' * 8)
    else:
        print(int(reply) ** 2)
print('Bye')
```

    Enter text: 24

    576

    Enter text: 45

    2025

    Enter text: asdf

    Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad!

    Enter text: stop

    Bye

# Handling Errors with try Statements

```python
while True:
    reply = input('Enter text:')
    if reply == 'stop': break
    try:
        num = int(reply)
    except:
        print('Bad!' * 8)
    else:
        print(int(reply) ** 2)
print('Bye')
```

    Enter text: 456

    207936

    Enter text: dasd

    Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad!

    Enter text: '454'

    Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad!

    Enter text: stop

    Bye

# Nesting Code Three Levels Deep

```python
while True:
    reply = input('Enter text:')
    if reply == 'stop':
        break
    elif not reply.isdigit():
        print('Bad!' * 8)
    else:
        num = int(reply)
        if num < 20:
            print('low')
        else:
            print(num ** 2)
print('Bye')
```

    Enter text: 454

    206116

    Enter text: 4

    low

    Enter text: stop

    Bye

# Chapter Summary

That concludes our quick look at Python statement syntax. This chapter introduced
the general rules for coding statements and blocks of code. As you’ve learned, in Python
we normally code one statement per line and indent all the statements in a nested block
the same amount (indentation is part of Python’s syntax). However, we also looked at
a few exceptions to these rules, including continuation lines and single-line tests and
loops. Finally, we put these ideas to work in an interactive script that demonstrated a
handful of statements and showed statement syntax in action.
In the next chapter, we’ll start to dig deeper by going over each of Python’s basic procedural statements in depth. As you’ll see, though, all statements follow the same general rules introduced here.

```python
import sys
from tkinter import *

class HelloClass:
    def __init__(self):
        widget = Button(None, text = 'Hello event world', command = self.quit)
        widget.pack()

    def quit(self):
        print('Hello class method world')
        sys.exit()

HelloClass()
mainloop()
```

```python
# coding:utf-8
import turtle as t
import time

#皮卡丘

#基础设置
t.screensize(800,600)
t.pensize(2) # 设置画笔的大小
t.speed(10) # 设置画笔速度为10

#画左偏曲线函数
def radian_left(ang,dis,step,n):
    for i in range(n):
        dis+=step #dis增大step
        t.lt(ang) #向左转ang度
        t.fd(dis) #向前走dis的步长

def radian_right(ang,dis,step,n):
    for i in range(n):
        dis+=step
        t.rt(ang) #向左转ang度
        t.fd(dis) #向前走dis的步长

#画耳朵
def InitEars():

    t.color("black","yellow")
    #左耳朵曲线
    t.pu() # 提笔
    t.goto(-50,100) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(110)#画笔角度

    t.begin_fill()

    radian_left(1.2,0.4,0.1,40)

    t.setheading(270) #画笔角度
    radian_left(1.2,0.4,0.1,40)

    t.setheading(44) #画笔角度
    t.forward(32)
    t.end_fill()

    #右耳朵曲线
    t.pu() # 提笔
    t.goto(50,100) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(70)#画笔角度

    t.begin_fill()
    radian_right(1.2,0.4,0.1,40)

    t.setheading(270) #画笔角度
    radian_right(1.2,0.4,0.1,40)

    t.setheading(136) #画笔角度
    t.forward(32)
    t.end_fill()

    #耳朵黑

    t.begin_fill()
    t.fillcolor("black")
    t.pu() # 提笔
    t.goto(88,141) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(35)#画笔角度

    radian_right(1.2,1.6,0.1,16)

    t.setheading(270) #画笔角度
    radian_right(1.2,0.4,0.1,25)

    t.setheading(132) #画笔角度
    t.forward(31)
    t.end_fill()

    t.begin_fill()
    t.fillcolor("black")
    t.pu() # 提笔
    t.goto(-88,141) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(145)#画笔角度

    radian_left(1.2,1.6,0.1,16)

    t.setheading(270) #画笔角度
    radian_left(1.2,0.4,0.1,25)

    t.setheading(48) #画笔角度
    t.forward(31)
    t.end_fill()

 #画尾巴
def InitTail():
    #尾巴
    t.begin_fill()
    t.fillcolor("yellow")
    t.pu() # 提笔
    t.goto(64,-140) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(10) #画笔角度
    t.forward(20)
    t.setheading(90) #画笔角度
    t.forward(20)
    t.setheading(10) #画笔角度
    t.forward(10)
    t.setheading(80) #画笔角度
    t.forward(100)
    t.setheading(35) #画笔角度
    t.forward(80)
    t.setheading(260) #画笔角度
    t.forward(100)
    t.setheading(205) #画笔角度
    t.forward(40)
    t.setheading(260) #画笔角度
    t.forward(37)
    t.setheading(205) #画笔角度
    t.forward(20)
    t.setheading(260) #画笔角度
    t.forward(25)
    t.setheading(175) #画笔角度
    t.forward(30)
    t.setheading(100) #画笔角度
    t.forward(13)
    t.end_fill()

#画脚
def InitFoots():
    #脚
    t.begin_fill()
    t.fillcolor("yellow")
    t.pensize(2)
    t.pu() # 提笔
    t.goto(-70,-200) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(225) #画笔角度
    radian_left(0.5,1.2,0,12)
    radian_left(35,0.6,0,4)
    radian_left(1,1.2,0,18)
    t.setheading(160) #画笔角度
    t.forward(13)
    t.end_fill()

    t.begin_fill()
    t.fillcolor("yellow")
    t.pensize(2)
    t.pu() # 提笔
    t.goto(70,-200) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(315) #画笔角度
    radian_right(0.5,1.2,0,12)
    radian_right(35,0.6,0,4)
    radian_right(1,1.2,0,18)
    t.setheading(20) #画笔角度
    t.forward(13)
    t.end_fill()

#画身体
def InitBody():
    #外形轮廓
    t.begin_fill()
    t.pu() # 提笔
    t.goto(112,0) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(90) #画笔角度
    t.circle(112,180)

    t.setheading(250) #画笔角度

    radian_left(1.6,1.3,0,50)

    radian_left(0.8,1.5,0,25)

    t.setheading(255) #画笔角度
    radian_left(0.4,1.6,0.2,27)

    radian_left(2.8,1,0,45)
    radian_right(0.9,1.4,0,31)

    t.setheading(355) #画笔角度
    radian_right(0.9,1.4,0,31)

    radian_left(2.8,1,0,45)

    radian_left(0.4,7.2,-0.2,27)

    t.setheading(10) #画笔角度
    radian_left(0.8,1.5,0,25)

    radian_left(1.6,1.3,0,50)

    t.end_fill()

def InitEyes():
    #左眼睛
    t.begin_fill()
    t.fillcolor("black")
    t.pu() # 提笔
    t.goto(-46,10) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(90) #画笔角度
    t.circle(5,360)
    t.end_fill()

    #右眼睛
    t.begin_fill()
    t.fillcolor("black")
    t.pu() # 提笔
    t.goto(46,10) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(-90) #画笔角度
    t.circle(5,360)
    t.end_fill()

#画脸
def InitFace():
    #脸蛋
    t.begin_fill()
    t.fillcolor("red")
    t.pu() # 提笔
    t.goto(-63,-10) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(90) #画笔角度
    t.circle(10,360)
    t.end_fill()

    t.begin_fill()
    t.fillcolor("red")
    t.pu() # 提笔
    t.goto(63,-10) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(-90) #画笔角度
    t.circle(10,360)
    t.end_fill()

    #嘴巴
    t.pensize(2.2)
    t.pu() # 提笔
    t.goto(0,0) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(235) #画笔角度
    radian_right(5,0.8,0,30)

    t.pu() # 提笔
    t.goto(0,0) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(305) #画笔角度
    radian_left(5,0.8,0,30)

#画手
def InitHands():
    #左手
    t.pensize(2)
    t.pu() # 提笔
    t.goto(-46,-100) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(285) #画笔角度
    radian_right(0.4,1.2,0,26)
    radian_right(5,0.35,0,26)
    radian_right(0.3,1.2,0,15)

    #右手
    t.pu() # 提笔
    t.goto(46,-100) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(255) #画笔角度
    radian_left(0.4,1.2,0,26)
    radian_left(5,0.35,0,26)
    radian_left(0.3,1.2,0,15)

def CloseEyes():
    #左眼睛
    t.pu() # 提笔
    t.goto(-46,12) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(180) #画笔角度
    t.forward(10)

    #右眼睛
    t.pu() # 提笔
    t.goto(46,12) # 笔头初始位置
    t.pd() # 下笔
    t.setheading(0) #画笔角度
    t.forward(10)

#初始化
def Init():
    InitEars()
    InitTail()
    InitFoots()
    InitBody()
    InitFace()
    InitHands()
    InitEyes()

 #眨眼睛
def Upgarde():
    InitEars()
    InitTail()
    InitFoots()
    InitBody()
    InitFace()
    InitHands()
    CloseEyes()

def Upgarde_Init():
    InitEars()
    InitTail()
    InitFoots()
    InitBody()
    InitFace()
    InitHands()
    InitEyes()

def main():

    Init()

    t.tracer(False)

    #眨眼睛动画
    for i in range(30):
        if i%2==0:
            t.reset()
            t.hideturtle()
            Upgarde()
            t.update()
            time.sleep(0.3)
        else:
            t.reset()
            t.hideturtle()
            Upgarde_Init()
            t.update()
            time.sleep(1)

main()

#结束画笔
t.done()
```

```python
import turtle as T
import random
import time

# 画樱花的躯干(60,t)
def Tree(branch, t):
    time.sleep(0.000005)
    if branch > 3:
        if 8 <= branch <= 12:
            if random.randint(0, 2) == 0:
                t.color('snow')  # 白
            else:
                t.color('lightcoral')  # 淡珊瑚色
            t.pensize(branch / 3)
        elif branch < 8:
            if random.randint(0, 1) == 0:
                t.color('snow')
            else:
                t.color('lightcoral')  # 淡珊瑚色
            t.pensize(branch / 2)
        else:
            t.color('sienna')  # 赭(zhě)色
            t.pensize(branch / 10)  # 6
        t.forward(branch)
        a = 1.5 * random.random()
        t.right(20 * a)
        b = 1.5 * random.random()
        Tree(branch - 10 * b, t)
        t.left(40 * a)
        Tree(branch - 10 * b, t)
        t.right(20 * a)
        t.up()
        t.backward(branch)
        t.down()

# 掉落的花瓣
def Petal(m, t):
    for i in range(m):
        a = 200 - 400 * random.random()
        b = 10 - 20 * random.random()
        t.up()
        t.forward(b)
        t.left(90)
        t.forward(a)
        t.down()
        t.color('lightcoral')  # 淡珊瑚色
        t.circle(1)
        t.up()
        t.backward(a)
        t.right(90)
        t.backward(b)

# 绘图区域
t = T.Turtle()
# 画布大小
w = T.Screen()
t.hideturtle()  # 隐藏画笔
t.getscreen().tracer(5, 0)
w.screensize(bg='wheat')  # wheat小麦
t.left(90)
t.up()
t.backward(150)
t.down()
t.color('sienna')

# 画樱花的躯干
Tree(79, t)
# 掉落的花瓣
Petal(200, t)
w.exitonclick()
```

```python
from turtle import *
from random import *
from math import *

def tree(n,l):
    pd()#下笔
    #阴影效果
    t = cos(radians(heading()+45))/8+0.25
    pencolor(t,t,t)
    pensize(n/3)
    forward(l)#画树枝

    if n>0:
        b = random()*15+10 #右分支偏转角度
        c = random()*15+10 #左分支偏转角度
        d = l*(random()*0.25+0.7) #下一个分支的长度
        #右转一定角度,画右分支
        right(b)
        tree(n-1,d)
        #左转一定角度，画左分支
        left(b+c)
        tree(n-1,d)
        #转回来
        right(c)
    else:
        #画叶子
        right(90)
        n=cos(radians(heading()-45))/4+0.5
        pencolor(n,n*0.8,n*0.8)
        circle(3)
        left(90)
        #添加0.3倍的飘落叶子
        if(random()>0.7):
            pu()
            #飘落
            t = heading()
            an = -40 +random()*40
            setheading(an)
            dis = int(800*random()*0.5 + 400*random()*0.3 + 200*random()*0.2)
            forward(dis)
            setheading(t)
            #画叶子
            pd()
            right(90)
            n = cos(radians(heading()-45))/4+0.5
            pencolor(n*0.5+0.5,0.4+n*0.4,0.4+n*0.4)
            circle(2)
            left(90)
            pu()
            #返回
            t=heading()
            setheading(an)
            backward(dis)
            setheading(t)
    pu()
    backward(l)#退回

bgcolor(0.5,0.5,0.5)#背景色
ht()#隐藏turtle
speed(2)#速度 1-10渐进，0 最快
tracer(0,0)
pu()#抬笔
backward(100)
left(90)#左转90度
pu()#抬笔
backward(300)#后退300
tree(12,100)#递归7层
done()
```

```python
from turtle import *
from random import *
from math import *

def tree(n, l):
    pd()
    t = cos(radians(heading() + 45)) / 8 + 0.25
    pencolor(t, t, t)
    pensize(n / 4)
    forward(l)
    if n > 0:
        b = random() * 15 + 10
        c = random() * 15 + 10
        d = l * (random() * 0.35 + 0.6)
        right(b)
        tree(n - 1, d)
        left(b + c)
        tree(n - 1, d)
        right(c)
    else:
        right(90)
        n = cos(radians(heading() - 45)) / 4 + 0.5
        pencolor(n, n, n)
        circle(2)
        left(90)
    pu()
    backward(l)
bgcolor(0.5, 0.5, 0.5)
ht()
speed(5)
tracer(0, 0)
left(90)
pu()
backward(300)
tree(20, 100)
done()
```

```python
from turtle import *
import random
import time

n = 100.0

speed(10)
screensize(bg='seashell')
left(90)
forward(3*n)
color("orange", "yellow")
begin_fill()
left(126)

for i in range(5):
    forward(n/5)
    right(144)
    forward(n/5)
    left(72)
end_fill()
right(126)

color("dark green")
backward(n*4.8)
def tree(d, s):
    if d <= 0: return
    forward(s)
    tree(d-1, s*.8)
    right(120)
    tree(d-3, s*.5)
    right(120)
    tree(d-3, s*.5)
    right(120)
    backward(s)
tree(15, n)
backward(n/2)

for i in range(200):
    a = 200 - 400 * random.random()
    b = 10 - 20 * random.random()
    up()
    forward(b)
    left(90)
    forward(a)
    down()
    if random.randint(0, 1) == 0:
            color('tomato')
    else:
        color('wheat')
    circle(2)
    up()
    backward(a)
    right(90)
    backward(b)

# time.sleep(60)
```

```python
# 魔法少女
import turtle as te
import time
WriteStep = 5000  # 贝塞尔函数的取样次数
Speed = 5
Width = 1800  # 界面宽度
Height = 1800  # 界面高度
Xh = 0  # 记录前一个贝塞尔函数的手柄
Yh = 0

def Bezier(p1, p2, t):  # 一阶贝塞尔函数
    return p1 * (1 - t) + p2 * t

def Bezier_2(x1, y1, x2, y2, x3, y3):  # 二阶贝塞尔函数
    te.goto(x1, y1)
    te.pendown()
    for t in range(0, WriteStep + 1):
        x = Bezier(Bezier(x1, x2, t / WriteStep),
                   Bezier(x2, x3, t / WriteStep), t / WriteStep)
        y = Bezier(Bezier(y1, y2, t / WriteStep),
                   Bezier(y2, y3, t / WriteStep), t / WriteStep)
        te.goto(x, y)
    te.penup()

def Bezier_3(x1, y1, x2, y2, x3, y3, x4, y4):  # 三阶贝塞尔函数
    x1 = -Width / 2 + x1
    y1 = Height / 2 - y1
    x2 = -Width / 2 + x2
    y2 = Height / 2 - y2
    x3 = -Width / 2 + x3
    y3 = Height / 2 - y3
    x4 = -Width / 2 + x4
    y4 = Height / 2 - y4  # 坐标变换
    te.goto(x1, y1)
    te.pendown()
    for t in range(0, WriteStep + 1):
        x = Bezier(Bezier(Bezier(x1, x2, t / WriteStep), Bezier(x2, x3, t / WriteStep), t / WriteStep),
                   Bezier(Bezier(x2, x3, t / WriteStep), Bezier(x3, x4, t / WriteStep), t / WriteStep), t / WriteStep)
        y = Bezier(Bezier(Bezier(y1, y2, t / WriteStep), Bezier(y2, y3, t / WriteStep), t / WriteStep),
                   Bezier(Bezier(y2, y3, t / WriteStep), Bezier(y3, y4, t / WriteStep), t / WriteStep), t / WriteStep)
        te.goto(x, y)
    te.penup()

def Moveto(x, y):  # 移动到svg坐标下（x，y）
    te.penup()
    te.goto(-Width / 2 + x, Height / 2 - y)

def line(x1, y1, x2, y2):  # 连接svg坐标下两点
    te.penup()
    te.goto(-Width / 2 + x1, Height / 2 - y1)
    te.pendown()
    te.goto(-Width / 2 + x2, Height / 2 - y2)
    te.penup()

def lineto(dx, dy):  # 连接当前点和相对坐标（dx，dy）的点
    te.pendown()
    te.goto(te.xcor() + dx, te.ycor() - dy)
    te.penup()

def Lineto(x, y):  # 连接当前点和svg坐标下（x，y）
    te.pendown()
    te.goto(-Width / 2 + x, Height / 2 - y)
    te.penup()

def Horizontal(x):  # 做到svg坐标下横坐标为x的水平线
    te.pendown()
    te.setx(x - Width / 2)
    te.penup()

def horizontal(dx):  # 做到相对横坐标为dx的水平线
    te.seth(0)
    te.pendown()
    te.fd(dx)
    te.penup()

def vertical(dy):  # 做到相对纵坐标为dy的垂直线
    te.seth(-90)
    te.pendown()
    te.fd(dy)
    te.penup()
    te.seth(0)

def polyline(x1, y1, x2, y2, x3, y3):  # 做svg坐标下的折线
    te.penup()
    te.goto(-Width / 2 + x1, Height / 2 - y1)
    te.pendown()
    te.goto(-Width / 2 + x2, Height / 2 - y2)
    te.goto(-Width / 2 + x3, Height / 2 - y3)
    te.penup()

def Curveto(x1, y1, x2, y2, x, y):  # 三阶贝塞尔曲线到（x，y）
    te.penup()
    X_now = te.xcor() + Width / 2
    Y_now = Height / 2 - te.ycor()
    Bezier_3(X_now, Y_now, x1, y1, x2, y2, x, y)
    global Xh
    global Yh
    Xh = x - x2
    Yh = y - y2

def curveto_r(x1, y1, x2, y2, x, y):  # 三阶贝塞尔曲线到相对坐标（x，y）
    te.penup()
    X_now = te.xcor() + Width / 2
    Y_now = Height / 2 - te.ycor()
    Bezier_3(X_now, Y_now, X_now + x1, Y_now + y1,
             X_now + x2, Y_now + y2, X_now + x, Y_now + y)
    global Xh
    global Yh
    Xh = x - x2
    Yh = y - y2

def Smooth(x2, y2, x, y):  # 平滑三阶贝塞尔曲线到（x，y）
    global Xh
    global Yh
    te.penup()
    X_now = te.xcor() + Width / 2
    Y_now = Height / 2 - te.ycor()
    Bezier_3(X_now, Y_now, X_now + Xh, Y_now + Yh, x2, y2, x, y)
    Xh = x - x2
    Yh = y - y2

def smooth_r(x2, y2, x, y):  # 平滑三阶贝塞尔曲线到相对坐标（x，y）
    global Xh
    global Yh
    te.penup()
    X_now = te.xcor() + Width / 2
    Y_now = Height / 2 - te.ycor()
    Bezier_3(X_now, Y_now, X_now + Xh, Y_now + Yh,
             X_now + x2, Y_now + y2, X_now + x, Y_now + y)
    Xh = x - x2
    Yh = y - y2

te.tracer(10)
te.setup(Width, Height, 0, 0)
te.pensize(1)
te.speed(Speed)
te.penup()

# 图层_2
# time.sleep(20)
te.color("black", "#F2F2F2")  # 外套
Moveto(61, 462)
te.begin_fill()
smooth_r(12, -41, 27, -58)
curveto_r(-6, -36, 6, -118, 9, -132)
curveto_r(-15, -27, -23, -51, -26, -74)
curveto_r(4, -66, 38, -105, 65, -149)
Horizontal(486)
curveto_r(12, 24, 40, 99, 33, 114)
curveto_r(39, 82, 55, 129, 39, 144)
smooth_r(-31, 23, -39, 28)
smooth_r(-12, 37, -12, 37)
lineto(50, 92)
Horizontal(445)
smooth_r(-29, -38, -31, -46)
smooth_r(78, -107, 72, -119)
Smooth(355, 178, 340, 176)
Smooth(272, 63, 264, 64)
smooth_r(-29, 67, -27, 73)
Curveto(99, 292, 174, 428, 173, 439)
smooth_r(-8, 23, -8, 23)
Lineto(61, 462)
te.end_fill()

Moveto(60.5, 461.5)  # 阴影
te.color("black", "#D3DFF0")
te.begin_fill()
curveto_r(0, 0, 17, -42, 27, -59)
curveto_r(-6, -33, 6, -128, 10, -133)
curveto_r(-15, -10, -27, -66, -27.285, -75)
te.pencolor("#D3DFF0")
curveto_r(12.285, 11, 82.963, 156, 82.963, 156)
te.pencolor("black")
smooth_r(12.322, 75, 19.322, 86)
curveto_r(-1, 11, -8, 25, -8, 25)
Horizontal(60.5)
te.end_fill()

Moveto(444.5, 464)
te.begin_fill()
curveto_r(0, 0, -29, -36, -31, -46)
smooth_r(53.59, -82.337, 53.59, -82.337)
te.pencolor("#D3DFF0")
smooth_r(86.41, -47.663, 96.072, -54.85)
Curveto(563.5, 297.5, 570.5, 299.5, 518.5, 334)
te.pencolor("black")
curveto_r(-2, 16, -12, 33, -12, 37)
smooth_r(50, 92, 50, 93)
Horizontal(444.5)
te.end_fill()

Moveto(195, 49)
te.begin_fill()
te.pencolor("#D3DFF0")
polyline(195, 49, 175.5, 106.5, 202.522, 49)
te.pencolor("black")
Horizontal(195)
te.pencolor("#D3DFF0")
te.end_fill()

Moveto(327.997, 49)
te.begin_fill()
te.pencolor("#D3DFF0")
curveto_r(0, 0, 11.503, 121.087, 13.503, 128.087)
curveto_r(11, 2, 54, 37, 54, 37)
lineto(-40, -165.087)
te.pencolor("black")
Horizontal(327.997)
te.pencolor("#D3DFF0")
te.end_fill()

te.pencolor("black")
line(94.5, 397.5, 107.5, 373.5)  # 皱纹
line(122.5, 317.5, 95.875, 274.699)
line(122.5, 341.5, 141.5, 402.5)
line(141.5, 409.5, 153.5, 431.5)
# line(328,47.712,344,175.977)
line(340.023, 49, 360.5, 144)
# line(353.5,47.5,395.5,208.5)
line(478.5, 95.5, 518.5, 161.5)
line(518.5, 332.5, 460.5, 359.5)
polyline(506.5, 369.5, 493.5, 402.5, 502.5, 443.5)
Moveto(530, 429)
curveto_r(4, 16, -5, 33, -5, 33)

# 图层_3
te.color("black", "#2b1d2a")  # 外套内侧
Moveto(225, 462)
te.begin_fill()
Horizontal(165)
smooth_r(9, -15, 8, -25)
curveto_r(-47, -126, 6, -212, 12, -225)
Curveto(185, 305, 202, 428, 225, 462)
Lineto(225, 462)
te.end_fill()

Moveto(390, 462)
te.begin_fill()
curveto_r(10, -23, 34, -180, 35, -222)  # !!!227
curveto_r(7, 4, 54, 45, 61, 61)  # 61
smooth_r(-73, 101, -72, 118)
curveto_r(5, 15, 31, 46, 31, 45)
Lineto(390, 462)
te.end_fill()
# 图层_4
te.color("black", "#2b1d29")  # 外套内侧
Moveto(225, 462)
te.begin_fill()
curveto_r(-28, -50, -40, -166, -40, -250)
curveto_r(6, 51, -6, 87, 45, 106)
smooth_r(64, 27, 89, 24)
smooth_r(49, -18, 56, -20)
smooth_r(50, -10, 51, -85)
curveto_r(0, 29, -25, 201, -36, 225)
Lineto(225, 462)
te.end_fill()
# 图层_5
te.color("black", "#3D3D3D")  # 衣服
Moveto(225, 462)
te.begin_fill()
curveto_r(-5, -5, -22, -53, -23, -70)
lineto(32, -13)
curveto_r(3, -25, 6, -28, 12, -36)
smooth_r(13, -12, 16, -12)
vertical(-2)
curveto_r(45, 20, 64, 14, 94, 1)
vertical(2)
curveto_r(8, -2, 15, 2, 17, 4)
smooth_r(0, 6, -2, 9)
curveto_r(10, 10, 10, 29, 11, 33)
smooth_r(23, 4, 25, 6)
smooth_r(-17, 83, -17, 78)
Lineto(225, 462)
te.end_fill()
# 图层_6
te.color("black", "#968281")  # 脖子
Moveto(262, 329)
te.begin_fill()
vertical(17)
curveto_r(1, 2, 44, 14, 45, 15)
smooth_r(3, 12, 3, 12)
horizontal(3)
vertical(-5)
curveto_r(1, -3, 4, -6, 5, -7)
lineto(36, -14)
curveto_r(1, -1, 3, -16, 2, -17)
Curveto(318, 348, 296, 344, 262, 329)
te.end_fill()
# 图层_8
te.color("black", "#E7F1FF")  # 白色褶皱
Moveto(225, 462)
te.begin_fill()
lineto(-3, -5)  # -3,-3,-3,-5
curveto_r(0, -2, 4, -4, 5, -6)
smooth_r(16, 3, 19, -8)
smooth_r(0, -7, 0, -11)
smooth_r(5, -8, 9, -5)
smooth_r(19, -8, 19, -11)
smooth_r(6, -7, 6, -7)
smooth_r(7, -2, 9, -4)
lineto(41, -2)
lineto(12, 9)
smooth_r(3, 15, 7, 18)
smooth_r(15, 4, 17, 4)
smooth_r(4, -4, 6, -4)
smooth_r(6, 4, 5, 9)
smooth_r(0, 9, 0, 9)
smooth_r(1, 7, 7, 6)
smooth_r(8, 0, 8, 0)
lineto(-2, 8)
Lineto(225, 462)
te.end_fill()

te.pensize(2)
Moveto(240, 450)
smooth_r(0, 9, 3, 12)
Moveto(372, 462)
curveto_r(-2, -4, -5, -29, -7, -28)
te.pensize(1)
# 图层_7
te.color("black", "#A2B8D6")  # 衣领
Moveto(262, 331)
te.begin_fill()
curveto_r(0, 8, -1, 13, 0, 15)
smooth_r(43, 14, 45, 15)
lineto(3, 12)
horizontal(3)
smooth_r(-1, -3, 0, -5)
lineto(5, -7)
lineto(36, -14)
curveto_r(1, -1, 2, -12, 2, -15)
smooth_r(25, -2, 15, 13)
curveto_r(-2, 4, -7, 29, -7, 32)
smooth_r(-35, 19, -41, 22)
smooth_r(-9, 14, -12, 14)
smooth_r(-7, -12, -14, -15)
curveto_r(-19, -2, -41, -25, -41, -25)
smooth_r(-10, -26, -10, -30)
Smooth(255, 332, 262, 331)
te.end_fill()

Moveto(262, 346)
lineto(-12, -6)
Moveto(369, 333)
curveto_r(2, 4, -6, 10, -15, 14)
# 图层_9
te.color("black", "#151515")  # 领结
Moveto(247, 358)
te.begin_fill()
curveto_r(-5, 3, -8, 20, -6, 23)
curveto_r(25, 21, 50, 17, 50, 17)
lineto(-23, 64)
horizontal(22)
smooth_r(1, -13, 2, -16)
lineto(13, -50)
curveto_r(2, 2, 7, 3, 10, 1)
smooth_r(18, 65, 18, 65)
horizontal(19)
lineto(-24, -65)
curveto_r(21, 5, 39, -10, 44, -13)
curveto_r(5, -20, 1, -21, 0, -24)
curveto_r(-18, -2, -49, 15, -52, 17)
smooth_r(-11, -3, -15, -1)
Smooth(252, 356, 247, 358)
te.end_fill()
# 图层_10
te.color("black", "#A2B8D6")  # 衣领（透过领结）
Moveto(297, 387)
te.begin_fill()
lineto(-11, 6)
curveto_r(-1, 0, -20, -7, -30, -19)
Curveto(259, 373, 297, 385, 297, 387)
te.end_fill()

Moveto(323, 384)
te.begin_fill()
lineto(8, 7)
lineto(30, -14)
curveto_r(1, -1, 5, -6, 4, -7)
Smooth(329, 379, 323, 384)
te.end_fill()
# 图层_11
te.color("black", "#F3EEEB")  # 脸
Moveto(185, 212)
te.begin_fill()
curveto_r(4, -9, 46, -77, 52, -75)
curveto_r(-2, -17, 19, -68, 27, -73)
curveto_r(16, 15, 71, 108, 76, 112)
smooth_r(76, 53, 86, 60)
curveto_r(0, 65, -27, 75, -31, 76)
curveto_r(-50, 28, -70, 30, -85, 30)
smooth_r(-77, -22, -86, -26)
Curveto(180, 302, 186, 228, 185, 212)
te.end_fill()
# 图层_12
te.color("black", "#2B1D29")  # 头发
Moveto(189, 202)
te.begin_fill()
curveto_r(-1, 22, 19, 51, 19, 51)
smooth_r(-10, -42, 7, -92)
Curveto(212, 168, 196, 189, 189, 202)
te.end_fill()

Moveto(221, 155)
te.begin_fill()
curveto_r(-2, 6, 5, 48, 5, 48)
smooth_r(18, -28, 20, -48)
curveto_r(-5, 24, 4, 43, 7, 50)
curveto_r(-10, -49, 3, -72, 13, -106)
curveto_r(-2, -7, -3, -32, -3, -35)
curveto_r(-17, 18, -27, 71, -27, 71)
Lineto(221, 155)
te.end_fill()

Moveto(264, 64)
te.begin_fill()
curveto_r(-4, 5, 14, 100, 14, 100)
smooth_r(-6, -79, -5, -85)
curveto_r(0, 98, 49, 139, 49, 139)
smooth_r(8, -50, 3, -65)
Smooth(272, 64, 264, 64)
te.end_fill()

Moveto(342, 176)
te.begin_fill()
curveto_r(-1, 27, -10, 57, -10, 57)
smooth_r(20, -33, 17, -54)
Lineto(342, 176)
te.end_fill()

te.penup()
te.begin_fill()
polyline(349, 180, 353, 203, 361, 203)
polyline(361, 203, 362, 188, 349, 180)
te.end_fill()
# 图层_13
te.pensize(2)
Moveto(210, 180)  # 眉毛
curveto_r(5, -4, 63, 9, 63, 14)
Moveto(338, 193)
curveto_r(0, -3, 18, -6, 18, -6)
te.pensize(1)
# 图层_14
te.color("black", "#D1D1D1")  # 眼睛1
te.pensize(2)
Moveto(206, 212)
te.begin_fill()
lineto(15, -7)
curveto_r(4, -1, 26, -2, 30, 0)
smooth_r(10, 3, 12, 7)
te.pencolor("#D1D1D1")
te.pensize(1)
smooth_r(2, 27, -1, 30)
smooth_r(-39, 5, -44, 1)
Smooth(206, 212, 206, 212)
te.end_fill()

Moveto(384, 204)
te.begin_fill()
te.pencolor("black")
te.pensize(2)
curveto_r(-3, -1, -18, -1, -28, 1)
smooth_r(-9, 6, -10, 9)
te.pencolor("#D1D1D1")
te.pensize(1)
smooth_r(3, 18, 6, 23)
smooth_r(38, 6, 40, 4)
smooth_r(10, -9, 13, -22)
te.pencolor("black")
te.pensize(2)
Lineto(384, 204)
te.end_fill()
# 图层_15
te.color("#0C1631", "#0C1631")  # 眼睛2
te.pensize(1)
Moveto(216, 206)
te.begin_fill()
curveto_r(-1, 5, 0, 26, 7, 35)
smooth_r(30, 2, 33, 0)
smooth_r(5, -31, 2, -34)
Smooth(219, 203, 216, 206)
te.end_fill()

Moveto(354, 207)
te.begin_fill()
curveto_r(-2, 1, 2, 29, 4, 31)
smooth_r(30, 3, 33, 1)
smooth_r(6, -24, 4, -27)
lineto(-11, -8)
Curveto(382, 204, 357, 206, 354, 207)
te.end_fill()

# 图层_17
te.color("#F5F5F5", "#F5F5F5")  # 眼睛3
Moveto(253, 211)
te.begin_fill()
curveto_r(-3, 0, -8, 8, 1, 10)
Smooth(258, 210, 253, 211)
te.end_fill()

Moveto(392, 209)
te.begin_fill()
lineto(4, 3)
vertical(4)
lineto(-4, 2)
Curveto(386, 214, 392, 209, 392, 209)
te.end_fill()
# 图层_18
te.color("#352F53", "#352F53")  # 眼睛4
Moveto(219, 229)
te.begin_fill()
smooth_r(2, -5, 6, -4)
smooth_r(18, 13, 27, 1)
curveto_r(3, 0, 5, 3, 5, 3)
vertical(13)
Horizontal(224)
Lineto(219, 229)
te.end_fill()

Moveto(357, 227)
te.begin_fill()
smooth_r(4, -6, 10, -2)
smooth_r(10, 13, 19, 1)
curveto_r(6, 0, 8, 6, 8, 6)
lineto(-2, 9)
curveto_r(-12, 3, -29, 0, -32, -2)
Smooth(357, 227, 357, 227)
te.end_fill()

# 图层_19
te.color("#9A90CB", "#9A90CB")  # 眼睛5
Moveto(227, 231)
te.begin_fill()
curveto_r(-6, 0, -5, 5, -3, 8)
smooth_r(24, 2, 27, 0)
smooth_r(0, -8, -1, -8)
Smooth(234, 231, 227, 231)
te.end_fill()

Moveto(361, 227)
te.begin_fill()
curveto_r(2, 18, 26, 14, 30, 6)
smooth_r(-1, -3, -2, -4)
smooth_r(-15, 9, -24, -4)
Curveto(363, 224, 361, 225, 361, 227)
te.end_fill()

# 图层_16
te.pencolor("black")  # 眼睛(线条)
te.pensize(3)
# Moveto(206,213)
# lineto(14,-8)
# curveto_r(3,-1,30,0,33,1)
# lineto(10,6)
Moveto(225, 215)
curveto_r(10, 28, 22, 16, 24, 6)
Moveto(365, 219)
curveto_r(4, 14, 18, 24, 22, -3)
te.pensize(2)
line(240.5, 207.5, 227.5, 211.5)
line(245.5, 209.5, 227.5, 214.5)
line(247.5, 211.5, 227.5, 217.5)
line(247.5, 214.5, 229.5, 220.5)
line(247.5, 218.5, 230.5, 223.5)
line(246.5, 222.5, 232.5, 226.5)
line(244.5, 225.5, 234.5, 228.5)

line(377.5, 207.5, 367.5, 210.5)
line(384.5, 207.5, 366.5, 212.5)
line(385.5, 210.5, 366.5, 215.5)
line(384.5, 213.5, 366.5, 218.5)
line(384.5, 215.5, 367.5, 220.5)
line(384.5, 218.5, 368.5, 223.5)
# line(383.5,220.5,368.5,225.5)
line(382.5, 223.5, 370.5, 227.5)
# line(381.5,226.5,373.5,229.5)
# 图层_20
te.pencolor("black")
Moveto(309, 270)  # 鼻子、嘴
curveto_r(0, 0, 4, 7, 1, 9)
line(296.5, 307.5, 303.5, 307.5)
Moveto(315, 307)
smooth_r(10, -1, 10, 2)

te.penup()
te.hideturtle()
te.update()
te.done()

```

```python
import turtle as T
import random
import time

# 画樱花的躯干(60,t)
def Tree(branch, t):
    t.hideturtle()
    time.sleep(0.00009)
    if branch > 3:
        if 8 <= branch <= 12:
            if random.randint(0, 2) == 0:
                t.color('snow')  # 白
            else:
                t.color('lightcoral')  # 淡珊瑚色
            t.pensize(branch / 3)
        elif branch < 8:
            if random.randint(0, 1) == 0:
                t.color('snow')
            else:
                t.color('lightcoral')  # 淡珊瑚色
            t.pensize(branch / 2)
        else:
            t.color('sienna')  # 赭(zhě)色
            t.pensize(branch / 10)  # 6
        t.forward(branch)
        a = 1.5 * random.random()
        t.right(20 * a)
        b = 1.5 * random.random()
        Tree(branch - 10 * b, t)
        t.left(40 * a)
        Tree(branch - 10 * b, t)
        t.right(20 * a)
        t.up()
        t.backward(branch)
        t.down()
        T

# 掉落的花瓣
def Petal(m, t):
    T.speed(0)
    for i in range(m):
        a = 200 - 400 * random.random()
        b = 10 - 20 * random.random()
        t.up()
        t.forward(b)
        t.left(90)
        t.forward(a)
        t.down()
        t.color('lightcoral')  # 淡珊瑚色
        t.circle(1)
        t.up()
        t.backward(a)
        t.right(90)
        t.backward(b)

# 绘图区域
t = T.Turtle()
# 画布大小
w = T.Screen()
t.hideturtle()  # 隐藏画笔
T.showturtle()
t.getscreen().tracer(5, 0)
w.screensize(3000,3000,bg='wheat')  # wheat小麦
t.left(90)
t.up()
t.backward(150)
t.down()
t.color('sienna')
t.hideturtle()
T.speed(0)

# 画樱花的躯干
Tree(79, t)
# 掉落的花瓣
Petal(200, t)
w.exitonclick()

```

```python
from turtle import *
colors = ['red', 'purple', 'blue', 'green', 'yellow', 'orange']
for x in range(360):
    pencolor(colors[x % 6])
    width(x / 100 + 1)
    forward(x)
    left(59)
```

```python
a,*b = 'spam'
```

```python
a,b
```

    ('s', ['p', 'a', 'm'])

```python
spam = ham = 'lunch'
```

```python
spam += str(42)
```

```python
spam
```

    'lunch4242'

```python
nudge = 1
wink = 2
A, B = nudge, wink
print(A, B)
[C, D] = [nudge, wink]
print(C,D)
```

    1 2
    1 2

# Advanced sequence assignment patterns

```python
string = 'SPAM'
a, b, c, d = string
```

```python
a, d
```

    ('S', 'M')

```python
a, b, c, d
```

    ('S', 'P', 'A', 'M')

```python
a, b, c = string[0], string[1], string[2:] #Index and slice
```

```python
a, b, c
```

    ('S', 'P', 'AM')

```python
a, b, c = list(string[:2]) + [string[2:]]
```

```python
a, b, c
```

    ('S', 'P', 'AM')

```python
(a, b), c = string[:2], string[2:]
```

```python
a, b, c
```

    ('S', 'P', 'AM')

```python
((a, b), c) = ('SP',"AM") # Paired by shape and position
```

```python
a, b, c
```

    ('S', 'P', 'AM')

```python
red, green, blue = range(3)
```

```python
red, blue
```

    (0, 2)

```python
L = [1,2,3,4]
while L:
    front, L = L[0], L[1:] # See next section for 3.0 alternative
    print(front, L)
```

    1 [2, 3, 4]
    2 [3, 4]
    3 [4]
    4 []

```python
L =[1,2,3,4]
while L:
    front = L.pop(0)
    print(front, L)
```

    1 [2, 3, 4]
    2 [3, 4]
    3 [4]
    4 []

```python
seq = [1,2,3,4]
a, b, c, d = seq
print(a, b, c, d)
```

    1 2 3 4

```python
a, *b = seq
```

```python
a, b
```

    (1, [2, 3, 4])

```python
*a, b = seq
```

```python
a, b
```

    ([1, 2, 3], 4)

```python
a, *b, c = seq
```

```python
a, b, c
```

    (1, [2, 3], 4)

```python
a, b, *c = seq
```

```python
a, *b = 'spam'
```

```python
print(a,b)
a, *b, c = 'spam'
a, b, c
```

    s ['p', 'a', 'm']

    ('s', ['p', 'a'], 'm')

# Boundary cases

```python
seq
```

    [1, 2, 3, 4]

```python
a, b, c, *d = seq
print(a, b, c, d)
```

    1 2 3 [4]

```python
a, b, c, d, *e = seq
print(a,b,c,d,e)
```

    1 2 3 4 []

```python
a, b, *e, c, d = seq
```

```python
print(a,b,c,d,e)
```

    1 2 3 4 []

```python
*a, = seq
```

```python
a
```

    [1, 2, 3, 4]

```python
T = (seq[1]) # A one-item tuple (not an expression)
```

```python
type(T), type((seq[1],))
```

    (int, tuple)

```python
seq
```

    [1, 2, 3, 4]

```python
a, *b = seq
```

```python
a, b
```

    (1, [2, 3, 4])

```python
a, b = seq[0], seq[1:] # First, rest : traditional
```

```python
a, b
```

    (1, [2, 3, 4])

```python
for (a, *b, c) in [(1,2,3,4),(5,6,7,8),(9,10,11,12)]:
    print(a,b,c)
```

    1 [2, 3] 4
    5 [6, 7] 8
    9 [10, 11] 12

```python
for allnum in [(1,2,3,4),(5,6,7,8)]:
    a, b, c = allnum[0], allnum[1:3], allnum[3]
```

# Multiple-Target Assignments

```python
a = b = c = 'spam'
a, b, c
```

    ('spam', 'spam', 'spam')

```python
c = 'spam'
b = c
a = b
```

```python
T= []
T.append([123, 'xyz', 'zara', 'abc'])
```

```python
T
```

    [[123, 'xyz', 'zara', 'abc']]

# Multiple-target assignment and shared references

```python
a = b = 0
b = b + 1
a, b
```

    (0, 1)

Here, changing b only changes b because numbers do not support in-place changes. As
long as the object assigned is immutable, it’s irrelevant if more than one name references
it.

```python
a = b = []
b.append(42)
print(a,b)
```

    [42] [42]

As usual, though, we have to be more cautious when initializing variables to an empty mutable object such as a list or dictionary:

This time, because a and b reference the same object, appending to it in-place through
b will impact what we see through a as well. This is really just another example of the
shared reference phenomenon we first met in Chapter 6. To avoid the issue, initialize
mutable objects in separate statements instead, so that each creates a distinct empty
object by running a distinct literal expression:

```python
a = []
b = []
b.append(42)
print(a,b)
```

    [] [42]

# Augmented Assignments

```python
a = a + b
print(a)
a += b
print(a)
```

    [42]
    [42, 42]

Table 11-2. Augmented assignment statements
X += Y  X &= Y  X -= Y  X |= Y
X *= Y  X ^= Y  X /= Y  X >>= Y
X %= Y  X <<= Y X **= Y X //= Y

```python
# a &= b unsupported operand type(s) for &=: 'list' and 'list'
```

```python
a, b = 36, 42
a &= b
```

```python
bin(36),bin(42)
```

    ('0b100100', '0b101010')

```python
bin(32)
```

    '0b100000'

```python
36 & 42, 1 & 1, 1 & 2, 1 & 3
```

    (32, 1, 0, 1)

```python
for i in range(40):
    print(1 & i, end = ',')
```

    0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,

```python
for i in range(50):
    print(36 & i, end = ', ')
    print(bin(36), bin(i), bin(36 & i), sep=', ')
```

    0, 0b100100, 0b0, 0b0
    0, 0b100100, 0b1, 0b0
    0, 0b100100, 0b10, 0b0
    0, 0b100100, 0b11, 0b0
    4, 0b100100, 0b100, 0b100
    4, 0b100100, 0b101, 0b100
    4, 0b100100, 0b110, 0b100
    4, 0b100100, 0b111, 0b100
    0, 0b100100, 0b1000, 0b0
    0, 0b100100, 0b1001, 0b0
    0, 0b100100, 0b1010, 0b0
    0, 0b100100, 0b1011, 0b0
    4, 0b100100, 0b1100, 0b100
    4, 0b100100, 0b1101, 0b100
    4, 0b100100, 0b1110, 0b100
    4, 0b100100, 0b1111, 0b100
    0, 0b100100, 0b10000, 0b0
    0, 0b100100, 0b10001, 0b0
    0, 0b100100, 0b10010, 0b0
    0, 0b100100, 0b10011, 0b0
    4, 0b100100, 0b10100, 0b100
    4, 0b100100, 0b10101, 0b100
    4, 0b100100, 0b10110, 0b100
    4, 0b100100, 0b10111, 0b100
    0, 0b100100, 0b11000, 0b0
    0, 0b100100, 0b11001, 0b0
    0, 0b100100, 0b11010, 0b0
    0, 0b100100, 0b11011, 0b0
    4, 0b100100, 0b11100, 0b100
    4, 0b100100, 0b11101, 0b100
    4, 0b100100, 0b11110, 0b100
    4, 0b100100, 0b11111, 0b100
    32, 0b100100, 0b100000, 0b100000
    32, 0b100100, 0b100001, 0b100000
    32, 0b100100, 0b100010, 0b100000
    32, 0b100100, 0b100011, 0b100000
    36, 0b100100, 0b100100, 0b100100
    36, 0b100100, 0b100101, 0b100100
    36, 0b100100, 0b100110, 0b100100
    36, 0b100100, 0b100111, 0b100100
    32, 0b100100, 0b101000, 0b100000
    32, 0b100100, 0b101001, 0b100000
    32, 0b100100, 0b101010, 0b100000
    32, 0b100100, 0b101011, 0b100000
    36, 0b100100, 0b101100, 0b100100
    36, 0b100100, 0b101101, 0b100100
    36, 0b100100, 0b101110, 0b100100
    36, 0b100100, 0b101111, 0b100100
    32, 0b100100, 0b110000, 0b100000
    32, 0b100100, 0b110001, 0b100000

```python
a, b = 36, 42
a -= b
print(a)
a, b = 36, 42
a |= b
print(a)
```

    -6
    46

```python
bin(36), bin(42), bin(46)
```

    ('0b100100', '0b101010', '0b101110')

```python
import pandas as pd
target_url = "http://aima.cs.berkeley.edu/data/iris.csv"
data = pd.read_csv(target_url, header=None)
data.describe()
```

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>0</th>
      <th>1</th>
      <th>2</th>
      <th>3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>count</td>
      <td>150.000000</td>
      <td>150.000000</td>
      <td>150.000000</td>
      <td>150.000000</td>
    </tr>
    <tr>
      <td>mean</td>
      <td>5.843333</td>
      <td>3.054000</td>
      <td>3.758667</td>
      <td>1.198667</td>
    </tr>
    <tr>
      <td>std</td>
      <td>0.828066</td>
      <td>0.433594</td>
      <td>1.764420</td>
      <td>0.763161</td>
    </tr>
    <tr>
      <td>min</td>
      <td>4.300000</td>
      <td>2.000000</td>
      <td>1.000000</td>
      <td>0.100000</td>
    </tr>
    <tr>
      <td>25%</td>
      <td>5.100000</td>
      <td>2.800000</td>
      <td>1.600000</td>
      <td>0.300000</td>
    </tr>
    <tr>
      <td>50%</td>
      <td>5.800000</td>
      <td>3.000000</td>
      <td>4.350000</td>
      <td>1.300000</td>
    </tr>
    <tr>
      <td>75%</td>
      <td>6.400000</td>
      <td>3.300000</td>
      <td>5.100000</td>
      <td>1.800000</td>
    </tr>
    <tr>
      <td>max</td>
      <td>7.900000</td>
      <td>4.400000</td>
      <td>6.900000</td>
      <td>2.500000</td>
    </tr>
  </tbody>
</table>
</div>

```python
a, b = 36, 42
a *= b
print(a)
print(36*42)
a = 36; b = 42; a^=b; print(a)
```

    1512
    1512
    14

```python
36 ^ 42; print(bin(36), bin(42),bin(14))
```

    0b100100 0b101010 0b1110

```python
import pandas as pd
data = pd.read_csv('F:\house-votes-84.data',header= None)
data.head(434)
```

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>0</th>
      <th>1</th>
      <th>2</th>
      <th>3</th>
      <th>4</th>
      <th>5</th>
      <th>6</th>
      <th>7</th>
      <th>8</th>
      <th>9</th>
      <th>10</th>
      <th>11</th>
      <th>12</th>
      <th>13</th>
      <th>14</th>
      <th>15</th>
      <th>16</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>republican</td>
      <td>n</td>
      <td>y</td>
      <td>n</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>n</td>
      <td>n</td>
      <td>n</td>
      <td>y</td>
      <td>?</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>n</td>
      <td>y</td>
    </tr>
    <tr>
      <td>1</td>
      <td>republican</td>
      <td>n</td>
      <td>y</td>
      <td>n</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>n</td>
      <td>n</td>
      <td>n</td>
      <td>n</td>
      <td>n</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>n</td>
      <td>?</td>
    </tr>
    <tr>
      <td>2</td>
      <td>democrat</td>
      <td>?</td>
      <td>y</td>
      <td>y</td>
      <td>?</td>
      <td>y</td>
      <td>y</td>
      <td>n</td>
      <td>n</td>
      <td>n</td>
      <td>n</td>
      <td>y</td>
      <td>n</td>
      <td>y</td>
      <td>y</td>
      <td>n</td>
      <td>n</td>
    </tr>
    <tr>
      <td>3</td>
      <td>democrat</td>
      <td>n</td>
      <td>y</td>
      <td>y</td>
      <td>n</td>
      <td>?</td>
      <td>y</td>
      <td>n</td>
      <td>n</td>
      <td>n</td>
      <td>n</td>
      <td>y</td>
      <td>n</td>
      <td>y</td>
      <td>n</td>
      <td>n</td>
      <td>y</td>
    </tr>
    <tr>
      <td>4</td>
      <td>democrat</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>n</td>
      <td>y</td>
      <td>y</td>
      <td>n</td>
      <td>n</td>
      <td>n</td>
      <td>n</td>
      <td>y</td>
      <td>?</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
    </tr>
    <tr>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
    </tr>
    <tr>
      <td>429</td>
      <td>democrat</td>
      <td>y</td>
      <td>n</td>
      <td>y</td>
      <td>n</td>
      <td>?</td>
      <td>n</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>n</td>
      <td>y</td>
      <td>n</td>
      <td>?</td>
      <td>y</td>
      <td>y</td>
    </tr>
    <tr>
      <td>430</td>
      <td>republican</td>
      <td>n</td>
      <td>n</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>n</td>
      <td>n</td>
      <td>y</td>
      <td>y</td>
      <td>n</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>n</td>
      <td>y</td>
    </tr>
    <tr>
      <td>431</td>
      <td>democrat</td>
      <td>n</td>
      <td>n</td>
      <td>y</td>
      <td>n</td>
      <td>n</td>
      <td>n</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>n</td>
      <td>n</td>
      <td>n</td>
      <td>n</td>
      <td>n</td>
      <td>y</td>
    </tr>
    <tr>
      <td>432</td>
      <td>republican</td>
      <td>n</td>
      <td>?</td>
      <td>n</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>n</td>
      <td>n</td>
      <td>n</td>
      <td>n</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>n</td>
      <td>y</td>
    </tr>
    <tr>
      <td>433</td>
      <td>republican</td>
      <td>n</td>
      <td>n</td>
      <td>n</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>?</td>
      <td>?</td>
      <td>?</td>
      <td>?</td>
      <td>n</td>
      <td>y</td>
      <td>y</td>
      <td>y</td>
      <td>n</td>
      <td>y</td>
    </tr>
  </tbody>
</table>
<p>434 rows × 17 columns</p>
</div>

```python
36 ^ 42; print(bin(36), bin(42),bin(14))
```

    0b100100 0b101010 0b1110

```python
L1 = []
for i in range(len(str(bin(36)))):
    L1.append(str(bin(36))[i])
L2 = []
for j in range(len(str(bin(42)))):
    L2.append(str(bin(42))[j])
```

```python
print(L1); print(L2)
```

    ['0', 'b', '1', '0', '0', '1', '0', '0']
    ['0', 'b', '1', '0', '1', '0', '1', '0']

```python
T = []
print(type(T))
for k in range(len(L1)):
    T.append((L1[k],L2[k]))
```

    <class 'list'>

```python
print(T)
```

    [('0', '0'), ('b', 'b'), ('1', '1'), ('0', '0'), ('0', '1'), ('1', '0'), ('0', '1'), ('0', '0')]

```python
S1 = ''
for m in range(2,len(L1)):
    if T[m][0] == T[m][1]:
        S1 +='0'
    else:
        S1 +='1'
```

```python
S2 = ''
for m in range(2,len(L1)):
    S2 += str(eval(T[m][0]) & eval(T[m][1]))
```

```python
print(S1,S2); S1 = '0b'+ S1; S2 = '0b'+ S2; print(eval(S1)); print(eval(S2))
```

    001110 100000
    14
    32

```python
a = 36; b = 42;
```

```python
a/=b
print(a)
```

    0.8571428571428571

```python
print(36/42); a == 36/42
```

    0.8571428571428571

    True

```python
a = 36; b =42; a>>=b; print(a); print(bin(36),bin(42))
```

    0
    0b100100 0b101010

```python
print(int(36/(2**42)) == 0); print(36<<42 == 36*2**42)
```

    True
    True

```python
print(8>>3 == 8/(2**3))
```

    True

```python
print(8%3); print(42%36); a = 42%36; print(a)
```

    2
    6
    6

```python
a = 42; b = 36; a**=b; print(a, a==42**36);
```

    27351078395457093635779121514268739090397938600214219718656 True

```python
a = 42; b = 36; a //=b; print(a,a==42//36)
```

    1 True

```python
import requests
from lxml import etree
from bs4 import BeautifulSoup

headers = {'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3970.5 Safari/537.36"}
url='https://www.cnblogs.com/JYNNO1/p/10525649.html'  #输入我们的url
get = requests.get(url) # get(url) 得到我们的网页, text将源网页转化为字符串
soup = BeautifulSoup(get.content, 'html.parser')
text = soup.find_all(text=True)
set([t.parent.name for t in text])
output = ''
blacklist = [
    '[document]',
 'a',
 'body',
 'div',
 'h1',
 'h2',
 'head',
 'html',
 'li',
 'p',
 'pre',
 'script',
 'span',
 'title',
 'ul'
]
for t in text:
    if t.parent.name not in blacklist:
        output += '{} '.format(t)
```

```python
print(output)
```

```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.cnblogs.com/JYNNO1/p/10525649.html'
res = requests.get(url)
html_page = res.content
soup = BeautifulSoup(html_page, 'html.parser')
text = soup.find_all(text=True)

output = ''
blacklist = [
    '[document]',
    'noscript',
    'header',
    'html',
    'meta',
    'head',
    'input',
    'script',
    # there may be more elements you don't want, such as "style", etc.
]

for t in text:
    if t.parent.name not in blacklist:
        output += '{} '.format(t)

print(output,end=';  ')
```

    Python-位操作( &、 | 、^、~ 、>>、 <<) - 已经崩盘了 - 博客园

     done

     done
     已经崩盘了

     end: blogTitle 博客的标题和副标题
     end: header 头部

    博客园

    首页

    新随笔

    联系

    管理

    订阅

     done
    随笔-
    17
    文章-
    0
    评论-
    0

    			 end: blogStats
     end: navigator 博客导航栏

     done

     Python-位操作( &、 | 、^、~ 、>>、 <<)

     用于提高运算速度，规避算术运算符。
     在位操作运算中，不应该试图考虑先得到一个数的二进制码，而应该将这个数看作是一个二进制码，二进制补码与整数之间是一一对应的。诚然 Python语言中有内置函数  bin将一个整数转换为二进制，Python中使用该函数转换为负数并不是其补码。因此不能先得到该数的二进制码。同时绞尽脑汁得到一个数的二进制补码是没有必要的。
     &：按位与操作，只有 1 &1 为1，其他情况为0。 可用于进位运算 。
     |：按位或操作，只有 0|0为0，其他情况为1。
     ~：逐位取反。
     ^：异或，相同为0，相异为1。 可用于加操作（不包括进位项）。
     <<：左移操作，2的幂相关
     >>：右移操作，2的幂相关
     判断一个整数的二进制补码中 1 的个数：
     　　既然一个整数在计算机内部为二进制的补码，那么直接对整数进行位操作即可，没有必要进行进制的转换。
     　　1）将整数通过移位并与1进行与操作，即可判断当时末尾是否为1. 但是 由于整数以二进制补码的方式存储，正数右移与负数右移得到的效果并不相同，负数在右移过程中会自动补 1 .由于在c 或c++这种语言中数据的类型要先声明，如 int为32位，而在python中，由于动态语言的特性，数据的位数理想上是不受限制的，因此可通过 移位的次数进行判断，int型数据移位不能超过32即可，这样程序的循环次数恒定为32.

      1   class  Solution:
      2       def  NumberOf1(self, n):
      3           #  write code here
      4          m =  0
      5          result =  0
      6
      7           while  m < 32 :
      8               if  n & 1 :
      9                  result += 1
     10              n = n >> 1
     11              m += 1
     12           return  result

     　　2）：同样的，可以通过左移 1 再与输入值进行与操作进行判断。 仍然是由于Python不会存在溢出现象 ，因此需要用到 数据类型的位数，进行限制。

      1   class  Solution():
      2       def  getResult(self, n):
      3          m = 1
      4          result =  0
      5          i =  0
      6
      7           while  i < 32 :
      8              i += 1
      9               if  m& n :
     10                  result += 1
     11              m = m << 1
     12           return  result

     　　3）一个二进制减一再于自身与操作能够将最后一位1置零。如 1011-1 = 1010 1010&1011 = 1010、1010-1 = 1001 1001 & 1010 = 1000、1000-1 = 0111 0111 &1000 = 0000
     但是 ，Python不会溢出，因此负数在进行持续减一 的运算， 若通过当前值是否为0进行循环终止条件会导致死循环 。因此需要为正负数分别设定终止条件。

      1   class  Solution2():
      2       def  getResult(self, n):
      3          result =  0
      4           if  n >=  0:
      5               while  n:
      6                  result += 1
      7                  n = (n - 1)& n
      8           else :
      9               while  n >=  -2147483648 :
     10                  result += 1
     11                  n = (n - 1)& n
     12           return  result

     　　4）：一个负数必然对应一个正数，先通过加法运算得到负数的相反数，这样可以将负数当作正数进行操作，唯一不同的是，负数的符号位要多一个 1

      1   #  -*- coding:utf-8 -*-
      2   class  Solution:
      3       def  NumberOf1(self, n):
      4           #  write code here
      5          result =  0
      6
      7           if  n <  0:
      8              n = n + (1<<31 )
      9              result += 1
     10          result += bin(n)[2:].count( ' 1 ' )
     11           return  result

     　　5）：结合方法 4 与 3之前的方法：

      1   #  -*- coding:utf-8 -*-
      2   class  Solution:
      3       def  NumberOf1(self, n):
      4           #  write code here
      5          result =  0
      6
      7           if  n <  0:
      8              n = n + (1<<31 )
      9              result += 1
     10           while  n:
     11              result += 1
     12              n = n&(n-1 )
     13           return  result

     posted @
     2019-03-14 21:16
     已经崩盘了
    阅读( ... )
    评论( ... )
     编辑
     收藏

     end: topics 文章、评论容器

     刷新评论 刷新页面 返回顶部

     end: forFlow
     end: mainContent 主体内容容器

     end: sideBarMain
     end: sideBar 侧边栏容器

     end: main

     done
    Copyright © 2020 已经崩盘了
     Powered by .NET Core on Kubernetes
     end: footer
     end: home 自定义的最大容器
     ;

```python
import requests
from bs4 import BeautifulSoup
headers = {'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3970.5 Safari/537.36"}

url = 'https://blog.csdn.net/Betty_betty_betty/article/details/80898798'
res = requests.get(url)
html_page = res.content
soup = BeautifulSoup(html_page, 'html.parser')
text = soup.find_all(text=True)

output = ''
blacklist = [
    '[document]',
    'noscript',
    'header',
    'html',
    'meta',
    'head',
    'input',
    'script',
    # there may be more elements you don't want, such as "style", etc.
]

for t in text:
    if t.parent.name not in blacklist:
        output += '{} '.format(t)

print(output)
```

     位运算符中的  (左移)    (右移)   (无符号右移)2_大数据_Dimples.-CSDN博客

         自定义皮肤样式

     js引用

            .MathJax, .MathJax_Message, .MathJax_Preview{
                display: none
            }

     位运算符中的  (左移)    (右移)   (无符号右移)2

     文章类型
     原创   DimplesDimples.
     最后发布于2018-07-03 15:05:49
     阅读数 573

                            收藏

     发布于2018-07-03 15:05:49

     分类专栏：

                                           java

                                    版权声明：本文为博主原创文章，遵循  CC 4.0 BY-SA  版权协议，转载请附上原文出处链接和本声明。

                                    本文链接： https://blog.csdn.net/Betty_betty_betty/article/details/80898798

     展开

     python安装手册开始
     python安装手册结束
     ####专栏广告位图文切换开始
     ####专栏广告位图文切换结束

     <<:某数据左移n位是该数据乘以2的n次幂，可以完成2的次幂运算
     >>:某数据右移n位是该数据除以2的n次幂，对于高位出现的空位，原来是什么就用什么来补全。
     >>>:无符号右移是数据进行右移时，高位出现的空位，无论原高位是什么，空位都用0补。

     点赞
     2

     收藏

     分享
     打赏开始
     打赏结束

     文章举报

     DimplesDimples.

     发布了127 篇原创文章  ·  获赞 18  ·  访问量 4万+

     私信

     关注

                        展开阅读全文

      多条广告如下脚本只需引入一次

        d-flex

     发表评论

     添加代码片

     HTML/XML
     objective-c
     Ruby
     PHP
     C
     C++
     JavaScript
     Python
     Java
     CSS
     SQL
     其它

     还能输入 1000 个字符

    				java 无符号右移>>>  有符号右移>>

     10-13

    					阅读数
    					2585

     有符号右移&amp;gt;&amp;gt;有符号右移就是右移之后，左边的补上符号位，正数补0，负数补1无符号右移&amp;gt;&amp...

     博文
     来自：	  sunshine

    				位操作（左移和右移）

     08-10

    					阅读数
    					9910

     位操作提高程序运行效率 减少除法和取模的运算。在计算机程序中数据的位是可以操作的最小数据单位，理论上可以用”位运算”来完成所有的运算和操作。左移，后空缺自动补0；右移，分为逻辑右移和算数右移1）逻辑右...

     博文
     来自：	  博客

    				关于（二进制）位移运算：带符号右移位；带符号左移位；无符号右移位

     06-04

    					阅读数
    					3682

     >> 带符号右移位分析：num>> n（1）相当于num（num的二进制）向右移动n位。（2）正数移位：右边（低位）移出部分，直接舍弃，左边（高...

     博文
     来自：	  weixin_42315600的博客

    				在java中无符号数-2，进行向右移动3位，结果为什么是8？(也就是a=-2，a>>>=8)

     03-13

    					阅读数
    					405

     这里写自定义目录标题欢迎使用Markdown编辑器新的改变功能快捷键合理的创建标题，有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中...

     博文
     来自：	  L_world_的博客

    				Java_位运算符_左移右移

     05-22

    					阅读数
    					193

     左移和右移都是对整数的补码进行运算的左移就是补码向左移两位，每左移一位就相当于补码所对应的十进制的整数 *2右移就是补码向右移两位，每右移一位就相当于补码所对应的十进制的整数 \261补码：00..0...

     博文
     来自：	  Song_MJ的博客

    				关于负数的右移>>与无符号右移>>>运算小结

     03-10

    					阅读数
    					1474

                                       对于带符号右移,若为负数,则在存储时首位表示符号位,其值为1...

     博文
     来自：	  王昌时的博客

    				python 没有无符号右移，左移

     02-27

    					阅读数
    					721

     python没有>>>无附后右移

     博文
     来自：	  weixin_44088837的博客

    				无符号右移问题

     07-21

     >>>作为无符号右移，可以使符号右移，但是我运算时却发现一个怪异的问题 byte n = (byte)((byte)0x80>>>4); 结果是-8 如果改成byte n = (byte)(0x80>
     论坛

    				python 怎样实现无符号右移？

     03-05

     java 里的无符号右移是 >>> python的无符号右移怎样实现？？ 求解！
     论坛

      多条广告如下脚本只需引入一次

    				移位（左移，右移和无符号右移）

     04-04

    					阅读数
    					1948

     public class Shift { public static void main(String[] args) {  int x = -50;  int a = 50;  int b = 5 ...

     博文
     来自：	  yshunb的博客

    				C++中实现无符号右移

     09-06

    					阅读数
    					1373

     无符号右移的意思是右移时不考虑符号问题，即无论右移正数还是负数，其最高位都是补0。不同于普通的“>>”移位操作，使用“>>”右移时，是以符号扩展原则进行右移，即在右移过程中它将保持原有数据的正负号不变...

     博文
     来自：	  冰殇的博客

    				Java 位运算符：左移、右移、无符号右移

     09-17

    					阅读数
    					702

     概述上一篇文章我们说到了Java运算符的优先级的问题，也给大家提供了一个简单易记的口诀，那么这一篇博文，我们就来看一看Java运算符中的位运算符：左移，右移，无符号右移。程序中的所有数在计算机内存中都...

     博文
     来自：	  枣面包的博客

    				位运算符之---左移右移运算符(简单易懂)

     08-07

    					阅读数
    					3218

     前言:位运算符是用来对二进制位进行操作的c语言中有6种位运算符:&按位与|按位或^按位异或~取反<<左移>>右移本篇文章我们只讲左移和右移运算符,其他的会陆续在其他篇讲...

     博文
     来自：	  沈明一的博客

    				按位与运算符&与右移运算符>>

     04-25

    					阅读数
    					341

     来自：https://zhidao.baidu.com/question/146401227.html&表示两种运算符，其中一种表示取值运算符，一种是按位与取值运算符int a=1;int *...

     博文
     来自：	  luo_yu_1106的博客

    				Java学习手册：无符号左移&无符号右移&有符号右移

     04-12

    					阅读数
    					683

     一、无符号右移“>>”与有符号右移“>>>”Java提供了两种右移运算符：“>>”和">>>"。其中，“>>”被称为有符号右移运...

     博文
     来自：	  浩比的专栏

    				javaSE (二）逻辑/位运算符、左移右移运算符、switch语句

     11-25

    					阅读数
    					360

     逻辑运算符 &amp;amp;amp;amp;amp; | ^ !&amp;amp;amp;amp;amp;：  与   有false则false| ：     或  ...

     博文
     来自：	  PizAn的博客

    				位运算以及位的左移和右移

     03-29

    					阅读数
    					442

     1、左移：m<<n。左移n位的时候，最左边的n位将被丢弃，最右边补上n个0。00001010<<2=0010100。10001010<<3=01010000  2、...

     博文
     来自：	  麋鹿麋鹿迷了路

    				关于C/C++左移右移运算符的总结

     09-02

    					阅读数
    					1万+

     （1）结合图示篇，更加简单明了。移位运算包含“逻辑移位”（logicalshift）和“算术移位”（arithmeticshift）。逻辑移位：移出去的位丢弃，空缺位（vacantbit）用0填充。算...

     博文
     来自：	  qq_39790992的博客

    				求解移位运算 无符号右移

     03-12

    -2的二进制应该是11111110
    向右无符号移位3位应该是00011111
    答案不应该是31吗，为啥选8啊
     问答

    				java中右移运算符>>和无符号右移运算符>>>的区别

     02-07

    					阅读数
    					1万+

     在做一个pcm音频时遇到了这个符，但是我看有些百度的地方的解释都不能令我很懂，所以就整理下。-----------------------------------------------------更...

     博文
     来自：	  cobbwho的博客

    				算法（一）：如何高效的算出2*8的值，位移算法原理解释，为什么8左移1位，4左移2位，2左移3位，1左移4位的结果为16

     03-31

    					阅读数
    					2万+

     位移算法，如何高效的算出2*8的值，为什么8&amp;amp;lt;&amp;amp;lt;1，4&amp;amp;lt;&amp;am...

     博文
     来自：	  seesun2012的专栏

    				无符号右移运算符 (>>>)

     08-07

    					阅读数
    					958

     转载自：http://hi.baidu.com/wlred/item/68abdeebf0910d2c5a2d64cc无符号右移运算符 (>>>)是右移表达式的位，不保留符号。使用示例result =...

     博文
     来自：	  hugoshine的专栏

    				1.双与(或)和单与(或)的区别2.左移右移无符号右移3.字符串的应用4.类型强制转换

     09-28

    					阅读数
    					197

     1.类型强制转换   byte y=2;  int x=3;   y=(byte)(x+y);  byte a=2;   a+=3; 对(做了强制转换动作)  a=a+3; 错(精度丢失 byte不可...

     博文
     来自：	  insiston0635的博客

    				C语言中的左移与右移

     12-20

    					阅读数
    					26

     C语言中的左移与右移先说左移,左移就是把一个数的所有位都向左移动若干位,在C中用<<运算符.例如:int i = 1;i = i << 2; //把i里的值左移2位也就是说,1...

     博文
     来自：	  weixin_30414245的博客

    				C/C++中的有符号和无符号的位运算问题

     08-11

    					阅读数
    					413

     是对C/C++下面的结果感到困惑？printf("%d\n", ((unsigned char)~0 >> 1)); //结果为127printf("%d\n", -((unsigned char)~...

     博文
     来自：	  百亿云

    				2018-1-20：左移<<和右移>>运算以及和>>>（无符号右移）的区别以及位运算的小题目...

     01-20

    					阅读数
    					8

     首先：左移和右移以及无符号右移都是应用于2的次幂运算左移几位就相当于该数据乘以2的几次方：即完成2的次幂运算右移几位就相当于该数据除以2的几次方：即完成2的次幂运算，右移有个小特点：右移之后空出的最高...

     博文
     来自：	  weixin_33766805的博客

    				无符号右移运算

     07-30

    					阅读数
    					27

     1.非数值转换成02.所以大于等于0的数取整数部分"a" >>> 0012.34 >>> 012转载于:https://www.cnblogs.com/bibiaf...

     博文
     来自：	  diancui3160的博客

    				位运算3

     03-26

    					阅读数
    					160

     /* 左边最高位丢弃，右边补齐0>>:右移 最高位是0，左边补齐0；最高为是1，左边补齐1>>>:无符号右移 无论最高位是0还是1，左边补齐0面试题：请用最有效率的方式写出计算2乘以8的结果?2 * ...

     博文
     来自：	  午夜的行人

    				左移右移小总结

     12-11

    					阅读数
    					1万+

     左移右移小总结@(组成原理)关于数的移位，特别需要注意正数，三码相同，所以无论左移还是右移都是补0.而负数的补码就需要注意，左移在右边补0，右移需要在左边补1，有一个很有趣的误区是，认为符号位保持不变...

     博文
     来自：	  Bing's Blog

    				C/C++中的逻辑右移、算数右移、循环左移、循环右移

     10-08

    					阅读数
    					1万+

     C/C++语言中逻辑右移和算数右移共享同一个运算符>>，编译器决定使用逻辑右移还是算数右移，根据的是运算数的类型。如果是unsigned则采用逻辑右移，如果是signed则采用算数右移。对于signe...

     博文
     来自：	  huizhang0110

    				C语言的逻辑右移和算术右移

     03-11

    					阅读数
    					5501

     首先说明一下这两个概念：逻辑右移：右移后左边添加0算术右移：右移后添加的位与原数的符号位相同在C语言中，对于移位操作执行的是逻辑左移和算术右移，不过对于无符号类型，所有的移位操作都是逻辑的。所以要相对...

     博文
     来自：	  萧十一的技术小站

    				关于java中位运算的左移、右移、无符号右移

     12-23

    					阅读数
    					7934

     今天学到了java中的位运算，和C语言还是有所不同的：>>:右移运算符，num>>1，相当于num*2；>>>:无符号右移，忽略符号位，空位以0补齐。位运算的一些规则：1.byte、short、cha...

     博文
     来自：	  光耀天下

    				有符号右移>>，无符号右移>>>

     02-27

    					阅读数
    					9025

     计算机表示数字正负不是用+-加减号来表示，而是用最高位数字来表示，0表示正，1表示负1.有符号右移>>（若正数,高位补0,负数,高位补1）正数:例如4>&am...

     博文
     来自：	  BushRo

    				分析轮子（二）- << ，>>，>> （左移、右移、无符号右移）

     09-06

    					阅读数
    					79

     前言：写 分析轮子（一）-ArrayList.java 的时候看到源码中有 int newCapacity = oldCapacity + (oldCapacity >> ...

     博文
     来自：	  weixin_33805992的博客

    				为什么要右移8位 >>8

     04-12

     byte b2_groupno = new byte; int groupno = ((int)b2_groupno & 0xFF)|(((int)b2_groupno & 0xFF)<<8); b2
     论坛

    				按位左右移位运算符

     05-11

    					阅读数
    					568

     按位左右移位运算符>> 今天在群里总算长见识了。。虽然不常用记下来...>> 1 = / 2>> 2 = / 4>> 3 = / 8>> 4 = / 16...失忆的猪猪(3224897) 17:04...

     博文
     来自：	  xiaoj13的专栏

    				位运算符左移右移的特点

     10-16

    					阅读数
    					468

     /* * 位运算符: *  *  * >>:右移,最高符号位如果是1,左边补齐1,最高符号位如果是0,左边补齐0 * //>>右移动特点:该符号左边的数据除以2的移动次幂:24/2^2 = 6 * >...

     博文
     来自：	  qq_39345059的博客

    				java 位运算符（左移与右移）

     01-19

    					阅读数
    					1608

     左移代表乘，左移一位代表乘2,左移两位代表乘4，依次递增           12<<1=24    12<<2=48 右移代表除,  右移一位...

     博文
     来自：	  shuoxi666的博客

    				SecureCRT的下载、安装（ 过程非常详细！！值得查看）

     03-03

    					阅读数
    					1万+

     SecureCRT的下载、安装和破解（ 过程非常详细！！值得查看）简单介绍下SecureCRT一、SecureCRT的下载二、SecureCRT的安装简单介绍下SecureCRTSecureCRT是一...

     博文
     来自：	  超Ren专属

    				Java学习的正确打开方式

     01-08

    					阅读数
    					28万+

     在博主认为，对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结，前三者博主将淋漓尽致地挥毫于这篇博客文章中，至于总结在于个人，实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次...

     博文
     来自：	  程序员宜春的博客

                                    python

                                    json

                                    java

                                    mysql

                                    pycharm

                                    android

                                    linux

                                    json格式

                                    c# temp 目录

                                    bytes初始化 c#

                                    c#显示无焦点窗口

                                    c# 类是否继承指定接口

                                    c# 检查数据更新

                                    c#连接扫描枪

                                    c# 跟c++ 进程同步

                                    c#中的arrylist

                                    c#子窗体重复打开

                                    c# 源码 网站监控

     没有更多推荐了， 返回首页

     ©2019 CSDN
     皮肤主题: 书香水墨
      设计师:
                                                CSDN官方博客

     主页引入

      <h3 class="aside-title">个人资料</h3>

                        DimplesDimples.

     TA的个人主页 >

     原创
     127

     粉丝
     19

     获赞
     18

     评论
     1

     访问
     4万+

     等级:

     周排名:

                        2万+

     积分:

                    1744

     总排名:

                        4万+

     勋章:

     持之以恒

                                                    授予每个自然月内发布4篇或4篇以上原创或翻译IT博文的用户。不积跬步无以至千里，不积小流无以成江海，程序人生的精彩需要坚持不懈地积累！

     1024勋章

                                                    #1024程序员节#活动勋章，当日发布原创博客即可获得

     关注

     私信

      博客内页左上视窗-20181120

     最新文章

                                            Hadoop怎样避免文件被切分？

                                            Flume是什么，有什么作用，flume的三个组件。

                                            HA架构中的脑裂，什么是脑裂，怎样预防脑裂？

                                            数据库事务的四个特性及含义

                                            MapReduce中排序发生在哪几个阶段？这些排序是否可以避免？为什么？

     分类专栏

     ####是否付费
     Flume

     ####是否付费
     1篇

     ####是否付费
     java

     ####是否付费
     71篇

     ####是否付费
     数据库

     ####是否付费
     18篇

     ####是否付费
     Linux

     ####是否付费
     14篇

     ####是否付费
     vim

     ####是否付费
     1篇

     ####是否付费
     Hadoop

     ####是否付费
     21篇

     ####是否付费
     计算机基础

     ####是否付费
     1篇

     ####是否付费
     JSP

     ####是否付费
     1篇

     ####是否付费
     Zookeeper

     ####是否付费
     1篇

     ####是否付费
     HBase

     ####是否付费
     3篇

     ####是否付费
     python

     ####是否付费
     1篇

     ####是否付费
     hive

     ####是否付费
     1篇

     ####是否付费
     Spring

     ####是否付费
     1篇

     展开

     归档

     归档统计

                        2020年1月                     2篇

     归档统计

                        2019年12月                     5篇

     归档统计

                        2019年3月                     1篇

     归档统计

                        2018年12月                     6篇

     归档统计

                        2018年11月                     23篇

     归档统计

                        2018年10月                     15篇

     归档统计

                        2018年9月                     18篇

     归档统计

                        2018年8月                     40篇

     归档统计

                        2018年7月                     20篇

     归档统计

                        2018年6月                     5篇

     展开

     热门文章

                                                    Hadoop完全分布式搭建步骤
     阅读数  4651

                                                    录入10个学生的数学语文英语的三科成绩 计算每科的平均成绩计算出每个人的总成绩 并找出每科成绩的最高分与最低分
     阅读数  2963

                                                    MySQL语言之约束(constraint)
     阅读数  2563

                                                    HBase有什么优点和缺点
     阅读数  2429

                                                    在window下设置hosts配置主机名和ip的映射
     阅读数  2261

     最新评论

     成员变量与局部变量的区别     ...

     qq_29951485： 作者你好，一个问题，GCROOT包含局部变量表里的引用的对象，那么等到局部变量表中的值置为null时，对象被回收，可以理解。但是成员变量随着对象一起再堆中，那么被回收的时机就和对象一致，不能单独被回收，是这样吗？

      博客内页左下视窗-20181130

     目录

      多条广告如下脚本只需引入一次

     分类专栏

     ####是否付费
     Flume

     ####是否付费
     1篇

     ####是否付费
     java

     ####是否付费
     71篇

     ####是否付费
     数据库

     ####是否付费
     18篇

     ####是否付费
     Linux

     ####是否付费
     14篇

     ####是否付费
     vim

     ####是否付费
     1篇

     ####是否付费
     Hadoop

     ####是否付费
     21篇

     ####是否付费
     计算机基础

     ####是否付费
     1篇

     ####是否付费
     JSP

     ####是否付费
     1篇

     ####是否付费
     Zookeeper

     ####是否付费
     1篇

     ####是否付费
     HBase

     ####是否付费
     3篇

     ####是否付费
     python

     ####是否付费
     1篇

     ####是否付费
     hive

     ####是否付费
     1篇

     ####是否付费
     Spring

     ####是否付费
     1篇

     点赞
     取消点赞

     2

     海报

     评论

     目录

     收藏
      <span class="hover-show text-box text">
    					<span class="no-active">收藏</span>
    					<span class="active">取消收藏</span>
    				</span>

    					手机看

     上一篇

     下一篇

      宽屏更多按钮

     更多

     上一篇

     下一篇

     打赏

     打赏

     DimplesDimples.
     “你的鼓励将是我创作的最大动力”

     5C币
     10C币
     20C币
     50C币
     100C币
     200C币

     确定

     分享到微信朋友圈

     ×

     扫一扫，手机浏览

```python
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 12*np.pi, 0.01)
x = np.sin(t)*(np.e**np.cos(t) - 2*np.cos(4*t)-np.sin(t/12)**5)
y = np.cos(t)*(np.e**np.cos(t) - 2*np.cos(4*t)-np.sin(t/12)**5)
plt.figure(figsize=(8,6))
plt.axis('off')
plt.plot(x,y,color='blue',linewidth = '2')
plt.show()
# plt.savefig("butter.jpg",dpi=400)
```

```python
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
[x, t] = np.meshgrid(np.array(range(25)) / 24.0, np.arange(0, 575.5, 0.5) / 575 * 17 * np.pi - 2 * np.pi)
p = (np.pi / 2) * np.exp(-t / (8 * np.pi))
u = 1 - (1 - np.mod(3.6 * t, 2 * np.pi) / np.pi) ** 4 / 2
y = 2 * (x ** 2 - x) ** 2 * np.sin(p)
r = u * (x * np.sin(p) + y * np.cos(p))
h = u * (x * np.cos(p) - y * np.sin(p))
surf = ax.plot_surface(r * np.cos(t), r * np.sin(t), h, rstride=1, cstride=1,
                       cmap=cm.gist_rainbow_r, linewidth=0, antialiased=True)
plt.show()
```

```python
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator
import matplotlib.pyplot as plt
import numpy as np

# 省略了头文件，可以在之前的博客里看到
fig = plt.figure()
ax = fig.gca(projection='3d')
# 将相位向后移动了6*pi
[x, t] = np.meshgrid(np.array(range(25)) / 24.0, np.arange(0, 575.5, 0.5) / 575 * 20 * np.pi + 4*np.pi)
p = (np.pi / 2) * np.exp(-t / (8 * np.pi))
# 添加边缘扰动
change = np.sin(15*t)/150
# 将t的参数减少，使花瓣的角度变大
u = 1 - (1 - np.mod(3.3 * t, 2 * np.pi) / np.pi) ** 4 / 2 + change
y = 2 * (x ** 2 - x) ** 2 * np.sin(p)
r = u * (x * np.sin(p) + y * np.cos(p))
h = u * (x * np.cos(p) - y * np.sin(p))
c= cm.get_cmap('Reds')
surf = ax.plot_surface(r * np.cos(t), r * np.sin(t), h, rstride=1, cstride=1,
                       cmap= c, linewidth=0, antialiased=True)
plt.show()
```

```python
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
[x, t] = np.meshgrid(np.array(range(25)) / 24.0, np.arange(0, 575.5, 0.5) / 575 * 30 * np.pi - 4*np.pi)
p = (np.pi / 2) * np.exp(-t / (8 * np.pi))
change = np.sin(20*t)/50
u = 1 - (1 - np.mod(3.3 * t, 2 * np.pi) / np.pi) ** 4 / 2 + change
y = 2 * (x ** 2 - x) ** 2 * np.sin(p)
r = u * (x * np.sin(p) + y * np.cos(p)) * 1.5
h = u * (x * np.cos(p) - y * np.sin(p))
c= cm.get_cmap('magma')
surf = ax.plot_surface(r * np.cos(t), r * np.sin(t), h, rstride=1, cstride=1,
                       cmap= c, linewidth=0, antialiased=True)
plt.show()
```

```python
# 我采用requests库
import requests
import time

# 用来获取 时间戳
def gettime():
    return int(round(time.time() * 1000))

if __name__ == '__main__':
    # 用来自定义头部的
    headers = {}
    # 用来传递参数的
    keyvalue = {}
    # 目标网址(问号前面的东西)
    url = 'http://data.stats.gov.cn/easyquery.htm'

    # 头部的填充
    headers['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14) ' \
                            'AppleWebKit/605.1.15 (KHTML, like Gecko) ' \
                            'Version/12.0 Safari/605.1.15'

    # 下面是参数的填充，参考图10
    keyvalue['m'] = 'QueryData'
    keyvalue['dbcode'] = 'hgnd'
    keyvalue['rowcode'] = 'zb'
    keyvalue['colcode'] = 'sj'
    keyvalue['wds'] = '[]'
    keyvalue['dfwds'] = '[{"wdcode":"zb","valuecode":"A0301"}]'
    keyvalue['k1'] = str(gettime())

    # 发出请求，使用get方法，这里使用我们自定义的头部和参数
    # r = requests.get(url, headers=headers, params=keyvalue)
    # 建立一个Session
    s = requests.session()
    # 在Session基础上进行一次请求
    r = s.get(url, params=keyvalue, headers=headers)
    # 打印返回过来的状态码
    print(r.status_code)
    # 修改dfwds字段内容
    keyvalue['dfwds'] = '[{"wdcode":"sj","valuecode":"2000"}]'
    # 再次进行请求
    r = s.get(url, params=keyvalue, headers=headers)
    # 此时我们就能获取到我们搜索到的数据了
    print(r.text)
```

    200
    {"returncode":200,"returndata":{"datanodes":[{"code":"zb.A030101_sj.2000","data":{"data":126743,"dotcount":0,"hasdata":true,"strdata":"126743"},"wds":[{"valuecode":"A030101","wdcode":"zb"},{"valuecode":"2000","wdcode":"sj"}]},{"code":"zb.A030102_sj.2000","data":{"data":65437,"dotcount":0,"hasdata":true,"strdata":"65437"},"wds":[{"valuecode":"A030102","wdcode":"zb"},{"valuecode":"2000","wdcode":"sj"}]},{"code":"zb.A030103_sj.2000","data":{"data":61306,"dotcount":0,"hasdata":true,"strdata":"61306"},"wds":[{"valuecode":"A030103","wdcode":"zb"},{"valuecode":"2000","wdcode":"sj"}]},{"code":"zb.A030104_sj.2000","data":{"data":45906,"dotcount":0,"hasdata":true,"strdata":"45906"},"wds":[{"valuecode":"A030104","wdcode":"zb"},{"valuecode":"2000","wdcode":"sj"}]},{"code":"zb.A030105_sj.2000","data":{"data":80837,"dotcount":0,"hasdata":true,"strdata":"80837"},"wds":[{"valuecode":"A030105","wdcode":"zb"},{"valuecode":"2000","wdcode":"sj"}]}],"freshsort":0,"hasdatacount":5,"wdnodes":[{"nodes":[{"cname":"年末总人口","code":"A030101","dotcount":0,"exp":"年末人口数指每年12月31日24时的人口数。年度统计的全国人口总数内未包括香港、澳门特别行政区和台湾省以及海外华侨人数。","ifshowcode":false,"memo":"1981年及以前人口数据为户籍统计数；1982、1990、2000、2010年数据为当年人口普查数据推算数；其余年份数据为年度人口抽样调查推算数据。总人口和按性别分人口中包括现役军人，按城乡分人口中现役军人计入城镇人口。","name":"年末总人口","nodesort":"1","sortcode":2785,"tag":"","unit":"万人"},{"cname":"男性人口","code":"A030102","dotcount":0,"exp":"","ifshowcode":false,"memo":"","name":"男性人口","nodesort":"1","sortcode":2786,"tag":"","unit":"万人"},{"cname":"女性人口","code":"A030103","dotcount":0,"exp":"","ifshowcode":false,"memo":"","name":"女性人口","nodesort":"1","sortcode":2787,"tag":"","unit":"万人"},{"cname":"城镇人口","code":"A030104","dotcount":0,"exp":"城镇人口是指居住在城镇范围内的全部常住人口。","ifshowcode":false,"memo":"","name":"城镇人口","nodesort":"1","sortcode":2788,"tag":"","unit":"万人"},{"cname":"乡村人口","code":"A030105","dotcount":0,"exp":"乡村人口是除城镇人口以外的全部人口。","ifshowcode":false,"memo":"","name":"乡村人口","nodesort":"1","sortcode":2789,"tag":"","unit":"万人"}],"wdcode":"zb","wdname":"指标"},{"nodes":[{"cname":"2000年","code":"2000","dotcount":4,"exp":"","ifshowcode":false,"memo":"","name":"2000年","nodesort":"1","sortcode":21,"tag":"","unit":""}],"wdcode":"sj","wdname":"时间"}]}}

```python
import pandas as pd
data = pd.read_excel("F:\Course\Ad Design Project\Adanced design Project\Layout phase\VeryIMMaterials\Dist_between_2_ASVs_Reservior_No_shutdown\Dist_between_2_ASVs_2km_Reservior_No_Shutdown.xlsx",sheet_name='Rupture Data')
```

```python
data.head(554)
```

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Time (s)</th>
      <th>Discharge Rate (kg/s)</th>
      <th>Cumulative Mass (kg)</th>
      <th>Pexit 1 (Bara)</th>
      <th>Pexit 2 (Bara)</th>
      <th>Temp 1 (K)</th>
      <th>Temp 2 (K)</th>
      <th>Density 1 (kg/m3)</th>
      <th>Density 2 (kg/m3)</th>
      <th>Velocity 1 (m/s)</th>
      <th>Velocity 2 (m/s)</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>0.0</td>
      <td>0.0000</td>
      <td>0.0000</td>
      <td>39.9958</td>
      <td>39.9958</td>
      <td>293.1447</td>
      <td>293.1447</td>
      <td>67.8854</td>
      <td>67.8854</td>
      <td>0.2655</td>
      <td>0.2655</td>
    </tr>
    <tr>
      <td>1</td>
      <td>0.0</td>
      <td>1180.0537</td>
      <td>0.0000</td>
      <td>22.5923</td>
      <td>22.5923</td>
      <td>252.5346</td>
      <td>252.5346</td>
      <td>42.2521</td>
      <td>42.2521</td>
      <td>253.1873</td>
      <td>253.1873</td>
    </tr>
    <tr>
      <td>2</td>
      <td>0.1</td>
      <td>628.1808</td>
      <td>62.8181</td>
      <td>13.7986</td>
      <td>13.7726</td>
      <td>231.6360</td>
      <td>231.5740</td>
      <td>25.6056</td>
      <td>25.5871</td>
      <td>220.4379</td>
      <td>220.4254</td>
    </tr>
    <tr>
      <td>3</td>
      <td>0.2</td>
      <td>609.6585</td>
      <td>123.7839</td>
      <td>12.4013</td>
      <td>12.3740</td>
      <td>235.4435</td>
      <td>235.3571</td>
      <td>21.5346</td>
      <td>21.4889</td>
      <td>241.2826</td>
      <td>241.2221</td>
    </tr>
    <tr>
      <td>4</td>
      <td>0.2</td>
      <td>609.6585</td>
      <td>123.7839</td>
      <td>12.4013</td>
      <td>12.3740</td>
      <td>235.4435</td>
      <td>235.3571</td>
      <td>21.5346</td>
      <td>21.4889</td>
      <td>241.2826</td>
      <td>241.2221</td>
    </tr>
    <tr>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
      <td>...</td>
    </tr>
    <tr>
      <td>549</td>
      <td>92.0</td>
      <td>42.7426</td>
      <td>12303.5007</td>
      <td>1.1570</td>
      <td>2.0338</td>
      <td>293.0632</td>
      <td>272.2323</td>
      <td>1.3432</td>
      <td>2.5657</td>
      <td>1.0638</td>
      <td>294.4158</td>
    </tr>
    <tr>
      <td>550</td>
      <td>94.0</td>
      <td>41.7717</td>
      <td>12387.0441</td>
      <td>1.1570</td>
      <td>1.9950</td>
      <td>293.0677</td>
      <td>272.4625</td>
      <td>1.3431</td>
      <td>2.5137</td>
      <td>0.9680</td>
      <td>294.4916</td>
    </tr>
    <tr>
      <td>551</td>
      <td>96.0</td>
      <td>40.8211</td>
      <td>12468.6863</td>
      <td>1.1570</td>
      <td>1.9511</td>
      <td>293.0718</td>
      <td>272.5504</td>
      <td>1.3431</td>
      <td>2.4566</td>
      <td>0.8925</td>
      <td>294.5369</td>
    </tr>
    <tr>
      <td>552</td>
      <td>98.0</td>
      <td>39.8860</td>
      <td>12548.4583</td>
      <td>1.1570</td>
      <td>1.9128</td>
      <td>293.0756</td>
      <td>272.7616</td>
      <td>1.3431</td>
      <td>2.4057</td>
      <td>0.8300</td>
      <td>294.7477</td>
    </tr>
    <tr>
      <td>553</td>
      <td>100.0</td>
      <td>38.9705</td>
      <td>12626.3994</td>
      <td>1.1570</td>
      <td>1.8701</td>
      <td>293.0790</td>
      <td>272.8312</td>
      <td>1.3431</td>
      <td>2.3504</td>
      <td>0.7771</td>
      <td>294.6870</td>
    </tr>
  </tbody>
</table>
<p>554 rows × 11 columns</p>
</div>

```python
data.describe()
```

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Time (s)</th>
      <th>Discharge Rate (kg/s)</th>
      <th>Cumulative Mass (kg)</th>
      <th>Pexit 1 (Bara)</th>
      <th>Pexit 2 (Bara)</th>
      <th>Temp 1 (K)</th>
      <th>Temp 2 (K)</th>
      <th>Density 1 (kg/m3)</th>
      <th>Density 2 (kg/m3)</th>
      <th>Velocity 1 (m/s)</th>
      <th>Velocity 2 (m/s)</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>count</td>
      <td>554.000000</td>
      <td>554.000000</td>
      <td>554.000000</td>
      <td>554.000000</td>
      <td>554.000000</td>
      <td>554.000000</td>
      <td>554.000000</td>
      <td>554.000000</td>
      <td>554.000000</td>
      <td>554.000000</td>
      <td>554.000000</td>
    </tr>
    <tr>
      <td>mean</td>
      <td>23.610830</td>
      <td>220.254032</td>
      <td>5240.308144</td>
      <td>4.998674</td>
      <td>5.362190</td>
      <td>268.013234</td>
      <td>266.615016</td>
      <td>6.895543</td>
      <td>7.372436</td>
      <td>274.070756</td>
      <td>284.984168</td>
    </tr>
    <tr>
      <td>std</td>
      <td>20.498052</td>
      <td>120.333537</td>
      <td>3356.582133</td>
      <td>3.104750</td>
      <td>2.740964</td>
      <td>8.683361</td>
      <td>6.452936</td>
      <td>5.081280</td>
      <td>4.656870</td>
      <td>47.287798</td>
      <td>15.001453</td>
    </tr>
    <tr>
      <td>min</td>
      <td>0.000000</td>
      <td>0.000000</td>
      <td>0.000000</td>
      <td>1.157000</td>
      <td>1.870100</td>
      <td>231.636000</td>
      <td>231.574000</td>
      <td>1.343100</td>
      <td>2.350400</td>
      <td>0.265500</td>
      <td>0.265500</td>
    </tr>
    <tr>
      <td>25%</td>
      <td>5.525000</td>
      <td>142.713700</td>
      <td>2043.940425</td>
      <td>3.198225</td>
      <td>3.719800</td>
      <td>264.603300</td>
      <td>264.625450</td>
      <td>4.102175</td>
      <td>4.789725</td>
      <td>279.212600</td>
      <td>283.126175</td>
    </tr>
    <tr>
      <td>50%</td>
      <td>19.350000</td>
      <td>192.511650</td>
      <td>5168.679000</td>
      <td>4.559000</td>
      <td>4.553350</td>
      <td>268.843150</td>
      <td>268.830550</td>
      <td>5.964700</td>
      <td>5.956950</td>
      <td>287.629750</td>
      <td>288.838800</td>
    </tr>
    <tr>
      <td>75%</td>
      <td>36.350000</td>
      <td>281.250950</td>
      <td>8069.759725</td>
      <td>6.493600</td>
      <td>6.481800</td>
      <td>270.508525</td>
      <td>270.720825</td>
      <td>8.823425</td>
      <td>8.805525</td>
      <td>290.000425</td>
      <td>290.835725</td>
    </tr>
    <tr>
      <td>max</td>
      <td>100.000000</td>
      <td>1180.053700</td>
      <td>12626.399400</td>
      <td>39.995800</td>
      <td>39.995800</td>
      <td>293.144700</td>
      <td>293.144700</td>
      <td>67.885400</td>
      <td>67.885400</td>
      <td>296.231100</td>
      <td>294.747700</td>
    </tr>
  </tbody>
</table>
</div>

```python
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from mpl_toolkits.mplot3d import Axes3D
import seaborn as sns
color = sns.color_palette()
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor, export_graphviz
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import GridSearchCV, train_test_split, KFold
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble.partial_dependence import plot_partial_dependence
from sklearn.ensemble.partial_dependence import partial_dependence
from scipy.stats.stats import pearsonr
```

```python
from IPython.display import Image
import pydotplus
```

```python
sns.set_style("dark")
def plot_corr(predictors):
    predictors = predictors[:]
    mcorr = data[predictors].corr()
    mask = np.zeros_like(mcorr, dtype=np.bool)
    mask[np.triu_indices_from(mask)] = True
    cmap = sns.diverging_palette(220, 10, as_cmap=True)
    g = sns.heatmap(mcorr, mask=mask, cmap=cmap, square=True, annot=True, fmt='0.2f')
    g.set_xticklabels(predictors, rotation=90)
    g.set_yticklabels(reversed(predictors))
    plt.show()
plot_corr(["Discharge Rate (kg/s)","Cumulative Mass (kg)","Pexit 1 (Bara)","Pexit 2 (Bara)","Temp 1 (K)","Temp 2 (K)","Density 1 (kg/m3)","Velocity 1 (m/s)","Velocity 2 (m/s)"])
```

Augmented assignments have three advantages:*
• There’s less for you to type. Need I say more?
• The left side only has to be evaluated once. In X += Y, X may be a complicated object
expression. In the augmented form, it only has to be evaluated once. However, in
the long form, X = X + Y, X appears twice and must be run twice. Because of this,
augmented assignments usually run faster.
• The optimal technique is automatically chosen. That is, for objects that support
in-place changes, the augmented forms automatically perform in-place change operations instead of slower copies.

```python
import time
start =time.time()
#中间写上代码块
L = [1,2]
L = L + [3] # Concatenation
print(L)
end = time.time()
print('Running time: %s Seconds'%(end-start))
```

    [1, 2, 3]
    Running time: 0.0 Seconds

```python
import time
start =time.time()
#中间写上代码块
L = [1,2]
L = L.append(3) # Concatenation
print(L)
end = time.time()
print('Running time: %s Seconds'%(end-start))
```

    None
    Running time: 0.0 Seconds

C/C++ programmers take note: although Python now supports statements like X += Y, it still does not have
C’s auto-increment/decrement operators (e.g., X++, −−X). These don’t quite map to the Python object model
because Python has no notion of in-place changes to immutable objects like numbers.

```python
import timeit
start=timeit.default_timer()

#中间写代码块

L = [1,2]
L = L.append(3) # Concatenation

end=timeit.default_timer()
print('Running time: %s Seconds'%(end-start))
```

    Running time: 7.229999937408138e-05 Seconds

```python
import timeit
start=timeit.default_timer()

#中间写代码块

L = [1,2]
L = L + [3] # Concatenation

end=timeit.default_timer()
print('Running time: %s Seconds'%(end-start))
```

    Running time: 7.509999886678997e-05 Seconds

# And to add a set of items to the end, we can either concatenate again or call the list extend method:

```python
import timeit
start = timeit.default_timer()

L= [1,2,3,4]
L = L + [5,6]
print(L)

end = timeit.default_timer()
print("Running time: %s Seconds"%(end-start))
```

    [1, 2, 3, 4, 5, 6]
    Running time: 0.00024709999888727907 Seconds

```python
import timeit
start = timeit.default_timer()

L= [1,2,3,4]
L += [5,6]
print(L)

end = timeit.default_timer()
print("Running time: %s Seconds"%(end-start))
```

    [1, 2, 3, 4, 5, 6]
    Running time: 0.00022110000099928584 Seconds

```python
import timeit
start = timeit.default_timer()

L = [1,2,3,4]
L.extend([5,6])
print(L)

end = timeit.default_timer()
print("Running time: %s Seconds"%(end-start))
```

    [1, 2, 3, 4, 5, 6]
    Running time: 0.00042180000127700623 Seconds

# ？ When we use augmented assignment to extend a list, we can forget these details—forexample, Python automatically calls the quicker extend method instead of using the slower concatenation operation implied by

```python
import pandas as pd
df = pd.DataFrame([["""def all_unique(lst):
    return len(lst) == len(set(lst))

x = [1,1,2,2,3,2,3,4,5,6]
y = [1,2,3,4,5]
print(all_unique(x)) # False
print(all_unique(y)) # True
print(x,y)"""],["""from collections import Counter

def anagram(first, second):
    return Counter(first) == Counter(second)

print(anagram("abcd3", "3acdb")) # True"""],["""import sys

variable = 30
print(sys.getsizeof(variable)) # 24"""],["""def byte_size(string):
    return(len(string.encode( 'utf-8' )))

print(byte_size( 'KDA' )) # 4
print(byte_size( 'Hello World' )) # 11   """],["""n = 2;
s ="Programming";

print(s * n);
# ProgrammingProgramming """],["""s = "programming is awesome"

print(s.title())
# Programming Is Awesome"""],["""

from math import ceil

def chunk(lst, size):
    return list(
        map(lambda x: lst[x * size:x * size + size],
            list(range(0, ceil(len(lst) / size)))))

print(chunk([1,2,3,4,5],2))
# [[1,2],[3,4],5]"""],["""def compact(lst):
    return list(filter(bool, lst))

print(compact([0, 1, False, 2, 3,  5 ,  s , 34]))
# [ 1, 2, 3,  a ,  s , 34 ]"""],["""array = [[ 'a' ,  'b' ], [ 'c' ,  'd' ], [ 'e' ,  'f' ]]
transposed = zip(*array)
print(transposed)
# [( a ,  c ,  e ), ( b ,  d ,  f )]"""],["""a = 3
print( 2 < a < 8) # True
print(1 == a < 2) # False"""],["""hobbies = ["basketball", "football", "swimming"]

print("My hobbies are: " + ", ".join(hobbies))
# My hobbies are: basketball, football, swimming"""],["""import re

def count_vowels(str):
    return len(re.findall('[aeiou]', str, re.IGNORECASE))

print(count_vowels( 'foobar' )) # 3
print(count_vowels( 'gym' )) # 0"""],["""def decapitalize(string):
    return string[:1].lower() + string[1:]

print(decapitalize( 'FooBar' )) #  fooBar
print(decapitalize( 'FooBar' )) #  fooBar"""],["""def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
            ret.extend(i)
        else:
            ret.append(i)
    return ret

def deep_flatten(lst):
    result = []
    result.extend(
        spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
    return result

print(deep_flatten([1, [2], [[3], 4], 5])) # [1,2,3,4,5]"""],["""def difference(a, b):
    set_a = set(a)
    set_b = set(b)
    comparison = set_a.difference(set_b)
    return list(comparison)

print(difference([1,2,3], [1,2,4])) # [3]"""],["""def difference_by(a, b, fn):
    b = set(map(fn, b))
    return [item for item in a if fn(item) not in b]

from math import floor
print(difference_by([2.1, 1.2], [2.3, 3.4],floor)) # [1.2]
print(difference_by([{  'x' : 2 }, {  'x' : 1 }], [{  'x' : 1 }], lambda v : v[ 'x' ]))
# [ { x: 2 } ]
"""],["""def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

a, b = 4, 5
print((subtract if a > b else add)(a, b)) # 9 """],["""def has_duplicates(lst):
    return len(lst) != len(set(lst))

x = [1,2,3,4,5,5]
y = [1,2,3,4,5]
print(has_duplicates(x)) # True
print(has_duplicates(y)) # False"""],["""def merge_two_dicts(a, b):
    c = a.copy()   # make a copy of a
    c.update(b)    # modify keys and values of a with the ones from b
    return c

a = {  'x' : 1,  'y' : 2}
b = {  'y' : 3,  'z' : 4}
print(merge_two_dicts(a, b))
# { y : 3,  x : 1,  z : 4}
"""],["""def to_dictionary(keys, values):
    return dict(zip(keys, values))

keys = ["a", "b", "c"]
values = [2, 3, 4]
print(to_dictionary(keys, values))
# { a : 2,  c : 4,  b : 3}"""],["""lst = ["a", "b", "c", "d"]
for index, element in enumerate(lst):
    print("Value", element, "Index ", index, )

# ( Value ,  a ,  Index  , 0)
# ( Value ,  b ,  Index  , 1)
#( Value ,  c ,  Index  , 2)
# ( Value ,  d ,  Index  , 3)"""],["""import time

start_time = time.time()

a = 1
b = 2
c = a + b
print(c) #3

end_time = time.time()
total_time = end_time - start_time
print("Time: ", total_time)

# ( Time:  , 1.1205673217773438e-05)"""],["""try:
    2*3
except TypeError:
    print("An exception was raised")
else:
    print("Thank God, no exceptions were raised.")

#Thank God, no exceptions were raised."""],["""def most_frequent(list):
    return max(set(list), key = list.count)

list = [1,2,1,2,3,2,1,4,2]
print(most_frequent(list))
del list"""],["""# def palindrome(string):
  #  from re import sub
  #  s = sub('\w',[W_], string.lower())
   # return s == s[::-1]

#print(palindrome( 'taco cat' )) # True"""],["""import operator
action = {
    "+": operator.add,
    "-": operator.sub,
    "/": operator.truediv,
    "*": operator.mul,
    "**": pow
}
print(action["-"](50, 25)) # 25"""],["""from copy import deepcopy
from random import randint

def shuffle(lst):
    temp_lst = deepcopy(lst)
    m = len(temp_lst)
    while (m):
        m -= 1
        i = randint(0, m)
        temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
    return temp_lst

foo = [1,2,3]
print(shuffle(foo)) # [2,3,1] , foo = [1,2,3]"""],["""def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
            ret.extend(i)
        else:
            ret.append(i)
    return ret

print(spread([1,2,3,[4,5,6],[7],8,9])) # [1,2,3,4,5,6,7,8,9]"""],["""def swap(a, b):
  return b, a

a, b = -1, 14
print(swap(a, b)) # (14, -1)
print(spread([1,2,3,[4,5,6],[7],8,9])) # [1,2,3,4,5,6,7,8,9]"""],["""d = { a : 1,  b : 2}

print(d.get( c , 3)) # 3"""]],index=['重复元素判定','字符元素组成判定','内存占用','字节占用','打印 N 次字符串','大写第一个字母','分块','压缩','解包','链式对比','逗号连接','元音统计',
                         '首字母小写','展开列表', '列表的差','通过函数取差','链式函数调用','检查重复项','合并两个字典','将两个列表转化为字典','使用枚举','执行时间',
                         'Try else','元素频率','回文序列','不使用 if-else 的计算子','Shuffle','展开列表','交换值','字典默认值'],columns=['Python codes'])
```

```python
df.head(31)
```

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Python codes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>重复元素判定</td>
      <td>def all_unique(lst):\n    return len(lst) == l...</td>
    </tr>
    <tr>
      <td>字符元素组成判定</td>
      <td>from collections import Counter\n\ndef anagram...</td>
    </tr>
    <tr>
      <td>内存占用</td>
      <td>import sys \n\nvariable = 30 \nprint(sys.getsi...</td>
    </tr>
    <tr>
      <td>字节占用</td>
      <td>def byte_size(string):\n    return(len(string....</td>
    </tr>
    <tr>
      <td>打印 N 次字符串</td>
      <td>n = 2; \ns ="Programming"; \n\nprint(s * n);\n...</td>
    </tr>
    <tr>
      <td>大写第一个字母</td>
      <td>s = "programming is awesome"\n\nprint(s.title(...</td>
    </tr>
    <tr>
      <td>分块</td>
      <td>\n\nfrom math import ceil\n\ndef chunk(lst, si...</td>
    </tr>
    <tr>
      <td>压缩</td>
      <td>def compact(lst):\n    return list(filter(bool...</td>
    </tr>
    <tr>
      <td>解包</td>
      <td>array = [[ 'a' ,  'b' ], [ 'c' ,  'd' ], [ 'e'...</td>
    </tr>
    <tr>
      <td>链式对比</td>
      <td>a = 3\nprint( 2 < a < 8) # True\nprint(1 == a ...</td>
    </tr>
    <tr>
      <td>逗号连接</td>
      <td>hobbies = ["basketball", "football", "swimming...</td>
    </tr>
    <tr>
      <td>元音统计</td>
      <td>import re\n\ndef count_vowels(str):\n    retur...</td>
    </tr>
    <tr>
      <td>首字母小写</td>
      <td>def decapitalize(string):\n    return string[:...</td>
    </tr>
    <tr>
      <td>展开列表</td>
      <td>def spread(arg):\n    ret = []\n    for i in a...</td>
    </tr>
    <tr>
      <td>列表的差</td>
      <td>def difference(a, b):\n    set_a = set(a)\n   ...</td>
    </tr>
    <tr>
      <td>通过函数取差</td>
      <td>def difference_by(a, b, fn):\n    b = set(map(...</td>
    </tr>
    <tr>
      <td>链式函数调用</td>
      <td>def add(a, b):\n    return a + b\n\ndef subtra...</td>
    </tr>
    <tr>
      <td>检查重复项</td>
      <td>def has_duplicates(lst):\n    return len(lst) ...</td>
    </tr>
    <tr>
      <td>合并两个字典</td>
      <td>def merge_two_dicts(a, b):\n    c = a.copy()  ...</td>
    </tr>
    <tr>
      <td>将两个列表转化为字典</td>
      <td>def to_dictionary(keys, values):\n    return d...</td>
    </tr>
    <tr>
      <td>使用枚举</td>
      <td>lst = ["a", "b", "c", "d"]\nfor index, element...</td>
    </tr>
    <tr>
      <td>执行时间</td>
      <td>import time\n\nstart_time = time.time()\n\na =...</td>
    </tr>
    <tr>
      <td>Try else</td>
      <td>try:\n    2*3\nexcept TypeError:\n    print("A...</td>
    </tr>
    <tr>
      <td>元素频率</td>
      <td>def most_frequent(list):\n    return max(set(l...</td>
    </tr>
    <tr>
      <td>回文序列</td>
      <td># def palindrome(string):\n  #  from re import...</td>
    </tr>
    <tr>
      <td>不使用 if-else 的计算子</td>
      <td>import operator\naction = {\n    "+": operator...</td>
    </tr>
    <tr>
      <td>Shuffle</td>
      <td>from copy import deepcopy\nfrom random import ...</td>
    </tr>
    <tr>
      <td>展开列表</td>
      <td>def spread(arg):\n    ret = []\n    for i in a...</td>
    </tr>
    <tr>
      <td>交换值</td>
      <td>def swap(a, b):\n  return b, a\n\na, b = -1, 1...</td>
    </tr>
    <tr>
      <td>字典默认值</td>
      <td>d = { a : 1,  b : 2}\n\nprint(d.get( c , 3)) # 3</td>
    </tr>
  </tbody>
</table>
</div>

```python
for i in range(30):
    exec(str((df.iloc[i].values)[0]))
```

    False
    True
    [1, 1, 2, 2, 3, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5]
    True
    28
    3
    11
    ProgrammingProgramming
    Programming Is Awesome
    [[1, 2], [3, 4], [5]]
    [1, 2, 3, 5, 'programming is awesome', 34]
    <zip object at 0x000002A44DE71F88>
    True
    False
    My hobbies are: basketball, football, swimming
    3
    0
    fooBar
    fooBar
    [1, 2, 3, 4, 5]
    [3]
    [1.2]
    [{'x': 2}]
    9
    True
    False
    {'x': 1, 'y': 3, 'z': 4}
    {'a': 2, 'b': 3, 'c': 4}
    Value a Index  0
    Value b Index  1
    Value c Index  2
    Value d Index  3
    3
    Time:  0.0
    Thank God, no exceptions were raised.
    2
    25
    [1, 2, 3]
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    (14, -1)
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    3

```python
help(re.sub)
```

    Help on function sub in module re:

    sub(pattern, repl, string, count=0, flags=0)
        Return the string obtained by replacing the leftmost
        non-overlapping occurrences of the pattern in string by the
        replacement repl.  repl can be either a string or a callable;
        if a string, backslash escapes in it are processed.  If it is
        a callable, it's passed the Match object and must return
        a replacement string to be used.

```python
def difference_by(a, b, fn):
    b = set(map(fn, b))
    return [item for item in a if fn(item) not in b]

from math import floor
difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]
difference_by([{  'x' : 2 }, {  'x' : 1 }], [{  'x' : 1 }], lambda v : v[ 'x' ])
# [ { x: 2 } ]
```

    [{'x': 2}]

```python
lines = df.iloc[0].values
print(lines)
```

    ['def all_unique(lst):\n    return len(lst) == len(set(lst))\n\n\nx = [1,1,2,2,3,2,3,4,5,6]\ny = [1,2,3,4,5]\nprint(all_unique(x)) # False\nprint(all_unique(y)) # True\nprint(x,y)']

```python
print(str(lines[0]))
```

    def all_unique(lst):
        return len(lst) == len(set(lst))

    x = [1,1,2,2,3,2,3,4,5,6]
    y = [1,2,3,4,5]
    print(all_unique(x)) # False
    print(all_unique(y)) # True
    print(x,y)

```python
x,y
```

    ([1, 1, 2, 2, 3, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5])

```python
exec_code = compile(str(lines),'<string>', 'exec')
print(exec_code)
```

    <code object <module> at 0x000002E0B0EAF390, file "<string>", line 1>

```python
print(df.iloc[1].values)
```

    ['from collections import Counter\n\ndef anagram(first, second):\n    return Counter(first) == Counter(second)\n\n\nanagram("abcd3", "3acdb") # True']

```python
exec('from collections import Counter\n\ndef anagram(first, second):\n    return Counter(first) == Counter(second)\n\n\nanagram("abcd3", "3acdb") # True')
```

```python
anagram("abcd3","333333333333333333acdb")
```

    False

```python
exec(str(lines[0]))
```

    False
    True
    [1, 1, 2, 2, 3, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5]

```python
str((df.iloc[1].values)[0])
```

    'from collections import Counter\n\ndef anagram(first, second):\n    return Counter(first) == Counter(second)\n\n\nprint(anagram("abcd3", "3acdb")) # True'

```python
exec(str((df.iloc[1].values)[0]))
```

    True

```python
print(dir(str))
```

    ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

```python
print(dir(str.__str__))
```

    ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__name__', '__ne__', '__new__', '__objclass__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']

```python
print(dir((str.__class__).__call__))
```

    ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__name__', '__ne__', '__new__', '__objclass__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']

```python
import inspect
```

```python
help((str.__class__).__call__)
```

    Help on wrapper_descriptor:

    __call__(self, /, *args, **kwargs)
        Call self as a function.

# Naming conventions

Besides these rules, there is also a set of naming conventions—rules that are not required
but are followed in normal practice. For instance, because names with two leading and
trailing underscores (e.g., __name__) generally have special meaning to the Python interpreter, you should avoid this pattern for your own names. Here is a list of the conventions Python follows:

• Names that begin with a single underscore (_X) are not imported by a from module
import * statement (described in Chapter 22).

• Names that have two leading and trailing underscores (__X__) are system-defined
names that have special meaning to the interpreter.

• Names that begin with two underscores and do not end with two more (__X) are
localized (“mangled”) to enclosing classes (see the discussion of pseudoprivate
attributes in Chapter 30).

• The name that is just a single underscore (_) retains the result of the last expression
when working interactively.

# The Python 3.0 print Function

```python
x = 'spam'
y = 99
z = ['eggs']
print(x,y,z)
```

    spam 99 ['eggs']

```python
L = print(x,y,z,sep='',end='')
```

    spam99['eggs']

```python
print(L)
```

    None

```python
print(x,y,z,sep='')
```

    spam99['eggs']

```python
print(x,y,z,sep='');print(x,y,z) # Two prints, same output line
print(x,y,z,end='');print(x,y,z)
```

    spam99['eggs']
    spam 99 ['eggs']
    spam 99 ['eggs']spam 99 ['eggs']

```python
import pyprind
import time
import pandas as pd

bar = pyprind.ProgBar(10, monitor=True)
for i in range(10):
    time.sleep(0.01) # your computation here
    data = pd.read_excel("F:\Course\Ad Design Project\Adanced design Project\Layout phase\VeryIMMaterials\Dist_between_2_ASVs_Reservior_No_shutdown\Dist_between_2_ASVs_2km_Reservior_No_Shutdown.xlsx",
                         sheet_name='Rupture Data')
    bar.update()
print(bar)
```

    0% [##########] 100% | ETA: 00:00:00
    Total time elapsed: 00:06:46

    Title:
      Started: 03/08/2020 20:24:03
      Finished: 03/08/2020 20:30:50
      Total time elapsed: 00:06:46
      CPU %: 95.50
      Memory %: 3.60

```python
print('x','y','z',end='...\n')
```

    x y z...

```python
print('x','y','z',sep='...',end='!\n') # Multiple keywords
print('x','y','z',end='\n', sep='...')
```

    x...y...z!
    x...y...z

Here is how the file keyword argument is used—it directs the printed text to an open
output file or other compatible object for the duration of the single print (this is really
a form of stream redirection, a topic we will revisit later in this section):

```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.cnblogs.com/JYNNO1/p/10525649.html'
res = requests.get(url)
html_page = res.content
soup = BeautifulSoup(html_page, 'html.parser')
text = soup.find_all(text=True)

output = ''
blacklist = [
    '[document]',
    'noscript',
    'header',
    'html',
    'meta',
    'head',
    'input',
    'script',
    # there may be more elements you don't want, such as "style", etc.
]

for t in text:
    if t.parent.name not in blacklist:
        output += '{} '.format(t)

print(output, file=open('data.txt','w',encoding='utf-8'))
```

```python
print('x','y','z',sep='...',file=open('data1.txt','w'))
```

```python
print('x','y','z',sep='...'); print(open('data1.txt').read())
```

    x...y...z
    x...y...z

```python
text = '%s: %-.4f, %05d' % ('Result',3.14159,42)
print(text)
```

    Result: 3.1416, 00042

```python
print('%s: %-.4f,%05d' % ('Result',3.14159,42))
```

    Result: 3.1416,00042

```python
import sys
sys.stdout.write('hello world\n')
```

    hello world

This code explicitly calls the write method of sys.stdout—an attribute preset when
Python starts up to an open file object connected to the output stream. The print
operation hides most of those details, providing a simple tool for simple printing tasks.

```python
S = """Here, we reset sys.stdout to a manually opened file named log.txt, located in the script’s
working directory and opened in append mode (so we add to its current content). After
the reset, every print operation anywhere in the program will write its text to the end
of the file log.txt instead of to the original output stream. The print operations are
happy to keep calling sys.stdout’s write method, no matter what sys.stdout happens
to refer to. Because there is just one sys module in your process, assigning
sys.stdout this way will redirect every print anywhere in your program."""
```

```python
L = S.split()
```

```python
print(L, end = ' ')
```

    ['Here,', 'we', 'reset', 'sys.stdout', 'to', 'a', 'manually', 'opened', 'file', 'named', 'log.txt,', 'located', 'in', 'the', 'script’s', 'working', 'directory', 'and', 'opened', 'in', 'append', 'mode', '(so', 'we', 'add', 'to', 'its', 'current', 'content).', 'After', 'the', 'reset,', 'every', 'print', 'operation', 'anywhere', 'in', 'the', 'program', 'will', 'write', 'its', 'text', 'to', 'the', 'end', 'of', 'the', 'file', 'log.txt', 'instead', 'of', 'to', 'the', 'original', 'output', 'stream.', 'The', 'print', 'operations', 'are', 'happy', 'to', 'keep', 'calling', 'sys.stdout’s', 'write', 'method,', 'no', 'matter', 'what', 'sys.stdout', 'happens', 'to', 'refer', 'to.', 'Because', 'there', 'is', 'just', 'one', 'sys', 'module', 'in', 'your', 'process,', 'assigning', 'sys.stdout', 'this', 'way', 'will', 'redirect', 'every', 'print', 'anywhere', 'in', 'your', 'program.']

# Manual stream redirection

```python
print('x','y') # Or, in 2.6: print X, Y
import sys
sys.stdout.write(str('x')+' '+ str('y') + '\n')
```

    x y
    x y

```python
import sys
temp = sys.stdout
sys.stdout = open('log.txt','a')
```

```python
S1 = """In fact, as this chapter’s upcoming sidebar about print and stdout will explain, you
can even reset sys.stdout to an object that isn’t a file at all, as long as it has the expected
interface: a method named write to receive the printed text string argument. When that
object is a class, printed text can be routed and processed arbitrarily per a write method
you code yourself"""
```

```python
print(S1.split())
```

```python
print(open('log.txt').read())
```

    ['In', 'fact,', 'as', 'this', 'chapter’s', 'upcoming', 'sidebar', 'about', 'print', 'and', 'stdout', 'will', 'explain,', 'you', 'can', 'even', 'reset', 'sys.stdout', 'to', 'an', 'object', 'that', 'isn’t', 'a', 'file', 'at', 'all,', 'as', 'long', 'as', 'it', 'has', 'the', 'expected', 'interface:', 'a', 'method', 'named', 'write', 'to', 'receive', 'the', 'printed', 'text', 'string', 'argument.', 'When', 'that', 'object', 'is', 'a', 'class,', 'printed', 'text', 'can', 'be', 'routed', 'and', 'processed', 'arbitrarily', 'per', 'a', 'write', 'method', 'you', 'code', 'yourself']
    ['In', 'fact,', 'as', 'this', 'chapter’s', 'upcoming', 'sidebar', 'about', 'print', 'and', 'stdout', 'will', 'explain,', 'you', 'can', 'even', 'reset', 'sys.stdout', 'to', 'an', 'object', 'that', 'isn’t', 'a', 'file', 'at', 'all,', 'as', 'long', 'as', 'it', 'has', 'the', 'expected', 'interface:', 'a', 'method', 'named', 'write', 'to', 'receive', 'the', 'printed', 'text', 'string', 'argument.', 'When', 'that', 'object', 'is', 'a', 'class,', 'printed', 'text', 'can', 'be', 'routed', 'and', 'processed', 'arbitrarily', 'per', 'a', 'write', 'method', 'you', 'code', 'yourself']
    ['In', 'fact,', 'as', 'this', 'chapter’s', 'upcoming', 'sidebar', 'about', 'print', 'and', 'stdout', 'will', 'explain,', 'you', 'can', 'even', 'reset', 'sys.stdout', 'to', 'an', 'object', 'that', 'isn’t', 'a', 'file', 'at', 'all,', 'as', 'long', 'as', 'it', 'has', 'the', 'expected', 'interface:', 'a', 'method', 'named', 'write', 'to', 'receive', 'the', 'printed', 'text', 'string', 'argument.', 'When', 'that', 'object', 'is', 'a', 'class,', 'printed', 'text', 'can', 'be', 'routed', 'and', 'processed', 'arbitrarily', 'per', 'a', 'write', 'method', 'you', 'code', 'yourself']
    ['In', 'fact,', 'as', 'this', 'chapter’s', 'upcoming', 'sidebar', 'about', 'print', 'and', 'stdout', 'will', 'explain,', 'you', 'can', 'even', 'reset', 'sys.stdout', 'to', 'an', 'object', 'that', 'isn’t', 'a', 'file', 'at', 'all,', 'as', 'long', 'as', 'it', 'has', 'the', 'expected', 'interface:', 'a', 'method', 'named', 'write', 'to', 'receive', 'the', 'printed', 'text', 'string', 'argument.', 'When', 'that', 'object', 'is', 'a', 'class,', 'printed', 'text', 'can', 'be', 'routed', 'and', 'processed', 'arbitrarily', 'per', 'a', 'write', 'method', 'you', 'code', 'yourself']

```python
df.iloc[1].values
```

    array(['from collections import Counter\n\ndef anagram(first, second):\n    return Counter(first) == Counter(second)\n\n\nprint(anagram("abcd3", "3acdb")) # True'],
          dtype=object)

```python
import sys
temp = sys.stdin
sys.stdin = open('myfile.txt','a')
```

```python
print('hello world')
```

    hello world

```python
myfile = open('log.txt','w+')
```

```python
myfile.write("""Let’s work through a simple example that demonstrates file-processing basics. The
following code begins by opening a new text file for output, writing two lines (strings
terminated with a newline marker, \n), and closing the file. Later, the example opens
the same file again in input mode and reads the lines back one at a time with
readline. Notice that the third readline call returns an empty string; this is how Python
file methods tell you that you’ve reached the end of the file (empty lines in the file come
back as strings containing just a newline character, not as empty strings). """)
```

    591

```python
myfile.close()
```

```python
open('log.txt').read()
```

    'Let’s work through a simple example that demonstrates file-processing basics. The\nfollowing code begins by opening a new text file for output, writing two lines (strings\nterminated with a newline marker, \n), and closing the file. Later, the example opens\nthe same file again in input mode and reads the lines back one at a time with\nreadline. Notice that the third readline call returns an empty string; this is how Python\nfile methods tell you that you’ve reached the end of the file (empty lines in the file come\nback as strings containing just a newline character, not as empty strings). '

```python
myfile = open('log.txt','a+')
myfile.write("""When coded this way, the temporary file object created by open will automatically read
and return one line on each loop iteration. This form is usually easiest to code, good
on memory use, and may be faster than some other options (depending on many variables, of course). Since we haven’t reached statements or iterators yet, though, you’ll
have to wait until Chapter 14 for a more complete explanation of this code.""")
```

    417

```python
myfile.flush()
myfile.readlines()
```

    []

```python
open('log.txt').read()
```

    'Let’s work through a simple example that demonstrates file-processing basics. The\nfollowing code begins by opening a new text file for output, writing two lines (strings\nterminated with a newline marker, \n), and closing the file. Later, the example opens\nthe same file again in input mode and reads the lines back one at a time with\nreadline. Notice that the third readline call returns an empty string; this is how Python\nfile methods tell you that you’ve reached the end of the file (empty lines in the file come\nback as strings containing just a newline character, not as empty strings). When coded this way, the temporary file object created by open will automatically read\nand return one line on each loop iteration. This form is usually easiest to code, good\non memory use, and may be faster than some other options (depending on many variables, of course). Since we haven’t reached statements or iterators yet, though, you’ll\nhave to wait until Chapter 14 for a more complete explanation of this code.When coded this way, the temporary file object created by open will automatically read\nand return one line on each loop iteration. This form is usually easiest to code, good\non memory use, and may be faster than some other options (depending on many variables, of course). Since we haven’t reached statements or iterators yet, though, you’ll\nhave to wait until Chapter 14 for a more complete explanation of this code.'

```python
import pubchempy as pcp
c = pcp.Compound.from_cid(5090)
print(c.molecular_formula)
print(c.molecular_weight)
print(c.isomeric_smiles)
```

    C17H14O4S
    314.4
    CS(=O)(=O)C1=CC=C(C=C1)C2=C(C(=O)OC2)C3=CC=CC=C3

```python
import sys
def test(x):
    if x==0:
        print(r'Error--> x: can\'t be zero', file=sys.stderr)
    else:
        print(x)
```

```python
test(0), test(1)
```

    1

    Error--> x: can\'t be zero

    (None, None)

```python
test(0); test(1)
```

    1

    Error--> x: can\'t be zero

Now that you know all about print redirections, the equivalence between printing and
file write methods should be fairly obvious. The following interaction prints both ways
in 3.0, then redirects the output to an external file to verify that the same text is printed:

```python
X = 1; Y = 2
print(X, Y)
import sys
sys.stdout.write(str(X)+' ' + str(Y) + '\n')
print
```

    1 2
    1 2

```python
f = open('alice.txt', encoding = 'utf-8')
while f.readline()!='':
    print(f.readline())
```

    如果是我自己的，我就使劲打

    真打重了他会哭

    他又有点可爱

    喊我侄子回来做作业

    不是说过了

    我现在就是讲一件事的心情啊，没什么不开心的

    所以就不继续啦

    所以如果你想要未来的妻子也只照顾你的话，保姆就可以啦

    不想说

    就见一次面而已，我的脾性你都不清楚

    你很喜欢我？

    风格突变啊

    净净：还没过关呢

    有个大侄子就够啦

    看来跟我说话拉低你能力啊

    又让你大开眼界了

    你有过几次恋爱

    没联系了吧

    空气

    哪敢打你

    不然家庭地位不高

    我不会攒钱啊

    那怎么办

    你对自己以后有什么规划吗

    我也给不了什么好的建议啊

    海南的经济贸易港重心还没确定下来么

    你现在就是要在深圳工作，是吗

```python
import os
f.close()
os.remove('alice.txt')
```

# Version-Neutral Printing

Finally, if you cannot restrict your work to Python 3.0 but still want your prints to be
compatible with 3.0, you have some options. For one, you can code 2.6 print statements and let 3.0’s 2to3 conversion script translate them to 3.0 function calls automatically. See the Python 3.0 documentation for more details about this script; it
attempts to translate 2.X code to run under 3.0.

```python
from __future__ import print_function
```

C:\misc> c:\python30\python
< print('spam') # 3.0 print function call syntax
spam

< print('spam', 'ham', 'eggs') # These are mutiple argments
spam ham eggs

The first of these works the same in 2.6, but the second generates a tuple in the output:
C:\misc> c:\python26\python

< print('spam') # 2.6 print statement, enclosing parens
spam

< print('spam', 'ham', 'eggs') # This is really a tuple object!
('spam', 'ham', 'eggs')

```python
print('%s %s %s ' %('spam','ham','eggs'))
print('{0} {1} {2}'.format('spam','ham','eggs'))
```

    spam ham eggs
    spam ham eggs

```python
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 12*np.pi, 0.01)
x = np.sin(t)*(np.e**np.cos(t) - 2*np.cos(4*t)-np.sin(t/12)**5)
y = np.cos(t)*(np.e**np.cos(t) - 2*np.cos(4*t)-np.sin(t/12)**5)
plt.figure(figsize=(8,6))
plt.axis('off')
plt.plot(x,y,color='blue',linewidth = '2')
plt.show()
# plt.savefig("butter.jpg",dpi=400)
```

# Chapter Summary

In this chapter, we began our in-depth look at Python statements by exploring assignments, expressions, and print operations. Although these are generally simple to use,
they have some alternative forms that, while optional, are often convenient in practice:
augmented assignment statements and the redirection form of print operations, for
example, allow us to avoid some manual coding work. Along the way, we also studied
the syntax of variable names, stream redirection techniques, and a variety of common
mistakes to avoid, such as assigning the result of an append method call back to a
variable.
In the next chapter, we’ll continue our statement tour by filling in details about the
if statement, Python’s main selection tool; there, we’ll also revisit Python’s syntax
model in more depth and look at the behavior of Boolean expressions. Before we move
on, though, the end-of-chapter quiz will test your knowledge of what you’ve learned
here.

```python

```

Chapter 11 Introducing Python Statements.ipynb