https://www.runoob.com/python3/python3-tutorial.html 基础学习文字教程
安装
https://www.python.org/downloads/ 下载对应的安装包。
mac上自带python,不过是2.x版本的, 想要升级可以参考mac升级到3.x版本
使用python -V查看版本
编辑器
可选择VSCODE或者pyCharm。 如果是之前是做前端的建议用VSCODE, 如果之前是做后端的建议用pyCharm。另外还有一些其他的工具,例如python神器kite。
基础语法
print("Hello, World!");
#含有表达式的输出
print(3+1);
#数据输出到文件
fp = open('/Users/apple/code/python3/text.txt','a+')
print("hello world", file=fp)
fp.close()
#行与缩进, 不需要用{}了
if True:
print ("True")
else:
print ("False")
import 与 from...import
在 python 用 import 或者 from...import 来导入相应的模块。
将整个模块(somemodule)导入,格式为: import somemodule
从某个模块中导入某个函数,格式为: from somemodule import somefunction
从某个模块中导入多个函数,格式为: from somemodule import firstfunc, secondfunc, thirdfunc
将某个模块中的全部函数导入,格式为: from somemodule import *
基本数据类型
- Number(数字): int、float、bool、complex
- String(字符串)
- List(列表) append()、pop() 等函数
- Tuple(元组)不可修改的list
- Set(集合) 差-;并|;交& ;异或^
- Dictionary(字典):key-value
isinstance 用来判断是否是某个数据类型, isInt = isinstance(1, int)
函数 | 描述 |
---|---|
将x转换为一个整数 | |
将x转换到一个浮点数 | |
创建一个复数 | |
将对象 x 转换为字符串 | |
将对象 x 转换为表达式字符串 | |
用来计算在字符串中的有效Python表达式,并返回一个对象 | |
将序列 s 转换为一个元组 | |
将序列 s 转换为一个列表 | |
转换为可变集合 | |
创建一个字典。d 必须是一个 (key, value)元组序列。 | |
转换为不可变集合 | |
将一个整数转换为一个字符 | |
将一个字符转换为它的整数值 | |
将一个整数转换为一个十六进制字符串 | |
将一个整数转换为一个八进制字符串 |
运算符
运算符 | 描述 |
---|---|
** | 指数 (最高优先级) |
~ + - | 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@) |
* / % // | 乘,除,求余数和取整除 |
+ - | 加法减法 |
>> << | 右移,左移运算符 |
& | 位 'AND' |
^ | | 位运算符 |
<= < > >= | 比较运算符 |
== != | 等于运算符 |
= %= /= //= -= += *= **= | 赋值运算符 |
is is not | 身份运算符 |
in not in | 成员运算符 |
not and or | 逻辑运算符 |
流程控制
#!/usr/bin/python3
# 该实例演示了数字猜谜游戏
number = 7
guess = -1
print("数字猜谜游戏!")
while guess != number:
guess = int(input("请输入你猜的数字:"))
if guess == number:
print("恭喜,你猜对了!")
elif guess < number:
print("猜的数字小了...")
elif guess > number:
print("猜的数字大了...")
数据库连接
#如果未安装mysql库可以先执行以下命令
python -m pip install mysql-connector
import mysql.connector
mydb = mysql.connector.connect(
host="localhost", # 数据库主机地址
user="yourusername", # 数据库用户名
passwd="yourpassword" # 数据库密码
)
print(mydb)
#插入数据
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="123456",
database="runoob_db"
)
mycursor = mydb.cursor()
sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
val = [
('Google', 'https://www.google.com'),
('Github', 'https://www.github.com'),
('Taobao', 'https://www.taobao.com'),
('stackoverflow', 'https://www.stackoverflow.com/')
]
mycursor.executemany(sql, val)
mydb.commit() # 数据表内容有更新,必须使用到该语句
print(mycursor.rowcount, "记录插入成功。")
使用pyMysql
#安装
pip3 install PyMySQL
#!/usr/bin/python3
import pymysql
# 打开数据库连接
db = pymysql.connect(host="82.156.80.239",user="h5root",password="bdds@j2020",database="h5")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
print ("Database version : %s " % data)
# 关闭数据库连接
db.close()