2022年 11月 5日

python 最简单基础教程

环境自行官网下载安装。

前提说明:

python是自上向下执行代码,有严格的缩进要求。

  1. #1.变量t
  2. t = 2 int类型
  3. t = '2' 字符串类型
  4. t = 2.2 float类型
  5. t = [2,3] 数组(列表)类型
  6. t = {'s':'v'} 字典类型
  7. python 声明变量不用指定类型 根据值得类型 具体详细解释自行百度
  8. #2.循环
  9. t = [2,3,4,5]
  10. #循环内容
  11. for i in t:
  12. print(i)
  13. #根据长度循环 len(t)可以替换成数字
  14. for i in range(len(t)):
  15. print(t[i])
  16. t = {'s':'v'}
  17. for k in t.keys():
  18. print(t.get(k))
  19. #3.条件判断
  20. t = 3
  21. if str(t).isdigit(): # str() 把t转成字符串,因为.isdigit()是字符串类型的函数
  22. print('t 是数字!')
  23. if t > 2:
  24. print('t 大于2')

差不多就这样了,之所以学python因为python开发效率太高了,同样的功能java声明一个类的代码行数就够python完成功能了。当然各有千秋,类似小工具的python效率极高,因为python封装了好多模块,直接调用模块就能完成大部分功能,模块其实就是提取出来的工具类。

例子:

  1. #发送post请求
  2. # !/usr/bin/python
  3. # -*- coding: utf-8 -*-
  4. import requests
  5. url = 'http://localhost:8083'
  6. body = '{"test":"test_value"}'
  7. header = {'Content-Type':'application/json','Host':'www.test.com','User-Agent':'Java/1.8.0'}
  8. response = requests.post(url=post_url,headers=header,json=body)
  9. print(response.status_code)
  1. #接受post请求
  2. # !/usr/bin/python
  3. # -*- coding: utf-8 -*-
  4. import json
  5. import uvicorn
  6. from fastapi import FastAPI, Body, Request
  7. from fastapi.middleware.cors import CORSMiddleware
  8. app = FastAPI()
  9. app.add_middleware(
  10. CORSMiddleware,
  11. allow_origins='*',
  12. allow_credentials=True,
  13. allow_methods=["GET", "POST"],
  14. allow_headers=["*"],
  15. )
  16. @app.post('/test')
  17. async def programInfo(request:Request):
  18. data = await request.body()
  19. print(json.loads(data)) # 转json格式
  20. if __name__ == '__main__':
  21. uvicorn.run(app=app,
  22. host="0.0.0.0",
  23. port=8083,
  24. workers=1)