Python基础简介

这篇博客主要介绍了Python编程的基础知识,包括语法特性、常用库的使用以及面向对象编程的概念。适合初学者快速掌握Python编程入门技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# 什么是变量
a = 123 #a是整数
print(a)
print(type(a))
a = 'ABC' #a是字符串
print(a)
print(type(a))

# 什么是算术计算
a = 10
a += 1
print("a += 1", a)
a -= 1
print("a -= 1", a)
a *= 10
print("a *= 10", a)
a /= 3
print("a /= 3", a)
a //= 3
print("a //= 3", a)
a %= 3
print("a %= 3", a)
a **= 2
print("a **= 2", a)

# 字符串是什么
str_1 = 'day1'
print('str_1 = ', str_1)
str_2 = 'day2'
print('str_2 = ', str_2)
str_3 = '''day1,
day2
day3'''
print('str_3 = ', str_3)
str_4 = """
day1
day2
day3
day4
"""
print('str_4 = ',str_4)

case1_1 = 'day1, day2,day3'
case1_2 = 'day1,\n day2,\n day3'
case1_3 = r'day1, \n day2,\n day3'
print('case1_1 = ', case1_1)
print('case1_2 = ', case1_2)
print('case1_3 = ', case1_3)

case2_1 = 'day1'
case2_2 = 'day2'
case2_3 = case2_1 + case2_2
case2_4 = case2_1*5
print('case2_3 = ', case2_3)
print('case2_4 = ', case2_4)

case3 = 'abcde'
print('case3 = ', case3)
print('case3[0] = ', case3[0])
print('case3[-1] =', case3[-1])
print('case3[1:] =', case3[1:])
print('case3[: -2] =', case3[: -2])
print('case3[1: 3] = ', case3[1: 3])
print('case3[-4: -2] = ',case3[-4: -2])

# 列表
list = [1, '2', '中文', False, [1, 2]]
print(list)
print(list[0])
print(list[-1])
print(list[: 2])
print(list[-3:])

# 爸爸说晚上有2个四川朋友来家里吃饭, 让妈妈准备菜单
menu = ['水煮鱼', '麻婆豆腐', '辣子鸡', '蒜蓉油麦菜']
print('原始菜单:', menu)
#爸爸点名要加个汤:西红柿蛋花汤
menu.append('西红柿蛋花汤')
print('修改菜单1:', menu)
# 爸爸说又要来2个朋友一起,让妈妈多加几个菜
menu_old = ['回锅肉', '干煸豆角']
menu.extend(menu_old)
print('修改菜单2', menu)
# 爸爸问妈妈菜单里有小炒黄牛肉吗?有个朋友是湖南的,妈妈说没有
print('菜单里有小炒黄牛肉吗?','小炒黄牛肉' in menu)
#爸爸说那把回锅肉换成小炒黄牛肉吧
menu.remove('回锅肉')
menu.insert(5,'小炒黄牛肉')
print('把回锅肉换成小炒黄牛肉', menu)
#爸爸问我总炒了几个菜
print('总共有', len(menu),'个菜')

#字典
#妈妈去超市买菜的清单 物品:价格
reciept = {'豆腐': 2, '鸡块': 20, '油麦菜': 2, '西红柿': 4, '牛肉': 30, '豆角': 5}
print('原始清单:', reciept)
#查询是否买了草鱼
print('是否买了草鱼', '草鱼' in reciept)
# 增加草鱼:20
reciept['草鱼'] = 20
print('修改菜单1:', reciept)
# 鸡块价格记错了,不是20,是30
reciept['鸡块'] = 30
print('修改菜单2:', reciept)
#查看所有菜名
print('所有菜名:',reciept.keys())
#求价格总和
print('所有菜单:', sum(reciept.values()))

# 集合
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3_1 = set1 & set2
print('交集', set3_1)
set3_2 = set1.intersection(set2)
print('交集', set3_2)
set4_1 = set1 | set2
print('并集', set4_1)
set4_2 = set1.union(set2)
print('并集',set4_2)
set5_1 = set1 - set2
print('差集', set5_1)
set5_2 = set1.difference(set2)
print('差集',set5_2)
set6_1 = set1 ^ set2
print('对称差集', set6_1)
set6_2 = set1.symmetric_difference(set2)
print('对称差集', set6_2)

# 注释
# Hello are the coments
'''
this is a multiline comment
    used in Python
'''
#This is a multiline comment
#used in Python

