Python 入门一

环境

我是使用vs code作为本地的开发环境,关于如何setup可参考 Getting Started with Python in VS Code

关于多版本的问题,如果机器上有2.x版本又有3.x版本,可以通过pyenv 这个工具进行管理的,这个工具非常好的解决了版本切换的问题,关于如何安装与使用可以参考pyenv github库。

安装Python可以是独立的Python版本,也可以是集成Anaconda, 如果使用Anaconda安装,它自带了许多包例如:Numpy,Pandas,matplotlib,还有后文提到的Jupyter 等,不需要再独立安装了

关于安装包的问题,国内下载Python第三方包比较慢,可以使用国内的镜像来提高速度

清华:https://pypi.tuna.tsinghua.edu.cn/simple

阿里云:http://mirrors.aliyun.com/pypi/simple/

中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/

豆瓣:http://pypi.douban.com/simple/

使用方法:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple 库名

Jupyter 是一个学习Python很棒的工具,关于如何在VS Code里使用可参考Working with Jupyter Notebooks in Visual Studio Code

基础

数字 Numbers

由于Python是一种弱类型语言,所以在都需要生命变量类型,可以直接使用,例如

i=1
f=2.5

Python解释器会判处出i为整数类型,f为浮点类型,如果运行下面的代码

print(type(i))
print(type(f))

我们会得到

布尔类型

Pyton中的布尔类型是True 和 False, 布尔类型的计算可以使用and, or 和not

字符串 Strings

字符串可以使用单引号,双引号,如果是多行声名,可以使用三个单引号。例如

str1 = 'I am a string in single quotes'
str2 = "I am a string in double quotes"
str3 = '''I am a string with
multiple lines'''

就像.net的字符串一样,Python中的字符串也是不可变的(Immutable)

在开发程序的过程中,我们会经常用到字符串格式化,Python的格式化有下面几种方法

age = 20
name = 'Tom'
str_format1 = 'My name is '+name+', I am '+str(age)
str_format2 = 'My name is {0}, I am {1}'.format(name,age)
str_format3 = 'My name is {name}, I am {age}'.format(name=name,age=age)

Python 3.6引入了一种新的方式

str_format4 = f'My name is {name}, I am {age}'

Raw string

如果我们不需要Python替我们处理字符串中的任何字符,例如换行符\n, 我们可以再字符串的前面加个r

另外Python 3的字符串使用Unicode,直接支持多语言,默认我们应该使用utf-8的编码方式

代码块

如果你使用过.net,会知道每一代码行是通过";"分割的,代码块是用过”{}"表示的,然而在Python中代码块是通过缩进来表示的

i = 1
 print('This line will cause an error',i)#由于缩进问题,在运行是代码会报错
print('This line is good',i)

运算符及表达式

  • +(plus) 加 3 + 5 = 8. 'a' + 'b' = 'ab'.

  • -(minus) 减或负数

  • *(multiply) 相乘 2 * 3 = 6. 'la' * 3 = 'lalala'.

  • **(power) x的y次方
    3 ** 4 = 81 (i.e. 3 * 3 * 3 * 3)

  • / (divide) 除法
    13 / 3 = 4.333333333333333

  • // (divide and floor) 相除并取整,如果有float类型,那么结果也会是float
    13 // 3 = 4
    -13 // 3 = -5
    9//1.81 = 4.0

  • % (modulo) 取余数(remainder)
    13 % 3 gives 1. -25.5 % 2.25 gives 1.5.

  • << (left shift) 按位左移

    2 << 2 会得到 8. 相当于二进制0010左移两位变成1000 即8

  • >> (right shift) 按位右移

    11 >> 1 得到 5. 1101右移一位变成0110 即5

  • & (bit-wise AND) 按位与

    Bit-wise AND of the numbers: if both bits are 1, the result is 1. Otherwise, it's 0.
    5 & 3 gives 1 (0101 & 0011 gives 0001)

  • | (bit-wise OR) 按位或

    Bitwise OR of the numbers: if both bits are 0, the result is 0. Otherwise, it's 1.
    5 | 3 gives 7 (0101 | 0011 gives 0111)

  • ^ (bit-wise XOR) 按位异或

    Bitwise XOR of the numbers: if both bits (1 or 0) are the same, the result is 0. Otherwise, it's 1.
    5 ^ 3 gives 6 (O101 ^ 0011 gives 0110)

  • ~ (bit-wise invert)

    The bit-wise inversion of x is -(x+1)
    ~5 gives -6. More details at http://stackoverflow.com/a/11810203

  • < (less than)

    Returns whether x is less than y. All comparison operators return True or False. Note the capitalization of these names.
    5 < 3 gives False and 3 < 5 gives True.
    Comparisons can be chained arbitrarily: 3 < 5 < 7 gives True.

  • > (greater than)

    Returns whether x is greater than y
    5 > 3 returns True. If both operands are numbers, they are first converted to a common type. Otherwise, it always returns False.

  • <= (less than or equal to)

    Returns whether x is less than or equal to y
    x = 3; y = 6; x <= y returns True

  • >= (greater than or equal to)

    Returns whether x is greater than or equal to y
    x = 4; y = 3; x >= 3 returns True

  • == (equal to)

    Compares if the objects are equal
    x = 2; y = 2; x == y returns True
    x = 'str'; y = 'stR'; x == y returns False
    x = 'str'; y = 'str'; x == y returns True

  • != (not equal to)

    Compares if the objects are not equal
    x = 2; y = 3; x != y returns True

  • not (boolean NOT)

    If x is True, it returns False. If x is False, it returns True.
    x = True; not x returns False.

  • and (boolean AND)

    x and y returns False if x is False, else it returns evaluation of y
    x = False; y = True; x and y returns False since x is False. In this case, Python will not evaluate y since it knows that the left hand side of the 'and' expression is False which implies that the whole expression will be False irrespective of the other values. This is called short-circuit evaluation.

  • or (boolean OR)

    If x is True, it returns True, else it returns evaluation of y
    x = True; y = False; x or y returns True. Short-circuit evaluation applies here as well.

