Python_ basis _1

Python

1 Comment

1.1 Single-line comments

#我注释了一行

More than 1.2-line comments

Three single quotes' '' enclosed

'''
我可以注释多行
我可以注释多行
我可以注释多行
'''

Three pairs of quotes "" "quotes

"""
我可以注释多行
我可以注释多行
我可以注释多行
"""

2 print output

Role: print to the screen some of the information

Can accept multiple strings, separated by commas, spaces will output a comma encounter

print(" It's a beautifu day", "Nice day", "my finished")
print(18)
print(10 + 8)
print("10 + 8 =", 18)

3 input input

Role: to obtain the value of the variable from outside

Waiting for input (blocking), the contents of the input variables in the newspaper in the age

age = input("请输入您的年龄:")
print("age =", age)

4 variables

Overview: The name of the program storage area operable, change during the run data, each variable has a specific type; the result of running the intermediate temporary memory is present, so that subsequent code calls.

Action: different types of data stored in the memory

Definition of variables: variable name = initial value (in order to determine the type of the variable)

Storing data: variable name = data value (Note: Variables must be "defined" before use (ie a value to a variable), otherwise an error occurs)

Delete variables: del variable names (variables can not be referenced later deleted)

Regulation 4.1 definition of variables

Variable names can be any combination of letters, numbers or underscore

The first character variable names can not be digital

May be defined to have variable descriptive

The following keywords can not be declared variable names:

['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']

4.2 Recommended defined way

#驼峰体

AgeOfOldboy = 56

NumberOfStudents = 80

#下划线

age_of_oldboy = 56

number_of_students = 80

4.3 Assignment of variables

#!/usr/bin/env python
# -*- coding: utf-8 -*-

name1 = "wupeiqi"
name2 = "alex"

Here Insert Picture Description

#!/usr/bin/env python
# -*- coding: utf-8 -*-

name1 = "taibai"
name2 = name1

Here Insert Picture Description

4.4 Defining variables bad way of example

Variable named Chinese, Pinyin

The variable name is too long

Variable noun lied

5 Constant

Constant refers to the same amount, such as pai 3.141592653 ..., or the amount of the program is running will not change

6 Data Types

What is a data type?

We humans can easily distinguish the difference between numbers and characters, but the computer does not die, although very powerful computer, but in some ways and silly point of view, unless you explicitly tell it, is the number 1, "Han" is the text, otherwise it is the difference and 'Chinese' tell of 1, therefore, in each programming language will have a data type of stuff is called, in fact, a variety of commonly used data types are clearly divided, you want the computer numerical calculation, you can transfer it to digital, you want him to word processing, you pass a string type to him.

6.1 integer int

Python can handle any size integer, of course, including negative integers, as expressed in the wording and mathematics program

num1 = 10
num2 = num1
print(id(num2))
# 连续定义多个变量
num3 = num4 = num5 = 1
print(num3, num4, num5)
1 1
#交互式赋值定义变量
num6, num7 = 6, 7
print(num6, num7)
7

6.2 Boolean value bool

Boolean value is two kinds: True, False. It is the correct reaction conditions or not.

True 1 True.

False 0 False

6.3 float float

Float integer part and fractional part of the composition, there may be rounding of floating point arithmetic error

f1 = 1.1
f2 = 2.2
f3 = f1 + f2
print(f3)
3.3000000000000003

6.4 Type String (str)

In Python, add a character quotes are considered to be a string!

>>> name = "Alex Li" #双引号
>>> age = "22"       #只要加引号就是字符串
>>> age2 = 22          #int
>>> hometown = 'ShanDong'   #单引号也可以

That single quotes, double quotes, and more quotes what difference does it make? Let me tell you out loud, single and double quotes wooden distinction of any kind, you only need to consider the following scenario with odd and even

msg = "My name is Alex, I'm 22 years old!"
more than what the role of the quotes it? Role is multi-line strings must be multi-quotes

msg = '''
今天我想写首小诗,
歌颂我的同桌,
你看他那乌黑的短发,
好像一只炸毛鸡。
'''
print(msg)

7 Data type conversion

print(int(1.9))
print(float(1))
1.0
print(int("123"))
print(float("12.3"))
12.3
#如果有其他无用字符会报错
print(int("abc"))
print(int("123abc"))
Traceback (most recent call last):
  File "H:/Python项目/day/file.py", line 2, in <module>
    print(int("abc"))
ValueError: invalid literal for int() with base 10: 'abc'
#只有作为正负号才有意义
print(int("+123"))
#print(int("12+3"))    #无意义会报错
print(int("-123"))
-123

8 digital functions

8.1 Returns the absolute value abs

a1 = -10
a2 = abs(a1)
print(a2)
10

8.2 magnitude comparison of two numbers

