python基础

num = 666
# 注释
"""
批量注释
"""
print("余额:", num)

print(type(num))


# 类型转换
ld = str(11)
print(type(ld))
num_ld = int("111")
print(type(num_ld))

"""
中文 英文 下划线 数字 数字不能开头
大小写敏感
关键字
"""

"""
常见7种运算符
+
-
*
/
// 取整
% 取余数
** 指数

复合运算
+=
"""


"""
字符串
可以\,或者单引号 双引号错开使用
"""
name1 = 'hello'
name2 = "hello2"
name3 = """hello3"""

"""
+ 只能用于字符串拼接 
错误:”hello“ + 111 
"""
tclass = "student"
count = 1111
message = "学生:%s, 人数:%s" % (tclass,count)
message = "学生:%s, 人数:%d" % (tclass,count)
# message = "学生:%s, 人数:%f" % (tclass,count)
print(message)

"""
精度控制
m 控制位数
n 小数点精度
%5.2f 
"""


#字符串快速格式化 f:format
print(f"学生{tclass},人数{count}")

"""
数据输入:
input 输入的收拾str
"""
# print("input your name:")
# my_name = input("...")
# print("name is :",my_name)


"""
判断
True 
False
"""

"""
if判断
"""
age = 17
if age > 18:
    print("old people")
elif age > 16:
    print("m people")
else:
    print("new people")


"""
循环语句
while 
for
continue
break
"""
i = 1
while i < 10 :
    print("l love u")
    i = i + 1

print("hello",end="")
print("world",end="")


print("hello \t world")

str_name = "i like fish"
for x in str_name:
    print(x)

for x in range(5):
    if x == 3:
        continue
    if x == 4:
        break
    print(x)
print(range(3,9))
print(range(3,9,2))

"""
函数:
参数
返回值
注释
函数嵌套
global 全局变量
"""
def my_len(data):
    scount = 0
    for x in data:
        scount+=1
    print(f"长度为{scount}")

test_len = "ssssss"
my_len(test_len)
print(f"无返回类型{my_len(test_len)}")

def add(x,y):
    """
    相加
    :param x:
    :param y:
    :return:
    """
    return x+y
print( add(3,5) )

# cc = 55
def pp():
    global cc
    cc = 100
    print(cc)

pp()
print(cc)


"""
数据容器 : list tuple str set dict
"""
#list
name_list = ["sss","aaaa","ccc",['c','rrr'],True]
print(name_list)
print(type(name_list))
print(name_list[0])
print(name_list[-1])
print(name_list.index("ccc"))
name_list[1] = "sda"
print(name_list)
name_list.insert(1,"ghgg")
print(name_list)
name_list.append("vvv")
print(name_list)
del  name_list[2]
print(name_list)
ps = name_list.pop(2)
print(name_list)
name_list.remove("vvv")
print(name_list)
# name_list.clear()
# print(name_list)
tc = name_list.count("sss")
print(tc)
print(len(name_list))

for x in name_list:
    print(x)
# tuple
tp = (1,2,'ccc')
print(tp)

t1 = ("hello")
print(type(t1))
t2 = ("hello",)
print(type(t2))
print(tp[1])
#str 不能修改
my_str = "111 hello str 11"
print(my_str[3])
print(my_str.index("o"))
new_str = my_str.replace("h","p")
print(new_str)
ss = my_str.split("l")
print(ss)
# 去除前后空格
ms = my_str.strip()
print(ms)
mk = my_str.strip("11")
print(mk)
# 序列切片
ss_list = [1,2,3,4,5,6]
print(ss_list[1:3])
print(ss_list[::-1])
# set集合
em = {"aa","bb","cc"}
print(type(em))
em.add("kk")
print(em)
em1 = {"aa","bb","cc","vvv"}
print(em1.difference(em))
print(em1.union(em))
for x in em:
    print(x)
# 字典 dict key:除字典任意数据 value:任意数据
my_dict = {"name":"zz","age":23}
print(my_dict)
nn = my_dict["name"]
print(nn)
my_dict["add"] = "bj"
print(my_dict)
my_dict.pop("add")
print(my_dict)

mk = my_dict.keys()
print(mk)

for key in my_dict:
    print(key)

print(sorted(my_dict))
print(sorted(my_dict,reverse=True ))

"""
函数高阶:
多返回值
关键字传参
缺省参数
不定长参数
"""
def test_re():
    return 1 ,2

xxc,xxy = test_re();
print(xxc)
print(xxy)

def text_xx(x,y = 10):
    print(x)
    print(y)
text_xx(y=4,x=6)
text_xx(5)

# 不定长 - 位置不定长 参数以元组形式存在
def user_info(*names):
    print(names)