流程控制

下面的内容相对简单,有点编程经验的看下就明白

  • if

    条件控制语句 if

    str=input('enter a string:')
    if len(str)>5:
        print('the length of input string is greater than 5')
    elif len(str)>2:
        print('the length of input string is greater than 2 but less than 5')
    else:
        print('the length of input string is less than 2')
    
  • while

    running = True
    while running:
        str = input('Enter a strig:')
        if str=="quit":
           print('quit the loop')
           running=False
        else:
             print(f"You entered {str}, you can enter 'quit' to exit" )
    else:
        print('the while loop is ended')
        
    
  • for

    for i in range(1, 5):
        print(i)
    else:
        print('The for loop is over')
    

数据结构

Python内置的数据结构有List,Tuple,Dictionary,Set
List是一个有序项的数据集合,可以添加,删除数据项,List数据集使用中括号表示

namelist = ['Tom', 'Bob', 'Sam']
print('There are ',len(namelist),'items in the list')
print('Sort the name list')
namelist.sort()
print('Sorted name list is',namelist)
print('The first name in the list is',namelist[0])
namelist.append('Amy')
print('Added a new name to the list',namelist)

Tuple也是一种有序列表,和list类似,只不过tuple初始化后就不能再修改

#这段代码会报错,因为第二行试图去修改这个tuple集合
tuplelist=('Tom','Bob')
namelist[0]='Sam'

Dictionary字典类型,使用键-值(key-value)存储

name_email={
    'Tom':'[email protected]',
    'Bob':'[email protected]',
    'Sam':'[email protected]'
}
print("Bob's email is",name_email['Bob'])
del name_email['Bob']
for name,email in name_email.items():
    print('name: {} email: {}'.format(name,email))
#add a new item
name_email['Amy']='[email protected]'
if 'Amy' in name_email:
    print("Amy's email is ",name_email['Amy'])

Set是一种无序不重复集合

country=set(['china','japan','us'])
print('us' in country)#True
country.add('india')
country.remove('us')
print(country)#{'india','china','japan'}
x=set('three')
print(x)#{'h','r','t','e'}

函数

Python的函数定义非常简单,参数可以没有,也可以是固定参数,可变参数,关键字参数,参数的定义非常灵活, 我们用例子加以说明

def fun():
    return 'fun 1'
def power(x):
    return x*x
def power(x,n=2):
    return x**n
#可变参数
def calc(*numbers):
    sum=0
    for n in numbers:
        sum+=n
    return sum
#关键字参数,dictionary
def combine(**kw):
    for k,v in kw:
        prin("key:{} value:{}".format(k,v))

文章参考

https://python.swaroopch.com/

https://www.liaoxuefeng.com/wiki/1016959663602400/1017063826246112

你可能感兴趣的:(Python 入门一)