a3 = 100
a4 = 9
print((a3>a4)-(a3<a4))
1

8.3 max returns a maximum value given parameter

print(max(1,2,3,4,5,6,7,8))
8

8.4 min return to the minimum value of the given parameter

print(min(1,2,3,4,5,6,7,8))
1

8.5 x y-demand power pow

print(pow(2, 5))
32

round (x [, n]) returns the value of the floating point number x rounded, if given the value of n represents the n-bit rounded to the decimal point

print(round(3.456))
print(round(3.556))
print(round(3.456, 2))
3.46
print(round(3.546, 1))
3.5

8.5 mathematically related math library

import math
#   向上取整
print(math.ceil(18.1))
print(math.ceil(18.9))
#   向下取整
print(math.floor(18.1))
print(math.floor(18.9))
#   返回整数部分与小数部分
print(math.modf(22.3))
(0.3000000000000007, 22.0)
#   开方
print(math.sqrt(16))
4.0

9 range 指定范围,生成指定数字

for i in range(1,10):
    print(i)

for i in range(1,10,2):  # 步长
    print(i)

for i in range(10,1,-2): # 反向步长
    print(i)

10 随机数 random

从序列的元素中随机挑选一个元素

import random
print(random.choice([1, 3, 5, 7, 9]))

print(random.choice(range(5)))    #range(5)== [0,1,2,3,4]

print(random.choice("Lee")) # "Lee" == ["L", "e", "e"]

>打印结果:
0
e

产生一个1~100之间的随机数

print(random.choice(range(100)))

91

从指定范围内,按指定的基数递增的集合中选取一个随机数

#   random.randrange([start,] stop[,step])
#   start--指定范围的开始值,包含在范围内,默认是0
#   stop--指定范围的结束值,不包含在范围内
#   step--指定的递增基数,默认是1
print(random.randrange(1,100,2))
13
#    从0-99选取一个随机数
print(random.randrange(100))
61

随机生成[0,1]之间的数(浮点数)

print(random.random())
0.14728254253360773

随机生成一个实数,它在[3,9]范围

print(random.uniform(3,9))
4.516309142130013

11 运算符与表达式

11.1 算数运算

表达式:由变量、常量和运算符组成的式子

算术运算符和算术运算表达式

算术运算符

+   -    *    /     %      **      //

以下假设变量:a=10,b=20
Here Insert Picture Description

11.2 比较运算

以下假设变量:a=10,b=20

Here Insert Picture Description

11.3 赋值运算

以下假设变量:a=10,b=20

Here Insert Picture Description

11.4 逻辑运算

Here Insert Picture Description

11.4.1 and

逻辑与:  and
逻辑与运算表达式:表达式1  and  表达式2
值:
如果表达式1的值为真,表达式2的值也为真,整体逻辑与运算表达式的值为真
如果表达式1的值为真,表达式2的值为假,整体逻辑与运算表达式的值为假
如果表达式1的值为假,表达式2的值为真,整体逻辑与运算表达式的值为假
如果表达式1的值为假,表达式2的值也为假,整体逻辑与运算表达式的值为假  
【有一个为假就为假】 
表达式1  and  表达式2  and  表达式3  and  ......  and  表达式n
num1 = 10
num2 = 20
if num1 and num2:
    print("&&&&&&&&&&&")
&&&&&&&&&&&

11.4.2 or

逻辑或: or
逻辑或运算表达式:表达式1  or  表达式2
值:
表达式1的值为真,表达式2的值为真,逻辑或运算表达式为真
表达式1的值为真,表达式2的值为假,逻辑或运算表达式为真
表达式1的值为假,表达式2的值为真,逻辑或运算表达式为真
表达式1的值为假,表达式2的值为假,逻辑或运算表达式为假
【有一个为真就为真】
表达式1  or  表达式2  or  表达式3  or  ......  or  表达式n
num3 = 0
num4 = 1
if num3 or num4:
    print("||||||||||")
||||||||||

11.4.3 not

逻辑非:  not
逻辑非运算表达式:   not 表达式
值:
如果表达式的值为真,整体逻辑非运算表达式的值为假
如果表达式的值为假,整体逻辑非运算表达式的值为真
【颠倒黑白】
if not 0:
    print("++++++++++")
++++++++++

11.5 成员运算符

in:如果在指定的序列中找到值返回True,否则返回False
not in: 如果在指定的序列中没有找到值返回True,否则返回False

11.6 身份运算符

is:判断两个标志符是不是引用同一个对象
is not:判断两个标志符是不是引用不同的对象

11.7 运算符优先级

运算符优先级
**
~ + -   正负号(一元加减)
*   /   %   //
+   -
>>  <<
&
~   |
<=  <   >   >=
==  !=
=   %=  +=  -=  //= 
is  in not
in  not in 
and     or      not

