Python学习(一)基础语法

1. 入门

1.1 解释器的作用

Python解释器作用:运行文件。
Python解释器类型:

  • CPython:官方开发的C语言解释器
  • IPython:基于CPython的一种交互式解释器
  • PyPy:基于Python开发的解释器
  • Jytion:运行在Java平台的解释器,直接把Python代码解析为Java字节码执行
  • IronPython:运行在.Net平台的解释器,将Python代码编译为.Net字节码

1.2 下载

官网:https://www.python.org/
注意Add Path。
验证:打开cmd,运行python.

(venv) F:\myStudySpace\pythonStudy\spider\web_crawler>python
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

1.3 基础语法

输入输出语法与引号

print()
print('')
print('''多行''')
print("")
print("""多行输出""")
print(123)
inputTxt = input("plese input:")
print(inputTxt)

注释:

# 单行注释
"""
多行注释
"""
'''
多行注释
'''

变量:

变量是一个存储数据的时候,当前数据所在内存地址的名字。
变量名 = 值
变量名规则:字母、下划线和数字组成。不能以数字开头

数据类型与四则运算

数据类型

  • 字符串,拼接用+号
    print('hello')
  • 整型
    print(99)
  • 浮点型
    print(3.14)
  • list列表:[]
    • 下标从0开始
    • 切片语法:[起始:结束:步长]。左闭右开区间取值
name = "abcdef"
print(name[0])
# 取到结束
print(name[:])
# 取到结束
print(name[0:])
# 取到结束前一个
print(name[0:len(name)-1])
print(name[:len(name)-1])
print(name[:len(name):2])
"""
a
abcdef
abcdef
abcde
abcde
ace
"""
list_2 = ['a','b','c','d','e','f']
print(list_2[5])
print(list_2[0:len(list_2)-2:2])
## 反转
print(list_2.reverse())
del list_2[2]
print(list_2)
# 删除列表最后一个元素
list_2.pop()
print(list_2)
# 增加元素
list_2.append("6666")
print(list_2)
"""
f
['a', 'c']
None
['f', 'e', 'c', 'b', 'a']
['f', 'e', 'c', 'b']
['f', 'e', 'c', 'b', '6666']
"""
  • dic字典(对应map):{}
xixi = {'name':'xixi',"age":18,'height':166.6}
print("正常的字典值:",xixi)
print(xixi['name'])
print(xixi.get('name'))
xixi["addr"] = "浙江"
print("增加后",xixi)
xixi["addr"] = "上海"
print("修改后",xixi)
del xixi["addr"]
print("删除后",xixi)

四则运算

加、减、乘*、除/、取模%、幂**

数据类型的查看type()

## 数据类型
str_1 = "123"
print(type(str_1))
str_2 = 123
print(type(str_2))
str_3 = 123.123
print(type(str_3))
list_1 = [1,2,3]
print(type(list_1))
# json
json_1 = {"name":"Huathy","age":18}
print(type(json_1))
# <class 'str'>
# <class 'int'>
# <class 'float'>
# <class 'list'>
# <class 'dict'>

数据类型的转换int()int()float()

在这里插入图片描述

流程控制

  • 单项判断:if
  • 双向判断:if…else…
  • 多向判断:if…elif…else…
  • if嵌套
# 单项判断:if
a = 0
if a==0:
    print('1')
# 双向判断:if...else...
if a==0:
    print('1')
else: print(2)
# 多向判断:if...elif...else...
if a==1:
    print('1')
elif a == 0:
    print(2)
else:
    print(3)
# if嵌套
score = 60
if score >= 60:
    print("及格")
    if(score>=80):print("优秀")
    else:print("还需努力")
else:
    print("不及格")

格式化输出

name = 'xixi'
age = 18
height = 166.6
print("name is: %s,age is %d ,height: %1f" % (name, age, height))
print("name is: {},age is {} ,height: {}".format(name, age, height))

循环与遍历

逻辑运算符

  • and:a and b。类比Java的&&
  • or:a or y。类比Java的||
  • not:not x。类比Java的!

list遍历

# range()函数 默认从0开始
for i in range(5):
    print(i)
#
print("===================")
# range 指定从一开始(左闭右开)
for i in range(1,5):
    print(i)

list_1 = ['xiix1','xi2','xi3','xi4']
# for in
for name in list_1:
    print(name)
print("while =============")
# while
i=0
while i < len(list_1):
    print(list_1[i])
    i += 1

字典dict遍历

dict_name = {'name':'xixi','age':18,'height':166.6}
for key in dict_name: print('key',key)
print("=================================")
for val in dict_name.values():print('val',val)
print("=================================")
for key,val in dict_name.items():print(key,'--',val)

跳出循环

  • break
  • continue
print('break')
name = 'python'
for x in name:
    if(x == 'h'):break;
    print(x)
