python环境搭建和基础语法

搭建开发环境

官网下载安装python,主流编辑器有pycharm和vscode,习惯了用vscode就选它吧。安装vscode插件Python。 新建一个.py文件,输入print('hello world'),按右边的执行按钮,打开vscode控制台,会看到控制台自动执行了一段脚本,说明现在使用的是全局环境的python编译器, 这就会带来一些版本上的问题,比如不同的项目使用不同版本的python或者其他python库。所以python推出了虚拟环境,每一个项目可以使用单独的环境,互相不影响,看下vscode文档里对这个环境的解释 所以怎么使用虚拟环境呢,vscode里ctrl+shift+p输入python:create,选择Python: Create Environment,然后把之前的控制台关掉新开一个控制台,这时候会看到如图,控制台命令前面多了(.venv),项目目录下多了.venv的文件夹,说明现在这个项目在使用自己的虚拟环境了,如果没这个(.venv)说明虚拟环境没激活,到.env/Script/目录下执行Activate.ps1可以手动激活(windows系统下执行ps1,其他系统找对应的可执行脚本) 可以看到.venv下Lib\site-packages里就是存python包的地方,其实就和js里node_modules差不多。js的包管理工具是npm,python的是pip,常用的安装、升级命令:

1
2
3
4
python -m pip install pygame 
pip list
pip list --outdated
pip install pygame --upgrade

语法

python的语法非常简洁,给人的感觉就是能省就省,我整理了些简单的例子,结合注释看。

变量声明

声明变量不需要使用关键字,不同类型的变量拼接或者计算时不会强制类型转换,需手动调用int()、str()这些转换方法进行类型转换

1
2
3
first_name = "Bro"
age = "21" // age = int("21")
age += 1

字符串

处理字符串的方法挺多

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
name = "Nicola Jokic"
print(len(name)) #12
print(name.find("o")) #3
print(name.capitalize()) #Nicola jokic
print(name.upper()) #NICOLA JOKIC
print(name.isdigit()) #False
print(name.isalpha()) #False
print(name.count("o")) #2
print(name.replace("o","a")) #Nicala Jakic
print(name*3) #Nicola JokicNicola JokicNicola Jokic
first_name = name[0:6] #Nicloa
last_name = name[7:] #Jokic
funky_name = name[0::2] #Ncl oi
reversed_name = name[::-1] #cikoJ alociN
slice = slice(2, -6)
print(name[slice]) #cola

# str.format()
animal = 'cow'
item = 'moon'
print("hello my name is {:20} hh".format(name))
print("the {animal} jumped over the {item}".format(animal=animal, item=item))
number = 3.14159
print('the number is {:.3f}'.format(number))
print('the number is {:,}'.format(100000))

number

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import math

pi = 3.14
x = 1
y = 2
z = 3
print(round(pi)) #3
print(math.ceil(pi)) #4
print(math.floor(pi)) #3
print(abs(pi)) #3.14
print(pow(pi,2)) #9.8596
print(math.sqrt(pi)) #1.772004514666935
print(max(x,y,z)) #3

数组

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
food = ["pizza","hotdog","hamburger"]
food.append("ice cream")
food.remove("hotdog")
food.pop()
food.insert(0, "cake")
food.sort()
food.clear()
print(food)
# 排序
food.sort() # 改变原数组
sorted_food = sorted(food, reverse=True) # 返回新数组
ss = [("Tom","F", 40),
      ("Sandy","A", 33),
      ("Jack","B", 20)]
grade = lambda grades:grades[1]
ss.sort(key=grade) #按每个tuple的第二项进行排序

# map(function, iterable), filter(funciton, iterable)
store = [("shirt", 20.00), ("pants", 25.00)]
to_eruos = lambda data: (data[0], data[1]*0.82)
store_euros = list(map(to_eruos, store)) # 返回的都是tuple类型

# 遍历数组可以用for循环,也提供了简化的语法
squares = []
for i in range (1, 11):
    squares.append(i * i)

squares = [i*i for i in range(1,11)] # 一行搞定

students = [100,90,80,70,60,50,40]
# 从数组中筛选出及格的可以这样写
passed_students = list(filter(lambda x:x>=60, students))
passed_students = [i for i in students if i >= 60]
passed_students = [i if i >= 60 else "failed" for i in students]

tuple

和数组有点像,区别是tuple用圆括号包裹,并且不能更改,tuple是有顺序的,tuple的性能更好

1
2
3
4
5
student = ("A",21,"male")
student.count("A") # 1
student.index("male") # 2
if "A" in student:
    print("in")

set

无序

1
2
3
4
5
6
7
8
utensils = {"fork", "spoon", "knife"}
dishes = {"bowl","plate","cup","knife"}
utensils.add("napkin")
utensils.remove("fork")
utensils.clear()
dishes.update(utensils)
dishes.difference(utensils)
dishes.intersection(utensils) #{"knife"}