# 条件判断语句
today = 5
if today == 1:
    print("周一")
elif today == 2:
    print("周二")
elif today == 3:
    print("周三")
else:
    print("周一周二周三之外的一天")

#循环语句
#break是跳出循环结束, continue跳到循环开始
for i in range(10):
    if i == 5:
        break
    print(i)

start_num = 0
while start_num != 10:
    start_num += 1
    if start_num % 2 == 0:
        continue    #跳过偶数
    print(start_num)

# 函数
# 计算面积函数
def area(width, height):
    return width * height
w = 4
h = 5
print("width =", w, " \nheight = ", h, " \narea = ", area(w, h))



a = 5
b = 7
def max (a, b):
    if a > b:
        return a
    else:
        return b

# 对象
a = 7
b = a
a = a + 3
print(a, id(a))
print(b, id(b))

a = [7]
b = a 
print(a, id(a))
a[0] += 3
print(a, id(a))
print(b, id(b))

# 类
class MyClass:
    """一个简单的类实例"""
    i = 12345
    def f(self):
        return 'hello world'

# 实例化类
x = MyClass()

# 访问类的属性和方法
print("MyClass 类的属性 i为:", x.i)
print("MyClass 类的方法 f输出为:", x.f())

# 类定义
class people:
    # 定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a 
        self.__weight = w
    def speak(self):
        print("%s 说:我%d岁。" %(self.name,self.age))
    
    #单继承实例
class student(people):
    grade = ''
    def __init__(self,n,a,w,g):
        #调用父类的构函
        people.__init__(self,n,a,w)
        self.grade = g
    # 覆写父类的方法
    def speak(self):
        print("%s 说:我 %d 岁了,在读 %d年级"%(self.name,self.age,self.grade))
    
s = student('ken',10,60,3)
s.speak()
# python由缩进来构成结构框架

# 创建数组
# numpy的几个属性
# 导入numpy,为了简便,采用np简写
import numpy as np

# 例子1:列表转化为矩阵
a = np.array([[1, 2, 3], [2, 3, 4]])
print(a)
print('number of dim:', a.ndim) # 维数
print('shape:', a.shape)    # 行数和列数
print('size:', a.size)  # 元素个数
print('dtype:', a.dtype)    # 数据类型
 
#例子2:创建全0矩阵
a = np.zeros((2, 3))
print(a)

#例子3:创建全1矩阵
a = np.ones((2, 3))
print(a)

#例子4:创建全空数组,其实每个值都是接近于零的数
a = np.empty((3, 3))
print(a)

# 例子5:创建连续数组
a = np.arange(1, 10, 2) # 0 - 9 的数据,2步长
print(a)

# 例子6:创建线段数据
a = np.linspace(1,10,10) # 开始端1, 结束端10,分割成10个数据
print(a)

# 基础运算
import numpy as np

x = np.array([[1,2],[3,4]], dtype = np.float64)
y = np.array([[5,6],[7,8]], dtype = np.float64)

print(x + y)
print(np.add(x, y))
print(x - y)
print(np.subtract(x, y))
print(x * y)
print(np.multiply(x, y))
print(x / y)
print(np.divide(x, y))
print(np.sqrt(x))
print(np.sqrt(y))

# 常见操作

# 修改数组形状
a = np.arange(8)
b = a.reshape(4, 2)
print(b)

# 翻转数组
a = np.arange(8).reshape(4,2)
b = np.transpose(a)
print(b)

# 修改数组维度
a = np.arange(8).reshape(4,2)
b = np.squeeze(a)
print(b)

# 连接多个数组
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[4,2]])
c = np.concatenate((a,b))
print(c)

# 分割数组
a = np.arange(8).reshape(4,2)
b = np.split(a,2)
print(b)


# 使用import导入matplotlib.pyplot模块,并简写成plt,使用plt.figure创建一个图像窗口
import matplotlib.pyplot as plt

plt.figure()
#使用plt.subplot来创建小图.plt.subplot(2,2,1)表示将整个图像窗口分为2行2列,当前位置为1
plt.subplot(2,2,1)
#使用plt.plot([0,1],[0,1])在第1个位置创建一个小图
plt.plot([0,1],[0,1])
plt.subplot(2,2,2)
plt.plot([0,1],[0,2])
plt.subplot(223)
plt.plot([0,1],[0,3])
plt.subplot(224)
plt.plot([0,1],[0,4])
plt.show() #展示




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值