print('continue')
for x in name:
    if (x == 'h'): continue;
    print(x)

面向对象OOP(封装、继承、多态)

封装:函数、全局变量与局部变量

"""
函数代码块以def开头,接标识符名称和(形参)
"""
def add(x,y):
    print(x,y)
    return x+y

print(add(1,2))
def none_fun():return
print(none_fun())

# 全局变量
a = 10
def inner():
    # 内部变量
    b = 20
    print(a)
    print(b)
inner()
# gloabl 修饰词:使用global对变量进行修饰,告诉计算机该变量变成全局变量在任何地方都起作用。类似js的var

def func():
    global a
    print('func a1', a)
    a = 200
    print('func a2',a)
func()

print(a)

函数的嵌套

"""
函数的嵌套:一个函数调用了另一个函数
"""
def test1():
    print('test 1 run')
def test2():
    print('test 2 run')
    test1()
test2()

class:万物皆对象

构成:类名、属性(一组数据)、方法(函数)

创建与调用:class name

# 创建
class Musician:
    loveMusic = True

    def sing(self):
        print('我在唱歌')
# 调用
clazz = Musician()
clazz.sing()

创建的俩个要素:

  • self参数:
    • self的作用:会在类的实例化中接受传入的数据,在代码中运行
    • 类方法中调用内部属性或者其他方法时,需要使用self来代表实例
    • self属性智慧在方法创建的时候出现,方法调用时就不需要出现
  • 初始化方法(构造函数):
    • 定义初始化方法:def __init__(self),init两边都是下划线
    • __init__()方法,在创建一个对象的时候被默认调用,不需要手动调用
    • 初始化方法中,除了可以设置固定值外,还可以设置其他参数
class Hero:
    def __init__(self,name,hp,atk,aro):
        # 类方法,用来做变量初始化赋值操作,在实例化的时候会被自动调用
        self.name = name
        self.hp = hp
        self.atk = atk
        self.aro = aro
    def move(self):
        print(self.name,'移动...')
    def attack(self):
        print(self.name,'攻击...')
        print('生命',self.hp)

hero = Hero('xixi',10000,50,20)
print(hero)
hero.move()
hero.attack()

类的继承

class Hero:
    def __init__(self,name,hp,atk,aro):
        # 类方法,用来做变量初始化赋值操作,在实例化的时候会被自动调用
        self.name = name
        self.hp = hp
        self.atk = atk
        self.aro = aro
    def move(self):
        print(self.name,'移动...')
    def attack(self):
        print(self.name,'攻击...')
        print('生命',self.hp)
"""
超级英雄继承英雄类
"""
class SuperHero(Hero):
    pass
superHero = SuperHero('超级英雄',1000000,5000,2000)
superHero.move()

多重继承与多层继承

class human:
    def humanSay(self):
        print('我是人类')
class woman(human):
    def humanSay(self):
        print('我是女人')
    def womanSay(self):
        print('女人')
class man(human):
    def humanSay(self):
        print('我是男人')
    def manSay(self):
        print('男人')
class p1(man,woman):
    pass
p1 = p1()
p1.manSay()
p1.womanSay()   
p1.humanSay()   # 重名的函数会覆盖(重写)父类的方法,先继承的覆盖后面的

文件IO

"""
open()
r :只读
w :写入
a :追加。存在追加,不存在则创建
rb :二进制打开用于只读
wb :二进制打开用于写入
ab :二进制打开用于追加
r+ :打开文件用于读写。文件指针在文件开头
w+ :打开文件用于读写。文件存在,则覆盖。否则新建
a+ :打开文件用于读写。文件存在,指针在尾。否则新建。
rb+ :以二进制打开文件用于读写。文件指针在头。
wb+ :以二进制打开文件用于读写。文件存在,则会覆盖。否则新建。
ab+ :以二进制打开文件用于追加。文件存在,指针在尾。否则新建。
"""
# open 读入
file = open('test.txt','r')
print(file)
# content = file.read()
# print('read',content)
line = file.readline()
line2 = file.readlines()
print('readline',line)
print('readlines',line2)
file.close()

# write 写出
newfile = open('newtest.txt','w')
newfile.write(line)
newfile.close()

print("=" * 30)
# with 自动关闭
with open('test.txt','r') as file:
    data = file.read()
    print(data)

import语句

  • func.py文件
def add(a,b):
    return a+b
from hello.helloEnd import func

res = func.add(1,2)
print(res)

time函数

import time
start_time = time.time()
print(start_time)
local_time = time.localtime()
print(local_time)
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))

csv模块读写

读取

import csv
with open('test.csv','r') as file:
    reader = csv.reader(file)
    print(reader)
    for content in reader:
        print(content)

写出

with open('test.csv','a') as file2:
    writer = csv.writer(file2)
    writer.writerow(['xixi2',22,'boy'])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Huathy-雨落江南,浮生若梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值