[Python Basics 1] Super detailed tutorial for entry-level friends

foreword

Many friends just started to get in touch with python, and they are full of thinking about typing codes, collecting this and that, but the fact is that their foundation is extremely poor.

Then share some basic python tutorials that Xiaobai reads [a total of four articles] You can bookmark them, I should update one every day

If you still don't understand anything, you can directly click on the business card at the end of the article to learn and communicate

1. Basic concepts

1.1 Four types

There are four types of numbers in python: integers, long integers, floating point numbers, and complex numbers.

  • integer, such as 1
  • Long integers are relatively large integers
  • Floating point numbers such as 1.23, 3E-2
  • Complex numbers such as 1 + 2j, 1.1 + 2.2j

1.2 Strings

Baozi, who just started to get in touch with Python, you can private message me if you don’t understand anything

I've also prepared tons of free video tutorials, PDF e-books, and source code! Just pick up the business card at the end of the article!

string (sequence of characters)

  • Single quotes and double quotes are exactly the same in python.
  • Use triple quotes (''' or """) to specify a multi-line string.
  • Escapes'\'
  • Natural strings, by prefixing the string with r or R. If r"this is a line with \n"will be\n displayed, not a newline.
  • Python allows to handle unicodestrings, prefixed with u or U, eg u"this is an unicode string".
  • Strings are immutable.
  • Concatenate strings literally, such as "this " "is " "string" will be automatically converted to this is string.

1.3 Naming of identifiers

Identifier naming

  • The first character must be a letter of the alphabet or an underscore '_'.
  • The rest of the identifier consists of letters, numbers, and underscores.
  • Identifiers are case sensitive.

1.4 Objects

Any "thing" used in a python program becomes an "object".

1.5 Logical row and physical row

  • Physical line: It is the line where the code written by the programmer is located.
  • Logical line: refers to the line where the code is located after the source code is precompiled.

Python assumes that each physical row corresponds to a logical row. For example: print("Hello World") is a physical line, and Python wants to have only one statement per line, because it looks more readable.

If you want to use more than one logical line in a physical line, then you need to use a semicolon ( ; ) to specifically mark this usage. A semicolon marks the end of a logical line/statement.

For example:

count = 5
print ( "count" )

Equivalent to the following statement:

count = 5print ( "count" );

Of course it can also be written as follows:

count = 5 ; print ( "count" );

It can even be written like this:

count = 5 ; print ( "count" )

\newline we use

print \
("Runsen")

1.6 Indentation

Blanks are very important in python, and the blanks at the beginning of the line are the most important, also known as indentation. Whitespace (spaces and tabs) at the beginning of a line is used to determine the indentation level of logical lines and thus statements.

2. Operators and expressions

2.1 Operators and their usage

operator name example
+ Adds two objects Addition, such as 3 + 5 to get 8, characters can also be added 'a' + 'b' to get 'ab'
- one number minus another 5 - 2 gets 3
* Multiplies two numbers or returns a string repeated several times 2*3 gets 6, 'a'*3 gets 'aaa'
** power returns x raised to the power of y 3**4 gets 81 (i.e. 3*3*3*3)
/ divide x by y 4/3 yields 1 (division of integers yields an integer result). 4.0/3 or 4/3.0 gets 1.3333
// Rounding and division returns the integer part of the quotient 4 // 3.0 gets 1.0
% Modulo returns the remainder of division 8% 3 get 2. -25.5% 2.25 gets 1.5
<< Left shift, shift the binary number of a number to the left by a certain number, that is, how many 0s are added to the right, Such as 2 << 2 to get 8, binary 10 becomes 1000
>> Shift right Shift the bits of a number to the right by a certain number, that is, delete the digits on the right 10>>2 gets 2, binary 1010 becomes 10, delete the last 2 digits directly
& bitwise AND The bitwise AND 9 & 13 of the number gets 9, binary 1001&1101, becomes 1001, and the corresponding positions of the two values ​​are both 1, then the result is 1, otherwise it is 0
| bitwise or The bitwise OR of the numbers 5|3 yields 7. Binary 101&11 becomes 111. If one of the corresponding positions of the two values ​​is 1, then the result is 1, that is, if both are 0, the result is 0. Neither 101 nor 11 are both 0, so 111
^ bitwise XOR The bitwise exclusive OR 5 ^ 3 of the number gets 6, binary 101&11, becomes 110, and the corresponding positions of the two values ​​are the same, then the result is 0, that is, if both are 0 or both are 1, the result is 0, 101 and 11, the first one is 1, so 110
~ bit flip The bitwise flip of x is -(x+1) ~5 gets 6
< less than returns whether x is less than y. All comparison operators return 1 for true and 0 for false. 5 < 3 returns 0 (i.e. False) and 3 < 5 returns 1 (i.e. True). Can also be arbitrarily concatenated: 3 < 5 < 7 returns True.
> greater than returns whether x is greater than y 5 > 3 returns True. If both operands need to be numbers
<= less than or equal returns whether x is less than or equal to y x = 3; y = 6; x <= y returns True
>= greater than or equal returns whether x is greater than or equal to y x = 4; y = 3; x >= y returns True
== Is equal to whether the comparison object is equal x = 2; y = 2; x == y returns True
!= Not equal compares whether two objects are not equal x = 2; y = 3; x != y returns True.
not Boolean "not" If x is True, return False x = True; not y returns False.
or Boolean OR It returns True if x is True, otherwise it returns the computed value of y. x = True; y = False; x or y specifier True

2.2 Operator precedence

.Operator precedence (from low to high)

operator describe
lambda Lambda expressions
or Boolean "or"
and Boolean "and"
not x Boolean "not"
in,not in member test
is,is not identity test
<,<=,>,>=,!=,== Compare
` `
^ bitwise XOR
` `
& bitwise AND
<<,>> shift
+, - Addition and Subtraction
*,/,% Multiplication, Division and Remainder
+x,-x sign
~x bit flip
** index
~x bit flip
x.attribute 属性参考
x[index] 下标
x[index:index] 寻址段
f(arguments…) 函数调用
(experession,…) 绑定或元组显示
[expression,…] 列表显示
{key:datum,…} 字典显示
‘expression,…’ 字符串

2.3 输出

python 控制台输出 使用print

print ("abc"  )  #打印abc并换行
print ("abc%s" % "d"  )  #打印abcd
print ("abc%sef%s" % ("d", "g")  )  #打印abcdefg

3、控制流

3.1 if 语句

i = 10
n = int(input("enter a number:"))

if n == i:
    print( "equal")
elif n < i:
    print( "lower")
else:
    print ("higher")

3.2 while语句

while True:
    pass
else:
    pass
#else语句可选,当while为False时,else语句被执行。 pass是空语句。

for 循环 for…in

for i in range(0, 5):
    print (i)
else:
    pass
# 打印0到4

注:当for循环结束后执行else语句;
range(a, b)返回一个序列,从a开始到b为止,但不包括b,range默认步长为1,可以指定步长,range(0,10,2);

3.3 break语句

终止循环语句,如果从for或while中终止,任何对应循环的else将不执行。

3.4 continue语句

continue语句用来调过当前循环的剩余语句,然后继续下一轮循环。

下面就是 break 和 continue 主要的 区别:

  • break:跳出整个循环
  • continue:跳出本次循环,继续执行下一次循环
    希望大家牢记。

4、函数

函数通过def定义。def关键字后跟函数的标识符名称,然后跟一对圆括号,括号之内可以包含一些变量名,该行以冒号结尾;接下来是一块语句,即函数体。

def sumOf(a, b):
    return a + b

4.1 函数形参

函数中的参数名称为‘形参’,调用函数时传递的值为‘实参’

4.2 局部变量

在函数内定义的变量与函数外具有相同名称的其他变量没有任何关系,即变量名称对于函数来说是局部的。这称为变量的作用域。

global语句, 为定义在函数外的变量赋值时使用global语句。

def func():
    global x
    print( "x is ", x)
    x = 1

x = 3
func()
print(x)
#3
#1 

4.3 默认参数

通过使用默认参数可以使函数的一些参数是‘可选的’。

def say(msg, times =  1):
    print(msg * times)

say("Runsen")
say("Runsen", 3)

注意:只有在形参表末尾的那些参数可以有默认参数值,即不能在声明函数形参的时候,先声明有默认值的形参而后声明没有默认值的形参,只是因为赋给形参的值是根据位置而赋值的。

4.4 关键参数

如果某个函数有很多参数,而现在只想指定其中的部分,那么可以通过命名为这些参数赋值(称为‘关键参数’)。
优点:不必担心参数的顺序,使函数变的更加简单;假设其他参数都有默认值,可以只给我们想要的那些参数赋值。

def func(a, b=2, c=3):
    print ("a is %s, b is %s, c is %s") % (a, b, c)

func(1) #a is 1, b is 2, c is 3
func(1, 5) #a is 1, b is 5, c is 3
func(1, c = 10) #a is 1, b is 2, c is 10
func(c = 20, a = 30) #a is 30, b is 2, c is 20

4.5 return 语句

return语句用来从一个函数返回,即跳出函数。可从函数返回一个值。
 没有返回值的return语句等价于return None。None表示没有任何东西的特殊类型。

4.5 文档字符串

__doc__ (文档字符串)

def func():
    '''This is self-defined function
	Do nothing
	'''
    pass

print(func.__doc__)

#This is self-defined function
#
#Do nothing

5、模块

模块就是一个包含了所有你定义的函数和变量的文件,模块必须以.py为扩展名。模块可以从其他程序中‘输入’(import)以便利用它的功能。

在python程序中导入其他模块使用’import’, 所导入的模块必须在sys.path所列的目录中,因为sys.path第一个字符串是空串’'即当前目录,所以程序中可导入当前目录的模块。

5.1 字节编译的.pyc文件

导入模块比较费时,python做了优化,以便导入模块更快些。一种方法是创建字节编译的文件,这些文件以.pyc为扩展名。

pyc是一种二进制文件,是py文件经编译后产生的一种byte code,而且是跨平台的(平台无关)字节码,是有python虚拟机执行的,类似于

java或.net虚拟机的概念。pyc的内容,是跟python的版本相关的,不同版本编译后的pyc文件是不同的。

5.2 from … import

如果想直接使用其他模块的变量或其他,而不加’模块名+.'前缀,可以使用from … import。

例如想直接使用sys的argv,from sys import argv 或 from sys import *

5.3 模块的__name__

每个模块都有一个名称,py文件对应模块名默认为py文件名,也可在py文件中为__name__赋值;如果是__name__,说明这个模块被用户

(4) dir()函数

  • dir(sys)返回sys模块的名称列表;如果不提供参数,即dir(),则返回当前模块中定义名称列表。

(5) del

del -> 删除一个变量/名称,del之后,该变量就不能再使用。

6、数据结构

python有三种内建的数据结构:列表、元组和字典。

6.1 列表

list是处理一组有序项目的数据结构,列表是可变的数据结构。列表的项目包含在方括号[]中,

eg: [1, 2, 3], 空列表[]。判断列表中是否包含某项可以使用in,

比如 l = [1, 2, 3]; print 1 in l; #True;

支持索引和切片操作;索引时若超出范围,则IndexError;

使用函数len()查看长度;使用del可以删除列表中的项,eg: del l[0] # 如果超出范围,则IndexError
    
list函数如下:

append(value)  ---向列表尾添加项value
l = [1, 2, 2]
l.append(3) #[1, 2, 2, 3]

count(value)  ---返回列表中值为value的项的个数
l = [1, 2, 2]
print( l.count(2)) # 2

extend(list2)  ---向列表尾添加列表list2
l = [1, 2, 2]
l1 = [10, 20]
l.extend(l1)
print (l )  #[1, 2, 2, 10, 20]

index(value, [start, [stop]])  ---返回列表中第一个出现的值为value的索引,如果没有,则异常 ValueError

l = [1, 2, 2]
a = 4
try:
    print( l.index(a))
except ValueError, ve:
    print( "there is no %d in list" % a
    insert(i, value))  ---向列表i位置插入项vlaue,如果没有i,则添加到列表尾部

l = [1, 2, 2]

l.insert(1, 100)
print l #[1, 100, 2, 2]

l.insert(100, 1000)
print l #[1, 100, 2, 2, 1000]

pop([i])  ---返回i位置项,并从列表中删除;如果不提供参数,则删除最后一个项;如果提供,但是i超出索引范围,则异常IndexError

l = [0, 1, 2, 3, 4, 5]

print( l.pop()) # 5
print( l) #[0, 1, 2, 3, 4]

print( l.pop(1)) #1
print( l) #[0, 2, 3, 4]

try:
    l.pop(100)
except IndexError, ie:
    print( "index out of range")

remove(value)  ---删除列表中第一次出现的value,如果列表中没有vlaue,则异常ValueError

l = [1, 2, 3, 1, 2, 3]

l.remove(2)
print (l )#[1, 3, 1, 2, 3]

try:
    l.remove(10)
except ValueError, ve:
    print ("there is no 10 in list")

reverse()  ---列表反转

l = [1, 2, 3]
l.reverse()
print (l) #[3, 2, 1]

sort(cmp=None, key=None, reverse=False)  ---列表排序

l5 = [10, 5, 20, 1, 30]
l5.sort()
print( l5) #[1, 5, 10, 20, 30]

l6 = ["bcd", "abc", "cde", "bbb"]
l6.sort(cmp = lambda s1, s2: cmp(s1[0],s2[1]))
print( l6) #['abc', 'bbb', 'bcd', 'cde']

l7 = ["bcd", "abc", "cde", "bbb", "faf"]
l7.sort(key = lambda s: s[1])
print (l7) #['faf', 'abc', 'bbb', 'bcd', 'cde']

Guess you like

Origin blog.csdn.net/yxczsz/article/details/128635732