Getting Started with Python Chapter II

Getting Started with Python Chapter II

2.1 Introduction

Python is the famous "turtle t" ( Guido Van Rossum ) during Christmas 1989, in order to fill the empty Christmas written in a programming language

   Python的哲学就是简单优雅,尽量写容易看明白的代码,尽量写少的代码。为我们提供了非常完善的基础代码库,覆盖了网络、文件、GUI、数据库、文本等大量内容,

2.1.1.Python what kinds of application development it?

  • cloud computing
  • Machine Learning
  • Scientific computing
  • Automated operation and maintenance
  • automated test
  • reptile
  • data analysis
  • GUI Graphical
  • Web development

2.1.2.Python What are the disadvantages?

  • Running slow, very slow compared to C programs and because Python is an interpreted language
  • Code can not be encrypted. If you want to publish your Python program, in fact, released the source code

2.1.3.python species

  • Cpython ( recommended )
    official version of Python, using the C language, the most widely used, CPython will realize the source file (py file) into byte code file (pyc files), then run on Python virtual machine.
  • Jyhton
    Python Java implementation, Jython Python code will be dynamically compiled into Java byte code, and then runs on the JVM.
  • IronPython
    Python C # implementation, the IronPython C # Python code into byte code, and then run on the CLR. (Jython and similar)
  • PyPy
    Python implemented Python, Python bytecode will compile the bytecode into machine code.
  • RubyPython, Britons 等.

2.1.4.Python version

Currently there are two main versions of Python Category:

  • 2.x, many companies are still using version 2.7, but in 2020 the official Python will stop support for Python 2's.
  • 3.x, more powerful and a lot of fixes improper release at 2 (recommended)

2.2 Environmental Installation

  • Interpreter: py2 / py3 (environment variables)
  • Development Tools: pycharm

2.3 encoding

2.2.1 code base

  • ascii, English, 8 represent a thing, 2 ** 8
  • unicode, unicode, 32 represent a thing, 2 ** 32
  • utf-8, to unicode compression, exhaustion represents a number of bits less things, to 8-bit units
  • gbk, GB, only the Chinese people themselves use, a Chinese with 16, two bytes.
  • gb2312

2.2.2 python coding-related

For the default Python interpreter code:

  • py2: ascii
  • py3: utf-8

If you want to modify the default encoding, you can use:

# -*- coding:utf-8 -*- 

Note: For operating files, in accordance with: to write what is written, it is necessary to open what encoding.

2.2.3 Unit conversion

8bit = 1byte
1024byte = 1KB
1024KB = 1MB
1024MB = 1GB
1024GB = 1TB
1024TB = 1PB
1024TB = 1EB
1024EB = 1ZB
1024ZB = 1YB
1024YB = 1NB
1024NB = 1DB
常⽤到TB就够了

O 2.4

2.4.1 Input

python2 and grammar are not the same input python3

  • python2
>>> my_input = raw_input('666')
666
  • python3
>>> my_input = input('666')
666

2.4.2 output

Python2 syntax and output is not the same python3

  • python2
>>> print "hello"
hello
  • python3
>>> print('hello')
hello

2.5 Variable

Q: Why have variable?

Create a "nickname" for a value addition after the adoption of resolution can be called directly using time.

Is a variable amount of change will be loaded into memory, easy call. Not only can be a number, it can also be any type of data

2.5.1 Specification

  1. Variable names can only contain: letter / number / underscore
  2. The numbers do not begin with
  3. 不能是python的关键字。 [‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘exec’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘not’, ‘or’, ‘pass’, ‘print’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]

2.5.2 recommendations

  1. See name EENOW
>>> name='zzy'
>>> print(name)
zzy
>>> age=24
>>> print(age)
24
  1. Connection with an underscore
>>> gao_qizhi='zzy'
>>> print(gao_qizhi)
zzy
  • Variable names recommended not to use Pinyin and Chinese
  • Variables to be meaningful
  • Not too long variable names
  • Variable names are case-sensitive

2.6 Constant

The so-called constant variables that can not be changed, such as the commonly used mathematical constant π is a constant. In Python, usually expressed with a constant variable name in ALL CAPS

2.7 Notes

  • Single-line comments, most begin with a "#" symbol in a row, the interpreter will ignore this line of code
# print(hello)
  • Multi-line comments, line in the code block, and the bottom row is added
'''
numb = 0
count = 1
while count < 100:
    if count % 2 == 1:
        numb -= count  # total -= count
    else:
        numb += count  # total += count
    count += 1
print(numb)

'''

2.8 If the conditional statement

  • The basic structure if conditional statement

if the full form of the statement is:

if <条件判断1>:
    <执行1>
elif <条件判断2>:
    <执行2>
elif <条件判断3>:
    <执行3>
·······
else:
    <执行4>

if there is a characteristic statement is executed, it is down from the judge, if the judge is on a True, the corresponding statement after the judgment executed, ignore the rest of the elif and else.

2.9 while loop

2.9.1 while loop format

while 条件:
    # 循环体
    # 如果条件为真,那么循环则执行
    # 如果条件为假,那么循环不执行
  • Examples

1. Output all numbers within 1-100.

count = 0
while count < 100:
    count = count + 1
    print(count)

2.9.2 break keyword

Role: end the current cycle of this while

  • Examples
##### 猜数字,设定一个理想数字比如:66,让用户输入数字,如果比66大,则显示猜测的结果大了;如果比66小,则显示猜测的结果小了;只有等于66,显示猜测结果正确,然后退出循环。


while True:
    number = input('请输入一个数字:')
    number = int(number)
    if number > 66:
        print('数字大了')
    elif number == 66:
        print('答对了')
        break
    else:
        print('小了')

