01-引言
Python作为一种当下非常方便的工具类语言,深受大众喜爱,而我则是为了学习《深度学习》而开始学习Python的基础语法。
若是基础的语法都不能掌握,未来必将是一片混沌。由点及面,生活中很多事物都是这样,比如说,英语。
02-基础
(1)Print the content into the specified file
# 将数据输出到文件中
fp = open('D:/text.txt', 'a+')
print("hello word", file=fp)
fp.close()
(2)Variable
强制类型转换 cast type
内置函数有
- str()
- int()
- float()
# 解决浮点数相加减出现误差的问题
from decimal import Decimal
def _01_part():
name = 'gxx'
print('标识(内存地址)', id(name))
print('类型', type(name))
print('值', name)
def _02_part():
print(1.1 + 2.2)
print(Decimal('1.1') + Decimal('2.2'))
# 数据类型转换
def _03_part():
name = 'gxx'
age = 18
# string concatenate only str + str not str + int
print('my name is ' + name + ' ,' + str(age) + ' years old')
return
if __name__ == '__main__':
# _01_part()
# _02_part()
_03_part()
(3)程序的组织结构
①Sequential structure
②Selective structure
num = int(input('please input a number'))
if num & 1:
print('the number is a odd number')
else:
print('the number is a even number')
score = int(input('please input a score\n'))
if 90 <= score <= 100:
print('A')
elif 80 <= score <= 90:
print('B')
else:
print('N')
# condition expression
a = int(input())
b = int(input())
print('Yes' if a > b else 'No')
pass充当一个占位符的作用,在搭建代码的大致框架时使用
answer = 'y'
if answer == 'y':
pass # 在这种情况下,要....
else:
pass # 在这种情况下,要....
③Loop structure
这里要先介绍一个内置函数 range()
左闭右开
for i in range(10):
print(i)
for item in 'Python':
print(item)
03-常见数据结构
(1)列表
# 列表的创建
def construct_list():
# (1) 使用中括号
lst1 = ['hello', 'world', 98]
print(lst1)
# (2) 调用内置函数list
lst2 = list(['hello', 'world', 98])
print(lst2)
# 切片 list[start: stop: step] 左闭右开 python的下标从0开始
def section_list():
lst = [0, 1, 2, 3, 4, 5, 6]
section_lst = lst[1: 5: 1]
print(section_lst)
# append extend insert
def sort_list():
lst = [20, 40, 10, 98, 54]
lst.sort()
print(lst)
lst.sort(reverse=True)
# lst = sorted(lst, reverse=True)
print(lst)
# 列表生成式 用来生成一个列表
def list_expression():
lst = [i*i for i in range(1, 10)]
print(lst)
if __name__ == '__main__':
# construct_list()
# section_list()
# sort_list()
list_expression()
(2)字典
以键值对的形式存储数据
def construct_dict():
# 使用{}创建字典
scores = {'张三': 100, '李四': 98}
print(scores)
# 使用内置函数dict创建
scores = dict({'张三': 100, '李四': 98})
students = dict(name='gxx', age=18)
students['sds'] = 19
print(scores)
print(students)
def find_dict():
scores = {'张三': 100, '李四': 98}
for item in scores: # 依次取出每个 键
print(item, scores[item])
if __name__ == '__main__':
# construct_dict()
find_dict()
(3)元组
元组是不可变的序列
# 元组的创建
def construct_tuple():
# 使用()创建
t = (1, 2, 3)
# 使用内置函数创建
t = tuple((1, 2, 3, 4))
# 如果元组中只包含一个元组, 元素的最后面要加个 ,
t = (1, )
print(t, type(t))
def for_tuple():
t = (1, 2, 3)
for item in t:
print(item)
if __name__ == '__main__':
# construct_tuple()
for_tuple()
(4)集合
# 集合的创建
def construct_set():
# 使用{} 跟字典一样,
s = {1, 2, 3}
# 使用内置函数
s = set({1, 2, 3})
print(s)
s = set({'python', 'hello'})
print(s)
if __name__ == '__main__':
construct_set()
04-Python的异常处理机制
try:
a = int(input('请输入第一个整数'))
b = int(input('请输入第二个整数'))
rst = a / b
print('rst: ', rst)
except ZeroDivisionError:
print('ZeroDivisionError')
except ValueError:
print('ValueError')
print('program finish')
05-类
class Clock:
price = None # 这里的成员方法可省, 在构造方法中定义也可以
def __init__(self, price): # 构造方法
self.price = price
print("Clock类创建了一个Clock对象")
def ring(self):
import winsound
winsound.Beep(2000, 1000)
def __str__(self): # 打印对象方法 类似 toString
return f"Clock类对象,price = {self.price}"
def __lt__(self, other):
return self.price < other.price
def __le__(self, other):
return self.price <= other.price
def __eq__(self, other):
return self.price == other.price
if __name__ == '__main__':
clock1 = Clock(19)
clock2 = Clock(29)
# clock1.ring()
print(clock1)
print(clock1 < clock2)
lst = []
lst.append(clock2)
lst.append(clock1)
print(lst[0].price)
lst.sort()
print(lst[0].price)
class Student:
name = None # 成员对象
age = None
def say_hi(self): # 成员方法
print(f'Hi 大家好, 我是{self.name}')
def say_hi_2(self, msg):
print(f'Hi 大家好, 我是{self.name}', msg)
if __name__ == '__main__':
student = Student()
student.name = "周杰伦"
student.say_hi_2('诶呦不错呦')
stu = Student()
stu.say_hi()