dictionary

和js的对象差不多,key:value的键值对

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
capitals = {'USA':'Washington DC','China':'Beijing'}
capitals.update({'Germany':'Berlin'})
capitals.pop('China')
print(capitals.get('China'))
print(capitals.keys())
print(capitals.values())
print(capitals.items())

for key,value in capitals.items(): # 遍历dictionary类型的数据如果要获取没项的key,value,需要遍历.items()
    print(key,value)
    
new_cap = {key: value.upper() for (key,value) in capitals.items()} #简化语法
print(new_cap)

条件语句

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
age = int(input("how old are you?"))
if age >= 18:
    if age > 20 and age < 30:
        print("1")
    elif not(age > 45 or age < 20):
        print("2")
elif age < 3: #elseif这也是能省就省
    print("you are a baby")
else:
    print("you are a child")

循环遍历

python中可迭代的数据类型包括了list, tuple, set, string, dictionary, generator,都可以使用for循环遍历

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# for loop
for i in range(10):
    print(i)

for i in range(10,15,2):
    print(i) #10 12 14

for i in "hello world":
    print(i)

# while loop
while True:
    name = input("enter your name")
    if name != "":
        break

phone_number = "123-456-7890"
for i in phone_number:
    if i == '-':
        continue  
    print(i, end="")

function

def关键字也是能省就省,大括号也省了

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def hello(first, last):
    print(first + last)

hello("a","b")
hello(first="a", last="b")

# *args = parameter that will pack all arguments into a tuple, useful so that a function can accept a varying amout of arguments
def add(*stuff):
    sum = 0
    for i in stuff:
        sum += i
    return sum

print(add(1,2,3,4,5))

# **kwargs = parameter that will pack all arguments into a dictionary
def hello(**kwargs):
    print(kwargs['first']+kwargs['last'])
hello(first="abc", last="123")

lambda函数

有点类似于js的匿名函数

1
2
3
4
double = lambda x:x * 2
multiply = lambda x, y: x * y
age_check = lambda age: True if age > 18 else False
double(5)

海象运算符:=

在表达式中就能完成对变量赋值,这玩意的目的也是简化代码吧

1
2
3
4
print(happy := True)
foods = list()
while food := input("what food do you like?") != "quit":
    foods.append(food)

类与继承

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Animal:
    alive = True
    def __init__(self, make): # 构造函数
        self.make = make

    def eat(self):
        print('this animal is eating')

    def sleep(self):
        print('this animal is sleeping')

class Rabbit(Animal): # 继承Animal
    def fun(self):
        print('run')

class Fish(Animal):
    def eat(self):
        super().eat() #super()调用父类方法
        print('fish eat')
        return self

rabbit = Rabbit()
fish = Fish()

from abc import ABC, abstractmethod
# 抽象类抽象方法,js里没这个概念,父类中定义的抽象方法子类中必须实现不然会报错
class Vehicle(ABC): # 抽象类需要继承ABC这个类
    @abstractmethod #子类中必须实现该方法
    def go(self):
        pass

class Car(Vehicle):
    def go(self):
        print("1")

错误处理

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
try:
    n = int(input('enter a number'))
    n2 = int(input('enter another number'))
    print(n / n2)
except Exception as e:
    print('error', e)
else:
    print('2')
finally:
    print('6')

线程

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import threading
import time

def eat_breakfast():
    time.sleep(3)
    print('brakfast')

def drink_coffee():
    time.sleep(4)
    print('coffee')

def study():
    time.sleep(5)
    print('study')

x = threading.Thread(target=eat_breakfast, args=())
x.start()

y = threading.Thread(target=drink_coffee, args=())
y.start()

z = threading.Thread(target=study, args=())
z.start()

x.join() #等待该线程执行结束
y.join()
z.join()

print(threading.enumerate())


# daemon thread a background thread that runs independently of the main program and terminates when the main program finishes

def timer():
    print()
    count = 0
    while True:
        time.sleep(1)
        count += 1
        print("logged in for: ",count, "seconds")

x = threading.Thread(target=timer, daemon=True)
x.start()
answer = input("Do you wish to exit?")

# multiprocessing
from multiprocessing import Process, cpu_count
def counter(num):
    count = 0
    while count < num:
        count += 1

def main():
    start_time = time.perf_counter()
    print(cpu_count())
    a = Process(target=counter, args=(500000000,))
    b = Process(target=counter, args=(500000000,))
    a.start()
    b.start()
    a.join()
    b.join()
    end_time = time.perf_counter()
    print("finished in ", end_time - start_time)

if __name__ == '__main__':
    main()

随机生成

1
2
3
4
import random
cards = [1,2,3,4,5,6,7,8,9]
random.shuffle(cards)
z = random.choice(cards)
comments powered by Disqus