2.9.3 continue keyword

Role: Exit the current cycle, the next cycle continues

  • Examples
#### 使用两种方法实现输出 1 2 3 4 5 6   8 9 10 。

count = 0
while count <= 9:
    count = count + 1
    if count == 7:
        continue
    print(count)

2.9.4 while else

Role: If the conditions are no longer satisfied after the initiation while loop and then continue, else the content is executed. If it is caused due to break the cycle is not executed, the contents else is not executed.

  • Examples
count = 0
while count <= 5:
    print(count)
    count += 1
else:
    print('窗前明月光,疑是地上霜')

2.10 for loop

2.11 formatted output

"%" Operator is used to format string. Within the string, the string is represented by S% Alternatively,% d represents an integer Alternatively, a few% placeholder, just behind several variables or a value, the order to the corresponding well.

Placeholder Replace content
%s String
%d Integer
%% A separate display%
  • Example 1
>>> 'Age: %s. Gender: %s' % (25, True)
'Age: 25. Gender: True'
>>>
  • Example 2
name = input('请输入姓名:')
age = input('请输入年龄:')
job = input('请输入职业:')
hobby = input('请输入爱好:')
msg = '''
------------ info of Alex Li ----------
Name  : %s
Age   : %s 
job   : %s 
Hobbie: %s 
------------- end ----------------'''
print(msg%(name,age,job,hobby))

### 运行后 ###
请输入姓名:高启芝
请输入年龄:18
请输入职业:开发
请输入爱好:你懂的

------------ info of Alex Li ----------
Name  : 高启芝
Age   : 18 
job   : 开发 
Hobbie: 你懂的 
------------- end ----------------
  • Example 3
num = input('>>>>')

s = '下载进度:%s%%'%(num)

print(s)

2.12. Operators

2.12.1 arithmetic operators

Operators description Examples
+ Plus - adding two objects a + b output 31
- Save - to give a number to another number or a negative number by subtracting a - b output -11
* By - multiplying two numbers or returns the string to be repeated several times a 210 outputs a * b
/ In addition - x divided by y b / a 2.1 output
% Modulo - returns the remainder of division b% a 1 output
** Power - Returns x to the power of y a ** b 10 to the power of 21
// Take divisible - close to the rounded down integer divisor 10 // 3 of 3 results

2.12.2 comparison operators

Operators description Examples
== Equal - compare objects for equality (A == b) returns False.
!= It is not equal to - compare whether two objects are not equal (A! = B) return True.
> Greater than - Returns whether x is greater than y (A> b) return False.
< Is smaller than the - Returns x is less than y. All comparison operators return 1 for true, 0 for false returns. True and False, respectively, which is equivalent to the special variables. Note the capitalization of these variable names. (A <b) return True.
>= Not less than - equal Returns whether x is greater than y. (A> = b) returns False.
<= Or less - Returns whether x is less than or equal y. (A <= b) return True.

2.12.3 Assignment Operators

Operators description Examples
= Simple assignment operator c = a + b a + b is the assignment of the operation result c
+= Addition assignment operator c + = a is equivalent to c = c + a
-= Subtraction assignment operator c - = a is equivalent to c = c - a
*= Multiplication assignment operator C = C = A is equivalent to C A
/= Division assignment operator c / = a is equivalent to c = c / a
%= Modulo assignment operator c% = a is equivalent to c = c% a
**= Power assignment operator C = C = A is equivalent to C A
//= Assignment operator take divisible c // = a is equivalent to c = c // a

2.12.4 Logical Operators

Operators Logical expression description Examples
and x and y Boolean "and" - if x is False, x and y returns the value of x, otherwise it returns evaluation of y. (A and b) returns 20.
or x or y Boolean "or" - If x is True, it returns the value of x, otherwise it returns evaluation of y. (A or b) to return 10.
not not x Boolean "NOT" - If x is True, it returns False. If x is False, it returns True. not (a and b) returns False
1/
value=0 and 9 
print(value) #0

value=1 and 9 
print(value) #9

对于and:
第一个值如果是转换成布尔值是假,则value=第一值,没有必要再往后计算了
第一个值如果是转换成布尔值是真,则value=第二值,在做后续计算

2/
value=1 or 9   数字遇到or都会转换为布尔
print(value) #1

value=0 or 9  
print(value) #9

对于or而言:
第一个值如果是转换成布尔值是真,则value=第一值,在做后续计算
第一个值如果是转换成布尔值是假,则value=第二值

2.12.5. Member operator

Determining whether the child element in the original string (dictionary, list, set) of

  • in (determining the presence of sub-elements)

Example 1

>>> value = "我是中国人"
>>> v1 = "中国" in value
>>> print(v1)
True

Example 2

while True:
    content = input('请输入内容:')
    if "退钱" in content:
        print('包含敏感字符')
    else:
        print(content)
        break
  • not in (determined child element is not present)

2.12.6 Priority

在没有()的情况下not 优先级高于 and,and优先级高于or,即优先级关系为( )>not>and>or,同一优先级从左往右计算。

Python运算符优先级

以下表格列出了从最高到最低优先级的所有运算符:

运算符 描述
** 指数 (最高优先级)
~ + - 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@)
* / % // 乘,除,取模和取整除
+ - 加法减法
>> << 右移,左移运算符
& 位 'AND'
^ | 位运算符
<= < > >= 比较运算符
<> == != 等于运算符
= %= /= //= -= += *= **= 赋值运算符
is is not 身份运算符
in not in 成员运算符
not and or 逻辑运算符

Guess you like

Origin www.cnblogs.com/hanfe1/p/11511102.html