基础语法快速学习下。
代码仓库:https://gitee.com/juncaoit/python-project
一:package
自带package和外部package
外部package以及管理系统介绍: 使用easy_install, pip进行下载
import os import requests if __name__ == '__main__': # 自带package a=os.getcwd() print(a) # 外部包 r = requests.get('https://api.github.com/events') print(r.encoding)
二:数据类型
1.说明
Python 中的变量赋值不需要类型声明。
每个变量在内存中创建,都包括变量的标识,名称和数据这些信息。
每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。
2.类型
Python有五个标准的数据类型:
- Numbers(数字)
- String(字符串)
- List(列表)
- Tuple(元组)
- Dictionary(字典)
三:数字
1.说明
Python支持四种不同的数字类型:
- int(有符号整型)
- long(长整型,也可以代表八进制和十六进制)
- float(浮点型)
- complex(复数)
2.程序
# 数字类型 if __name__ == '__main__': a = 3 b = 4 c = 5.66 d = 8.0 e = complex(c, d) f = complex(float(a), float(b)) print("a is type", type(a)) print("b is type", type(b)) print("c is type", type(c)) print("d is type", type(d)) print("e is type", type(e)) print("f is type", type(f)) print(a + b) print(d / c) print(b / a) # 1,整除 print(b // a) # (5.66+8j) print(e) # (8.66+12j) print(e + f) print("e's real part is: ", e.real) print("e's imaginary part is: ", e.imag)
四:字符串
1.说明
python的字串列表有2种取值顺序:
- 从左到右索引默认0开始的,最大范围是字符串长度少1
- 从右到左索引默认-1开始的,最大范围是字符串开头
2.程序
基本操作,输出
# 字符串类型的代码 if __name__ == '__main__': # 字符串的操作 strDEmo = 'Hello World!' print(strDEmo) # 输出完整字符串 print(strDEmo[0]) # 输出字符串中的第一个字符 print(strDEmo[2:5]) # 输出字符串中第三个至第六个之间的字符串 print(strDEmo[2:]) # 输出从第三个字符开始的字符串 print(strDEmo * 2) # 输出字符串两次 # 联合 print(strDEmo + "TEST") # 输出连接的字符串 # Format字符串 age = 3 name = "Tom" print("{0} was {1} years old".format(name, age)) # 中文 zn = "你好" print(zn)
五:列表
1.说明
# 列表程序 if __name__ == '__main__': # 创建一个列表 number_list = [1, 3, 5, 7, 9] string_list = ["abc", "bbc", "python"] mixed_list = ['python', 'java', 3, 12] # 访问列表中的值 second_num = number_list[1] third_string = string_list[2] fourth_mix = mixed_list[3] print("second_num: {0} third_string: {1} fourth_mix: {2}".format(second_num, third_string, fourth_mix)) # 更新列表 print("number_list before: " + str(number_list)) number_list[1] = 30 print("number_list after: " + str(number_list)) # 删除列表元素 print("mixed_list before delete: " + str(mixed_list)) del mixed_list[2] print("mixed_list after delete: " + str(mixed_list)) # Python脚本语言 print(len([1, 2, 3])) # 长度 print([1, 2, 3] + [4, 5, 6]) # 组合 print(['Hello'] * 4) # 重复 print(3 in [1, 2, 3]) # 某元素是否在列表中 # 列表的截取 # 字符串也存在 abcd_list = ['a', 'b', 'c', 'd'] print(abcd_list[1]) print(abcd_list[-2]) print(abcd_list[1:])
3.其他的方法
# 1、cmp(list1, list2):比较两个列表的元素# 2、len(list):列表元素个数# 3、max(list):返回列表元素最大值# 4、min(list):返回列表元素最小值# 5、list(seq):将元组转换为列表# 列表操作包含以下方法:# 1、list.append(obj):在列表末尾添加新的对象# 2、list.count(obj):统计某个元素在列表中出现的次数# 3、list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)# 4、list.index(obj):从列表中找出某个值第一个匹配项的索引位置# 5、list.insert(index, obj):将对象插入列表# 6、list.pop(obj=list[-1]):移除列表中的一个元素(默认最后一个元素),并且返回该元素的值# 7、list.remove(obj):移除列表中某个值的第一个匹配项# 8、list.reverse():反向列表中元素# 9、list.sort([func]):对原列表进行排序
六:元祖
1.说明
元组是另一个数据类型,类似于 List(列表)。
元组用 () 标识。内部元素用逗号隔开。但是元组不能二次赋值,相当于只读列表。
2.程序
# 元组测试 if __name__ == '__main__': # 创建只有一个元素的tuple,需要用逗号结尾消除歧义 a_tuple = (2,) # tuple中的list,可以进行修改 mixed_tuple = (1, 2, ['a', 'b']) print("mixed_tuple: " + str(mixed_tuple)) mixed_tuple[2][0] = 'c' mixed_tuple[2][1] = 'd' print("mixed_tuple: " + str(mixed_tuple)) # 多次赋值 v = ('a', 'b', 'e') (x, y, z) = v print(x)
七:字典
1.说明
字典(dictionary)是除列表以外python之中最灵活的内置数据结构类型。列表是有序的对象集合,字典是无序的对象集合。
两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
字典用"{ }"标识。字典由索引(key)和它对应的值value组成。
2.程序
# 字典类型 if __name__ == '__main__': # 创建一个词典 phone_book = {'Tom': 123, "Jerry": 456, 'Kim': 789} mixed_dict = {"Tom": 'boy', 11: 23.5} # 访问词典里的值 print("Tom's number is " + str(phone_book['Tom'])) print('Tom is a ' + mixed_dict['Tom']) # 修改词典 phone_book['Tom'] = 999 phone_book['Heath'] = 888 print("phone_book: " + str(phone_book)) # 如果没有,则新增 phone_book.update({'Ling': 159, 'Lili': 247}) print("updated phone_book: " + str(phone_book)) # 删除词典元素以及词典本身 del phone_book['Tom'] print("phone_book after deleting Tom: " + str(phone_book)) # 清空词典 phone_book.clear() print("after clear: " + str(phone_book)) # 删除词典 del phone_book # 不允许同一个键出现两次。展示的是后一个 rep_test = {'Name': 'aa', 'age': 5, 'Name': 'bb'} print("rep_test: " + str(rep_test))
八:函数
1.上程序
一些类型的函数下面有说明
# 没有参数和返回的函数 def say_hi(): print(" hi!") say_hi() say_hi() # 有参数,无返回值 def print_sum_two(a, b): c = a + b print(c) print_sum_two(3, 6) # 有参数,有返回值 def repeat_str(str, times): repeated_strs = str * times return repeated_strs repeated_strings = repeat_str("Happy Birthday!", 4) print(repeated_strings) #全局变量与局部 变量 x = 60 def foo(x): print("x is: " + str(x)) x = 3 print("change local x to " + str(x)) foo(x) print('x is still', str(x)) # 默认参数 def repeat_str(s, times=1): repeated_strs = s * times return repeated_strs repeated_strings = repeat_str("Happy Birthday!") print(repeated_strings) repeated_strings_2 = repeat_str("Happy Birthday!", 4) print(repeated_strings_2) # 关键字参数: 调用函数时,选择性的传入部分参数 def func(a, b=4, c=8): print('a is', a, 'and b is', b, 'and c is', c) func(13, 17) func(125, c=24) func(c=40, a=80) # VarArgs参数 def print_paras(fpara, *nums, **words): print("fpara: " + str(fpara)) # fpara: hello print("nums: " + str(nums)) # nums: (1, 3, 5, 7) print("words: " + str(words)) # words: {'word': 'python', 'anohter_word': 'java'} print_paras("hello", 1, 3, 5, 7, word="python", anohter_word="java")
九:控制语句
1.if控制语句
#if number = 59 guess = int(input('Enter an integer : ')) if guess == number: print('Bingo! you guessed it right.') print('(but you do not win any prizes!)') elif guess < number: print('No, the number is higher than that') else: print('No, the number is a lower than that') print('Done')
2.while用法
#while example number = 59 guess_flag = False while guess_flag == False: guess = int(input('Enter an integer : ')) if guess == number: guess_flag = True elif guess < number: print('No, the number is higher than that, keep guessing') else: print('No, the number is a lower than that, keep guessing') print('Bingo! you guessed it right.') print('Done')
3.for用法
#For number = 59 num_chances = 3 print("you have only 3 chances to guess") for i in range(1, num_chances + 1): print("chance " + str(i)) guess = int(input('Enter an integer : ')) if guess == number: print('Bingo! you guessed it right.') break elif guess < number: print('No, the number is higher than that, keep guessing, you have ' + str(num_chances - i) + ' chances left') else: print('No, the number is lower than that, keep guessing, you have ' + str(num_chances - i) + ' chances left') print('Done')
4.关键字brank,continue,pass
和java中的一样
十:文件操作
1.程序
## 用Python内置的open()函数打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写 import os some_sentences = '''\ I love learning python because python is fun and also easy to use ''' # 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。 fileName = 'sentences.txt' f = open(fileName, 'a+') f.write(some_sentences) f.close() # 读取 f = open('sentences.txt') while True: line = f.readline() if len(line) == 0: break print(line) # 刷新缓冲区里任何还没写入的信息 f.close() # 查找当前位置 fo = open("foo.txt", "r") position = fo.tell() print("当前文件位置 : ", position) # 把指针再次重新定位到文件开头 position = fo.seek(0, 0) str1 = fo.read(10) print("重新读取字符串 : ", str1) fo.close() #os模块提供了帮你执行文件处理操作的方法,比如重命名和删除文件 # os.rename("original.txt", "senten4444ces2.txt") # os.remove("original.txt") # 显示当前的工作目录 os.getcwd() # 创建目录test os.mkdir("test") # 删除目录 os.rmdir('test')
十一:面向对象[基本使用,继承等没有写]
1.程序
将对象进行定义
然后引用
_init_.py
class Employee: '所有员工的基类' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print("Total Employee %d" % Employee.empCount) def displayEmployee(self): print("Name : ", self.name, ", Salary: ", self.salary)
Test
from object import Employee if __name__ == '__main__': emp1 = Employee("Zara", 2000) emp1.displayEmployee() print("Total Employee %d" % Employee.empCount)
十一:mysql
1.说明
python可以进行连接库
感觉这篇文章不错:https://www.cjavapy.com/article/1157/
2.import
这个不是导入mysql_python之类的
pip install mysql-connector-python -i https://pypi.tuna.tsinghua.edu.cn/simple
3.程序
只有删除数据
插入数据
批量插入
import datetime import mysql.connector # 删除数据 def delete(id): # 删除数据 mydb = mysql.connector.connect( host="127.0.0.1", user="root", passwd="123456", database="center" ) sql = ' delete from firs where id=%s' idParam = (id, ) test = mydb.cursor() test.execute(sql, idParam) mydb.commit() mydb.close() # 插入数据 def insert(): mydb = mysql.connector.connect( host="127.0.0.1", user="root", passwd="123456", database="center" ) # 插入数据 insertSql = 'insert into firs(card_id,it_name,it_desc,gmt_create) values(%s, %s, %s, %s) ' insert_data = ('222', '333','5555', datetime.datetime.now()) mycursor = mydb.cursor() mycursor.execute(insertSql, insert_data) mydb.commit() print("1 record inserted, ID:", mycursor.lastrowid) mydb.close() # 批量插入 def batchInsert(): mydb = mysql.connector.connect( host="127.0.0.1", user="root", passwd="123456", database="center" ) # 插入数据 insertSql = 'insert into firs(card_id,it_name,it_desc,gmt_create) values(%s, %s, %s, %s) ' insert_data = [ ('222', '333', '5555', datetime.datetime.now()), ('333', '333', '5555', datetime.datetime.now()), ('444', '333', '5555', datetime.datetime.now()), ('555', '333', '5555', datetime.datetime.now()) ] mycursor = mydb.cursor() mycursor.executemany(insertSql, insert_data) mydb.commit() print(mycursor.rowcount, "was inserted.") mycursor .close() if __name__ == '__main__': # 删除数据 delete(1) # 插入数据 insert() # 批量插入 batchInsert()
效果:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器