nl = ['a','b']
user_info(nl)
user_info('a','b')
# 不定长 - 关键字不定长**
def user_info2(**kwargs):
    print(kwargs)
user_info2(name ="zz1",age = 1)

#函数作为参数 逻辑的传入
def test_fc(com):
    rs = com(1,3)
    print(rs)
def com(x,y):
    return x +y
test_fc(com)

test_fc(lambda x,y:x+y)


"""
文件的操作 r w a 
"""
# f = open("hello.txt","r",encoding="utf-8")
# print(type(f))
# i1 = f.read()
# print(i1)
# i2 = f.readlines()
# print(i2)
# for line in f :
#     print(line)
# f.close()

#自动关闭文件流
# with open("hello.txt","w",encoding="utf-8") as f:
#     # for line in f:
#     #     print(line)
#     f.write("ccccc")
#     f.flush()
#

with open("hello.txt","a",encoding="utf-8") as f:
    # for line in f:
    #     print(line)
    f.write("cccccccccccccssssssssss")
    f.flush()

"""
异常
捕获异常
异常传递
"""
try:
    3/0
except:
  print("error")


try:
    print(fsad)
except NameError as  e:
  print("error")
  print(e)


try:
    print("sss")
except NameError as  e:
  print("error")
  print(e)
else:
  print("sssvv")
finally:
  print("vvvv")

"""
模块导入
main
all

"""
#import time
# print(time.gmtime())
# from time import sleep
# sleep(5)
# from time import *
# sleep(5)
import my_module1 as mm
aa = mm.test(2,4)
print(aa)

"""
图形可视化
折线图
json
地图
:
1)cmd控制台输入:conda env list,查看自己的环境,base是系统环境,myenv是自己创建的环境,我要激活的是自己创建的环境
2)cmd控制台输入:conda activate+环境名称,之后再输入python即为激活成功
"""
from pyecharts.charts import Line
line = Line()
line.add_xaxis(["ch_z","us","uk"])
line.add_yaxis("GDP",[30,20,11])
#全局设置
#line.set_global_opts()
line.render()


from pyecharts.charts import Map
map = Map()
data = [
    ("北京",111),
    ("上海",3231),
    ("成都",444),
]
map.add("测试地图",data,"china")
map.render()

"""
类
成员变量和方法
构造方法 __init__
__str__
__eq__
私有成员变量 __avg__
继承,多继承:属性重复,以左边的类为主
重写
父类调用
类型注解:仅仅是备注,错了代码也能跑
多态
"""
class Student:
    name11 = None
    age11 = 23
    __avg__ = None
    def say_hi(self,mes):
        print(f"say :" ,{self.name11},mes)
    def __init__(self,name11,age11):
        self.name11 = name11;
        self.age11 = age11;
    def __str__(self):
        return f"student",self.name11,self.age11
    def __kk__(self):
        print("sss")



# st = Student()
# st.age11 = 21
# st.name11 = "zz1"
# st.say_hi("xxx")
# print(st.name11)
# print(st.age11)


st2 = Student("aa",44)
print(st2.name11)
print(st2.age11)
print(st2.__str__())

class StudentPro(Student):
    high = None
    def __init__(self,high):
        self.high = high;

sp = StudentPro(444)
sp.name11 = "ggg"
print(sp.high)


class Student66(Student):
    nfc = None
    def say(self,mes):
        super().say_hi(mes)
    def __init__(self):
      None

s6 = Student66()
print(s6.say("ddd"))


var_1: int = 10
var_2: int = 10  # type: int
# sttu :Student = Student()
my_list1 : list = [2,3,45,5]


def add_plu(x:int ,y:int) -> int:
    return x+y


class Animal:
    def speak(self):
        None
    pass


class Cat(Animal):
    def speak(self):
        print("miao miao~~~")
class Dog(Animal):
    def speak(self):
        print("wang wang @@@")


def make(an:Animal):
    an.speak()




cat = Cat()
dog = Dog()

# cat.speak()
# dog.speak()

make(dog)
make(cat)

"""
MYSQL
"""
from pymysql import Connection
conn = Connection(
    host = "localhost",
    port = 3306,
    user="root",
    password="123456",
    autocommit=True
)
print(conn.get_server_info())
cursor = conn.cursor()
conn.select_db("cloud_user")

# cursor.execute("select * from tb_user")
# rs = cursor.fetchall()
# print(rs)

cursor.execute("insert into tb_user values(8, '柳岩2', '湖南省衡阳市2')")

# cursor.execute("select * from tb_user")
# rs = cursor.fetchall()
# print(rs)

#conn.commit()



你可能感兴趣的:(数据结构,python)