12 if for while 语句

12.1 if 语句

格式:

if 表达式:
    语句...

逻辑:当程序执行到if语句时,首先计算“表达式”的值,如果“表达式”的值为真,那么执行if下的“语句”,如果“表达式”的值为假,则跳过整个if语句继续向下执行。
何为真假?

假:0 0.0 ‘’ None False
真:除了假就是真

num5 = 10
num6 = 20
if num5 == num6:
    num5 = 100
print("num5 =", num5)
num5 = 10
--------------------------------
num5 = 20
num6 = 20
if num5 == num6:
    num5 = 100
print("num5 =", num5)
num5 = 100

12.2 if -else 语句

格式:

if 表达式:
    语句1
else:
    语句2

逻辑:当程序执行到if-else语句时,首先计算“表达式”的值,如果表达式的值为真,则执行 “语句1”。执行完“语句1”跳出整个if-else语句。如果“表达式”的值为假,则执行“语句2”。执行完“语句2”跳出整个if-else语句。

num = int(input())
if num % 2 == 0:
    print("是偶数")
else:
    print("是奇数")

12.3 if-elif-else 语句

格式:


if  表达式1:
    语句1
elif 表达式2:
    语句2
elif 表达式3:
    语句3
……
elif 表达式n:
    语句n
else:                    #可有可无
    语句e

Logic: When the program executes the if-elif-else statements, first calculated value "Expression 1", if "Expression 1" is true, execute "statement 1", executing the "statement 1", skip the entire if-elif-else statement. If "expression 1" is false, calc "Expression 2". If "Expression 2" is true, execute "statement 2", executing the "sentence 2", then skip the entire if-elif-else statements. If "Expression 2" is false, calc "Expression 3". It goes really did not stop until the value of an expression, if not a true expression, and there is else, then execute "statement e"

age = int(input())
if age < 0:
    print("娘胎里")
if age >=0 and age <= 3:
    print("婴儿")
if age >=4 and age <= 6:
    print("儿童")
if age >=7 and age <= 18:
    print("童年")
if age >=19 and age <= 30:
    print("青年")
if age >=31 and age <= 40:
    print("壮年")
if age >=41 and age <= 50:
    print("中年")
if age >=51 and age <= 100:
    print("老年")
if age >=101 and age <= 150:
    print("老寿星")
if age > 150:
    print("老妖怪")

12.6 for loop

format:

for 变量名 in 集合:
    语句

Logic: by taking sequence "collection" is assigned to each element of "variable" in the statement to execute. So on ad infinitum, until take complete "collection" in the cut-off element

range([start,] end[, step])函数 列表生成器
start默认为0,step默认为1
功能呢:生成数列
a = range(10)
print(a)
range(0, 10)

for x in range(10):
    print(x, end=" ")
1 2 3 4 5 6 7 8 9

for y in range(2, 20, 2):
    print(y, end=" ")
4 6 8 10 12 14 16 18

While traversing the index and the elements

方法一:
for index, m in enumerate([1,2,3,4,5]): #index, m = 下标,元素
    print(index, m)
1
2
3
4
5

方法二:
index = 0
for i in range(1,6):
    print(index, i)
    index += 1
1
2
3
4
5

12.7 while loop

format:

while 表达式:
    语句

Logic: When the program executes the while statement, first calculate the value of "expression" if "expression" is false, then the end of the entire while statement. If the "expression" is true, then execute "statement", executing the "statement" to go to a value of "expression" is calculated. If the "expression" is false, then the end of the entire while statement. If the value of "expression" is also true, then execute "statement", executing the "statement" to go to the calculated value "expression" of. So the cycle, we know the expression is false stopped.

while 表达式:
    语句1
else:
    语句2

逻辑:在条件语句(表达式)为False时执行else中的“语句2”

a = 1
while a <= 3:
    print("lee is a good man!")
    a += 1
else:
    print("very very good")

print("you are right")

12.8 break statement

effect:

And out of the loop for a while

Note: You can only jump from his recent cycle that layer

for i in range(10):
    print(i)
    if i == 5:
        break

num = 1
while 1 <= 10:
    print(num)
    if num == 3:
        break
    num += 1
#注意:循环语句可以有else语句,break导致循环截止,不会执行else下面的语句
else:
    print("lee is a good man")

12.9 continuc statement

Role: out of the remaining statements in the current cycle, and then continue to the next cycle

Note: The jump from the nearest cycle

for i in range(10):
    print(i)
    if i == 3:
        continue
    print("*")
    print("&")

num = 0
while num < 10:
    print(num)
    if num == 3:
        num += 1
        continue
    print("*")
    print("&")
    num += 1
Published 126 original articles · won praise 12 · views 9450

Guess you like

Origin blog.csdn.net/qq_43141726/article/details/104458922