Python3 Quick Start (two) - Python3 basis

Python3 Quick Start (two) - Python3 basis

A, Python3 basic grammar

1, Python3 coding

By default, Python source code file in UTF-8 encoding, all strings are unicode string can specify different encoding for Python source code file, as follows:
# -*- coding: utf-8 -*-

2, the identifier

Python language identifier rule is as follows:
A, the first character must be an alphabet letter or an underscore.
B, partial identifiers from the other letters, numbers and underscores.
C, identifier sensitive.
In Python 3, allowing non-ASCII identifier.

3, Python reserved word

That is a reserved word keyword, not as any identifier name. Python's standard library module provides a keyword, you can output the current version of all keywords:

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
>>> 

4, Print output

The default print output is the new line, if you want to achieve does not need to wrap at the end of variable plus end = "".

#!/usr/bin/python3

print("Hello Python3")
print("Hello ", end="")
print("Python", end="3\n")

5, Python comment

Python in single-line comments begin with #:

#! /usr/bin/python3
# 第一个注释
print("Hello Python3")  #第二个注释

Python3 multi-line comments with three single quotes' '' or three double quotation marks "". "

#!/usr/bin/python3 
'''
第三注释
第四注释
'''

"""
第五注释
第六注释
"""
print("Hello Python3")

6, indent

Python is most unique code block used to represent indentation, without using braces {}.
The number of spaces to indent is variable, but the same statement a block of code must contain the same number of spaces to indent, if not the same indentation causes a runtime error. Examples are as follows:

#!/usr/bin/python3
flag = True
if flag:
    print("True")
    print("true")
else:
    print("False")
    print("false")
print ("Hello Python3")

7, multi-line statement

Python is usually a one liner statement, but if the statement is very long, you can use the backslash () to achieve multi-line statement.

#!/usr/bin/python3
item_one = 1
item_two = 2
item_three = 3
total = item_one + \
        item_two + \
        item_three
print(total)

In [], {}, or () statement in a plurality of rows, without using a backslash (), e.g.

#!/usr/bin/python3
item_one = 1
item_two = 2
item_three = 3
total = item_one + \
        item_two + \
        item_three
print(total)
total = ['item_one', 'item_two', 'item_three',
       'item_four', 'item_five']
print(total)

8, variable

Python does not need to declare variables in each variable must be assigned before use, it will be created after the variable assignment.
In Python, no variable type, the object type is the type of memory within the meaning of the variables.
Python allows simultaneous assignment to multiple variables.

a = b = c = 1
a, b, c = 1, True, "hello"
x,y = 1,2
x,y = y,x
print(x,y)

Python variable names recommended Hungarian rule.

9, the user input

#!/usr/bin/python3

input("Please enter the name:\n")

Python code above will wait for user input, press the Enter key to exit.

10, digital type

Python digital There are four types: integer, boolean, floating point and complex.
int (integer), only one integer type, int, long integer expressed.
bool (Boolean), True, False.
float (floating-point), such as 2-1.23,3E
Complex (complex), such as 1 + 2j, 1.1 + 2.2j

11, string

Python is used to create single and double quotes string, tris quotation marks ( '' 'or' '') to create a multi-line string
escape '\'
backslash is used to escape, r may be used let backslash does not occur, such as r "this is a line with \ n" is \ n will be displayed, not wrap.
strings can be connected together in the + operator, with the operator * is repeated.
the Python in there are two ways string index, starting with 0 from left to right, right to left to begin -1.
the string can not be changed in Python.
Python no separate character type is a character string of length 1.

Two, Python3 operator

1, arithmetic operators

加(+):两对象相加
减(-):两对象相减
乘(*):两个数相乘或是返回一个被重复若干次的字符串
除(/):x除以y
取模(%):返回除法的余数
幂(**):返回x的y次幂
取整除(//):向下取接近除数的整数

Arithmetic operators Python3 sample code:

#!/usr/bin/python3
a = 10
b = 5
c = 0
# +
c = a + b
print("a + b = ", c)
# a + b =  15
a = "Hello"
b = "Python3"
c = a + b
print("a + b = ", c)
#a + b =  HelloPython3

# -
a = 10
b = 5
c = a -b
print("a - b = ", c)
# a - b =  5

# *
a = 10
b = 3
c = a * b
print("a * b = ", c)
#a * b =  30
a = "Hello"
b = 3
c = a * b 
print("a * b = ", c)
#a * b =  HelloHelloHello

# /
a = 10
b = 3
c = a / b
print("a / b = ", c)
#a / b =  3.3333333333333335

# %
a = 10
b = 3
c = a % b
print("a % b = ", c)
#a % b =  1

# **
a = 2
b = 10
c = a ** b
print("a ** b = ", c)
# a ** b =  1024

# //
a = 10
b = 3
c = a // b
print("a // b = ", c)
# a // b =  3

2, comparison operators

等于(==):比较对象是否相等
不等于(!=):比较对象是否不相等
大于(>):x是否大于y
小于(<):是否x小于y
大于等于(>=):x是否大于等于y
小于等于(<=):x是否小于等于y

Sample Code Python3 relational operators are as follows:

#!/usr/bin/python3
a = 21
b = 10
c = 0

if (a == b):
    print("a 等于 b")
else:
    print("a 不等于 b")

if (a != b):
    print("a 不等于 b")
else:
    print("a 等于 b")

if (a < b):
    print("a 小于 b")
else:
    print("a 大于等于 b")

if (a > b):
    print("a 大于 b")
else:
    print("a 小于等于 b")

if (a <= b):
    print("a 小于等于 b")
else:
    print("a 大于  b")

if (b >= a):
    print("b 大于等于 a")
else:
    print("b 小于 a")

For strings, lists, tuples comparison operation, according to the comparison performed by one element of the sequence.

a1 = "hello"
a2 = "hello"
print(a1 == a2)

b1 = [1,2,3]
b2 = [1,2,3]
print(b1 == b2)

c1 = (1,2,3)
c2 = (1,2,4)
print(c2 > c1)

3, the assignment operator

赋值(=):简单赋值运算
加法赋值(+=):c += a等效于c = c + a
减法赋值(-=):c -= a等效于c = c - a
乘法赋值(*=):c *= a等效于c = c * a
除法赋值(/=):c /= a等效于c = c / a
取模赋值(%=):c %= a等效于c = c % a
幂赋值(**=):c **= a等效于c = c ** a
取整除赋值(//=):c //= a 等效于c = c // a

Example Python3 assignment operator as follows:

#!/usr/bin/python3
a = 21
b = 10
c = 0

# =
c = a + b
print("c = ", c)
# c = 31

# +=
a = 10
c = 3
c += a
print("c = ", c)
# c = 13

a = 3
c = 10
# -=
c -= a
print("c = ", c)
# c = 1

# *=
a = 3
c = 5
c *= a
print("c = ", c)
# c = 15

# /=
a = 2
c = 10
c /= a
print("c = ", c)
# c = 5.0

# %=
a = 3
c = 10
c %= a
print("c = ", c)
# c = 1

# **=
a = 10
c = 2
c **= a
print("c = ", c)
# c = 1024

# //=
c = 10
a = 3
c //= a
print("c = ", c)
# c = 3

4, logical operators

Logic (and): x and y, if x is False, x and y returns x, otherwise the value of y.
Logical OR (or): x or y, if x is True, the return value of x, y values otherwise.
Logical NOT (not): not x, if x is True, it returns False. If x is False, returns True.
Example Python3 logical operators are as follows:

#!/usr/bin/python3
x = 10
y = 5

# x and y
print(x and y) #5
print(0 and y) #0

# x or y
print(x or y)  #10
print(0 or y)  #5

# not x
print(not x)
print(not False)

5, bitwise operator

Bitwise AND operator (&): involved in computing two values, if the corresponding two bits are 1, then the 1-bit result is 0 otherwise.
Bitwise OR operator (|): as long as the two corresponding binary bit is a 1, it is a result bit.
Bitwise exclusive OR operator (^): When two different corresponding binary, the result is 1.
Bitwise (~): for each binary data bit negated, i.e., the 1 to 0, the 0 to 1. equivalent to ~ x - (x + 1).
Left shift operator (<<): respective binary operand to the left a number of bits of all, the number of bits of a mobile "<<" specifies the right, discarding the upper, lower 0s.
Right shift operator (>>): The respective binary operand is ">>" All right a number of bits left, ">>" the number of bits specified right.
Example Python3 bitwise operators as follows:

#!/usr/bin/python3

a = 0b00111100
b = 0b00001101
c = 0

c = a & b;
print("c 的值为:", bin(c))  # 0b1100

c = a | b;
print("c 的值为:", bin(c))  # 0b111101

c = a ^ b;
print("c 的值为:", bin(c))  # 0b110001

c = ~a;
print("c 的值为:", bin(c))  # -0b111101

c = a << 2;
print("c 的值为:", bin(c))  # 0b11110000

c = a >> 2;
print("c 的值为:", bin(c))  # 0b1111

6, member operator

Python support member operator, test case contains a number of members, including strings, lists or tuples.
in: If you find the value in the specified sequence returns True, otherwise False.
not in: If you do not find value in the specified sequence returns True, otherwise False.
Example Python3 member operator as follows:

#!/usr/bin/python3

a = 1
b = 20
list = [1, 2, 3, 4, 5]

if (a in list):
    print("变量a在给定的列表list中")
else:
    print("变量a不在给定的列表list中")

if (b not in list):
    print("变量b不在给定的列表list中")
else:
    print("变量b在给定的列表list中")

7, the identity of the operator

Python3 operator for comparing the identity of two of the memory cells.
is: x is y, for determining whether the two identifiers are not referenced from an object, if references to the same object returns True, otherwise return False.
is not: x is not y, for determining whether the identifier is not referenced from two different objects, if the reference result is not the same object returns True, otherwise False.
Example Python3 identity operator as follows:

#!/usr/bin/python3

a = 20
b = 20

if (a is b):
    print("a和b有相同的标识")
else:
    print("a和b没有相同的标识")

if (a is not b):
    print("a和b没有相同的标识")
else:
    print("a和b有相同的标识")
Python中对象类型的判断使用is×××tance方法进行判断。
a = "hello"
print(is×××tance(a, str))

8, operator precedence

Python operator highest to lowest priority as follows:
Python3 Quick Start (two) - Python3 basis
the coding process for the recommendation priority using parentheses uncertain fuzzy display determination.

Three, Python3 process control

1, conditional control

Python by a conditional statement or statements of the execution result (True or False) to determine the execution code block.
The general form of Python if statement is as follows:

if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3

If "condition_1" to True will perform "statement_block_1" block statements.
If "condition_1" to False, the judge "condition_2".
If "condition_2" to True will perform "statement_block_2" block statements.
If "condition_2" to False, will perform "statement_block_3" block statements.
Each condition after a colon (:) represents a block of statements to be executed after the condition is satisfied.
Control of the conditions used to divide indentation statement blocks, the number of statements in the same indentation together to form a block.
No switch in Python - case statement.

#! /usr/bin/python3

score = int(input("Please enter the score: "))

if score < 60:
    print("D")
elif score < 80:
    print("C")
elif score < 90:
    print("B")
elif score <= 100:
    print("A")

In the nested if statements, can if ... elif ... else in another configuration if ... elif ... else structure.

2, the control loop

Python in the loop and there for while. Python while statement in general form as follows:

while 判断条件:
    语句

No do..while loop in Python.

#! /usr/bin/python3

N = 100
counter = 1
n = 0
while counter <= N:
    n += counter
    counter += 1

print("1 到 %d 之和为: %d" % (N, n))

In the execution else while ... else conditional statement is false in order to block.

#! /usr/bin/python3

count = 0
while count < 5:
    print("Hello Python3")
    count += 1
else:
    print("Hello Go")

If only one body of the while statement, the while statement can be written in the same row, as follows:

#! /usr/bin/python3

flag = 1

while flag: print('Hello Python3')

print("Good bye!")

Python for loop can iterate through the sequence of items, such as a list or a string.
The general format for the following cycle:

for <variable> in <sequence>:
    <statements>
else: 
    <statements>
#! /usr/bin/python3

languages = ["C", "C++", "Perl", "Python"]
for x in languages:
    print(x)

used for loop statement is used to break out of this loop, a for loop does not end normally, i.e. else branch is not performed.

#! /usr/bin/python3

languages = ["C", "C++", "Perl", "Python"]
for x in languages:
    if x == "Python":
        print(x)
        break
    print(x)
else:
    print("None")

range () built-in function may be used to generate a number of columns.

#! /usr/bin/python3

for x in range(5):
    print(x)
# 指定区间
for x in range(5,9):
    print(x)

# 指定区间和步长
for x in range(0,10,2):
    print(x)

for x in range(-10,-100,-10):
    print(x)

a = [1,2,3,4,5,6,7,8]
for i in range(0, len(a), 2):
    print(a[i])

b = a[0:len(a):2]
print(b) # [1, 3, 5, 7]

By seq [0: len (seq) : step] step can take a step to form a new sequence of every element from seq.
Python, pass an empty statement is used to maintain the integrity of the program structure, pass without doing anything, generally used as a placeholder statement.

#! /usr/bin/python3

for x in range(5):
    pass

3, switch to achieve

Python does not support the switch, can be achieved by using a dictionary switch, following implementation:
A, fault tolerance values using the dictionary get method, the process of the default case in the switch statement.
B, set at a dictionary vlaue corresponding method name, instead of the code block in the switch statement.
C, is set the same value in different key, the penetration of the analog switch.
Example dictionary switch implemented as follows:

#!/usr/bin/python3

def taskForRest():
    print("Today is easy!")
def taskForWork():
    print("Good job!")
def taskForDefault():
    print("Invalid input!")

switchDic = {"Sunday":taskForRest,
            "Monday":taskForWork,
            "Tuesday":taskForWork,
            "Wednesday":taskForWork,
            "Tursday":taskForWork,
            "Friday":taskForWork,
            "Saturday":taskForRest
}

monday = "Monday"
switchDic.get(monday,taskForWork())
tuesday = "Tuesday"
switchDic.get(tuesday, taskForWork)()
today = "Today"
switchDic.get(today,taskForDefault())

Reproduced in: https: //blog.51cto.com/9291927/2409575

Guess you like

Origin blog.csdn.net/weixin_34409357/article/details/92651099