Python基础 小白入门笔记

笔记来源

Day-1

基础知识(注释、输入、输出、循环、数据类型、随机数)

#-*- codeing = utf-8 -*-
#@Time : 2020/7/11 11:38
#@Author : HUGBOY
#@File : hello1.py
#@Software: PyCharm

print("hello word !")
#注释
'''
注释多行注释
'''
'''
===输入===
#格式化输出
a = 100
print("变量",a)
age = 18
print("我有%d个女朋友"%age)
print("my name is : %s,and natinal:%s"%("HUGBOY","CHINA"))
print("ndnd","kdghkds","akgh")
#用点连接
print("www","baidu","com",sep=".")
#不自动换行

print("hello",end = "")
print("hello",end = "\t")
print("hello",end = "\n")
print("hello")
'''
'''
#输入
password = input("请输入您的QQ密码:")
print("你的QQ密码是:",password)

a = input("The number a:")
print(type(a))
print("a value is: %s"%a)#input赋值的变量默认以字符串打印出来



#强制转换类型
b = input("类型转化:")
b = int(b)
#b = int(input("整形:"))
print(type(b))
sum = b + 521
print("The sum value is:%d"%sum)
'''
'''
#if else判断语句
if True:
    print("This ture")
else:
    print("False")

if 0:
    print("This false")
else:
    print("Wow is true")
print("end")
'''
'''
score = int(input("你的分数:"))
if score >= 90 and score <= 100:
    print("score = %d成绩等级为:A"%score)
elif score >=80 and score < 90:
    print("成绩等级为 B")
elif score >=70 and score < 80:
    print("成绩等级为 C")
elif score >=60 and score < 70:
    print("成绩等级为 D")
elif score > 100:
    print("Your input number id EORR !")
else:
    print("score = %d 不及格 !"%score)
'''
'''
sex = 1 # man
girlfd = 1 # no girlfriend

if sex ==  1:
    print("你是小哥哥")
    if girlfd == 1:
        print("你个单身狗哈哈")
    else:
        print("甜蜜")
else:
    print("你是小姐姐")
    print("hello !!!")
'''

'''
#引入随机库
import random
x = random.randint(1,9)
print(x)
'''


#课堂练习   剪刀石头布游戏
import random

print("游戏规则 0代表石头、1代表剪刀、2代表布")
a = int(input("请出拳:"))
if a>2 or a<0 :
    print("出拳错误!")
    exit(0)
b = random.randint(0,2)
if a == b :
    print("平局")
elif(b - a) == 1 or (b - a) == -2:
    print("恭喜你获胜啦")
else:
    print("很遗憾,你失败了")

print("我方 %d"%a)
print("对方 %d"%b)

Day-2

基础知识(循环、列表)

#-*- codeing = utf-8 -*-
#@Time : 2020/7/11 15:28
#@Author : HUGBOY
#@File : hello2.py
#@Software: PyCharm

#for 循环
for i in range(10):
    print(i)
print("----------------")
#每次增3
for v in range(0,13,3):
    print(v)

for v in range(-10,-120,-20):
    print(v)

#对字符串
name = "zhaolin"
for i in name:
    print(i)
#列表
a = ["you","me","he"]
for i in range(len(a)):
    print(i,a[i])

#while循环
i = 0
while i<100:
    print("Now is the %d times to run !"%(i+1))
    print("i = %d"%i)
    i+=1
#0~100求和
sum = 0
n = 0
while n<=100:
    sum = sum + n
    n+=1
print("sum = %d"%sum)
#while 和 else 混用
i = 0
while i<20:
    print("i 还小 小于10")
    i+=1
else:
    print("i 很大 大于10")
#pass
a = 'blood'
for i in a:
    if i == 'o':
        pass
        print("It is o,pass")
    print(i)
#break continue
c = 0
while c <= 12:
    c +=1
    if c == 6:
        print("-"*60)
        print("The number is the half of 12,end!!!")
        break#continue
    else:
        print("The nb is :%d"%c)
#课堂作业  九九乘法表
m = 0
while m <= 9:
    m+=1
    n=1
    while n <= m:
            print("%d * %d = %d"%(m,n,m*n),end=' ')
            n += 1
    else:
        print("")
        continue




Day-3

基础知识(字符串、转译、列表截取/切片、列表-增-删-查-改-、排序、嵌套)

#-*- codeing = utf-8 -*-
#@Time : 2020/7/11 18:52
#@Author : HUGBOY
#@File : hello3.py
#@Software: PyCharm
#alt shift f10

#字符串

word = 'CHINA'
sentence = "a national"
paragraph ="""
line1  which is my only love
line2 ........
line3 .......
"""
print(word)
print(sentence)
print(paragraph)

#转译
my1 = "I'm a student"
my2 = 'I\'m a student'
my3 ="she said :\"hhhhh\""
my4 = 'he had said "123"'
print(my1)
print(my2)
print(my3)
print(my4)

#截取
str = "hugboy"
print(str)
print(str[0])
print(str[0:5])

print(str[0:6:3])#步进值3
print(str[:3])
print(str[3:])

print("hello\nhugboy")
print(r"hello\nhugboy")#注释掉转译
print(("hello  " + str +  " !")*3)

#列表
list = ['123','abc','爬虫','iioi']
print(list)
print(list[0])
print(list[3])

print(type(list[0]))

alist = [123,'test']
print(type(alist[0]))

print('-'*30)
#list遍历

for i in list:
    print(i)

n = 0
k = len(list)
while n<k:
    print(n)
    print(list[n])
    n+=1

#增删改查

namelist = ["张三","李四","李华","小明"]
print(namelist)
#增
'''
#(追加 append)
new = input("请输入添加学生姓名:")
namelist.append(new)#末尾追加
print(namelist)

a = [1,2,3]
b = ['a','b','c']
print(a)
a.append(b)
print(a)

#(插入 insert)
a = [8,5,7]
print(a)
a.insert(1,99)
print(a)

#删
#(del)下标
movie = ["《你的名字》","《美丽人生》","《叶问》","《星际大战》"]
print(movie)
del movie[2]
print(movie)

#(pop)弹出末尾
movie.pop()
print(movie)

#(remove)
movie.remove("《你的名字》")
print(movie)

movie.append("《美丽人生》")
movie.remove("《美丽人生》")#元素重复时删除第一个
print(movie)

#改
namels = ["李一","王唯","李白","唐虎","李清照"]
print(namels)
namels[0] = "李四"
print(namels)

#查
#[in/not in]
findstu = input("Please input the name you want find:")
if findstu in namels:
    print("找到啦")
else:
    print(type(findstu))
    print("同学 %s 不存在!"%findstu)
    
#(查索引)
a = ["a","c","d","e","d"]
print(a.index("c",0,3))#"c"是否存在于列表的 [0,3) 范围中
#print(a.index("v",0,2)

print("计数 'd' 出现的次数")
print(a.count("d"))
'''
'''
#排序
#(reverse)
nber = [1,7,3,2,5,9,4]
print("倒着输出")
nber.reverse()
print(nber)
#sort
print("sort升序")
nber.sort()
print(nber)
print("降序")
nber.sort(reverse = True)
#nber.reverse()

#嵌套
print("定义三个空列表")
school = [[],[],[]]
school = [["清华大学","北京大学"],["南阳理工","南阳师范"],["西北农业大学","兰州大学"]]
print(school[0][1])
print(nber)

'''

'''
#练习 三个老师随机分到三个办公室
import random
office = [[ ],[ ],[ ]]
teacher = ["tech-1","tech-2","tech-3","tech-4","tech-5","tech-6"]
for tech in teacher:
    id = random.randint(0,2)
    office[id].append(tech)
print(office)

i = 1
for offic in office:
    print("办公室%d中人数为:%d"%(i,len(offic)))
    i+=1
    print("具体老师:")
    for tech in offic:
        print("%s"%tech,end = "\t")
    print(end = "\n")
    print("-"*60)
'''

#课堂作业  购物
products = [["iphone",7999],["MacPro",14999],["Coffee",29],["Book",699],["Nike",199]]
goodscar = []
print("--------商品列表--------")
num = 0
for i in products:
    print("%d %s   %d"%(num,i[0],i[1]))
    num+=1
pay = 0
flag = 'n'
while flag != 'q':
    id = int(input("选择商品编号,加入购物车:"))
    if id == 0:
        goodscar.append(products[0])
        pay = pay + products[0][1]
    elif id == 1:
        goodscar.append(products[1])
        pay = pay + products[1][1]
    elif id == 2:
        goodscar.append(products[2])
        pay = pay + products[2][1]
    elif id == 3:
        goodscar.append(products[3])
        pay = pay + products[3][1]
    elif id == 4:
        goodscar.append(products[4])
        pay = pay + products[4][1]
    flag = input("按任意键继续添加,按q退出:")
print("--------购物车列表--------")
num = 0
for i in goodscar:
    print("%d %s   %d"%(num,i[0],i[1]))
    num+=1
print("------------------------")
print("总计¥:%d"%pay)

Day-4

基础知识(元组-及其增删查改、字典-及其增删查改、集合、枚举)

#-*- codeing = utf-8 -*-
#@Time : 2020/7/12 11:59
#@Author : HUGBOY
#@File : hello4.py
#@Software: PyCharm
'''
#元组
tup1 = (5)
print(type(tup1))
print("只有一个元素时要加逗号")
tup2 = (5,)
print(type(tup2))
tup3 = (5,2,1)
print(type(tup3))

tup = ("Apple","bra",20,60,85,100)
print(tup)
print(tup[0])
print("The last one is:")
print(tup[-1])
print("[ , ) 左闭右开")
print(tup[2:5])

#增删查改
temp1 = ('a','b','c',1,2,3)
temp2 = (7,8,9)
#add
print("其实是两个元组的连接")
temp = temp1 + temp2
print(temp)
#delete
print("删除整个元组")
print(temp1)
del temp1
#print(temp1)
#find
if 9 in temp2:
    print("yes")
else:
    print("no")
#edi
#temp[3] = 10 #报错--元组不可以修改
'''

#字典
print("字典就是 键-值 对")
info = {"name":"李沁","age":"17","work":"actor"}
#(键访问)
print(info["name"])
print(info["age"])
print(info["work"])
print("当访问键不存在,报错")
#print(info["home"])

#(get访问)
print("当访问键不存在,返回默认值")
print(info.get("home","No Value !"))

#增
#id = input("请输入演员编号:")
id = 123
info["ID"] = id
print(info)

#删
#(del)
print("del  删除了整个键值对")
print(info)
del info["ID"]
print(info)
print("删除字典")
# del info
# print(info)报错

#(clear)
print(info)
info.clear()
print(info)

#改
gil = {"name":"胡可小小","age":"19","where":"doyin","like":"beautful"}
print(gil)
print(gil["name"])
gil["name"] = "小小"
print(gil["name"])
print(gil)

#查
#(key)
print(gil.keys())
#(value)
print(gil.values())
#(一项 key-value)
print(gil.items())

#遍历
for key in gil.keys():
    print(key)

for value in gil.values():
    print(value)

for item in gil.items():
    print(item)

for key,value in gil.items():
    print("key = %s,value = %s"%(key,value))

#列表(枚举函数)
mylist = ["a","b","c",1,2,3]
for i in mylist:
    print(i)
print("想拿到列表元素的下标")
for a,b in enumerate(mylist):
    print(a,b)


#集合(可以去重)
print("集合中的元素不可重复")
s = set([1,2,3,3,6,7,8,8,8,])
print(s)

Day-5

函数

#-*- codeing = utf-8 -*-
#@Time : 2020/7/12 13:45
#@Author : HUGBOY
#@File : hello5_func.py
#@Software: PyCharm

#函数

def display():
    print("*"*30)
    print("  若飞天上去,定做月边星。 ")
    print("             --《咏萤火》")
    print("*" *30)
display()

#(含参)
def add(x,y):
    c = x + y
    print(c)

add(20,30)

def add2(x,y):
    c = x + y
    return c
print(add2(100,20))

#(多个返回值)
def div(a,b):
    sh = a//b
    yu = a%b
    return sh,yu
s,y = div(9,2)
print("商:%d 余数:%d"%(s,y))

#课堂练习
#1
def show():
    print("-"*60)
show()
#2
def showpp(m):
    i = 0
    while i < m:
        show()
        i+=1
    print("%d 条直线打印完毕!"%m)

#n = int(input("打印几条直线?:"))
n = 5
showpp(n)
#3
def addthree(x,y,z):
    sum = x+y+z
    return sum
s = addthree(1,2,3)
print("求和结果:%d"%s)
#4
def mean(a,b,c):
    sum = addthree(a,b,c)
    rel = sum // 3
    return rel
m = mean(7,8,9)
print("求平均值结果:%d"%m)


#全局变量&局部变量

Day-6

文件操作

#-*- codeing = utf-8 -*-
#@Time : 2020/7/12 15:20
#@Author : HUGBOY
#@File : hello6_file.py
#@Software: PyCharm

#文件
#(写)
f = open("test.txt","w")

f.write("Write succese,this is only a test ! \n")
f.write("Do you know a say that:\n'人生苦短,我选Python'\nHahaha......")

f.close()

#(读)
print("指针方式读取,按字符逐个读取")
f = open("test.txt","r")

content = f.read(10)

print(content)

content = f.read(20)

print(content)

f.close()

print("按行读取")
f = open("test.txt","r")

content = f.readline()
print(content)
content = f.readline()
print(content)

f.close()

print("按行读取所有")
f = open("test.txt","r")

content = f.readlines()#readlines()

print(content)

f.close()

print("优雅的读取哈哈")
f = open("test.txt","r")

content = f.readlines()#readlines()

i = 1
for con in content:
    print("第 %d 行: %s"%(i,con))
    i+=1

f.close()

#修改文件名
import os

#os.rename("test.txt", "NEWtest.txt")


Day-7

异常处理

#-*- codeing = utf-8 -*-
#@Time : 2020/7/12 16:02
#@Author : HUGBOY
#@File : hello7_error.py
#@Software: PyCharm

#捕获异常
#f = open("no.txt","r") 打开一个不存在的文件/会报错

try:
    print("001-开头正常!")
    f = open("no.txt","r")
    print("002-结尾正常")
except IOError: #"文件没找到"属于IO/输入输出异常
    print("报错已被拦截!")
    pass

try:
    print(num)
except NameError: #"num未定义"属于NameError异常
    print("代码有错误!")
    pass

#(多种异常)
try:
    print("目前正常1!")
    f = open("no.txt","r")
    print(num)
except (IOError,NameError): #"文件没找到"属于IO/输入输出异常
    print("有错误!")
    pass

#(打印错误内容)
try:
    print("目前正常2!")
    f = open("no.txt","r")
    print(num)
except (IOError,NameError) as result:
    print("有错误,错误内容:")
    print(result)

#(通用-捕获所有异常)
try:
    print("目前正常3!")
    print(num)
except Exception as result:
    print("有错误,错误内容:")
    print(result)

#嵌套
import time
try:
    f = open("no.txt","r")
    #f = open("test.txt","r")
    try:
        while True:
            content = f.readline()
            if len(content) == 0:
                break
            time.sleep(2)
            print(content)
            print("下面的finally 是必须要执行的内容")
    finally:
        f.close()
        print("文件已关闭!")

except Exception as rel:
    print("[嵌套]发生异常,异常内容:")
    print(rel)


#课堂作业  文件拷贝
f = open("gushi.txt","w",encoding="utf-8")
f.write("《咏萤火》\n雨打灯难灭,风吹色更明。\n若飞天上去,定作月边星。")
f.close()

def read_txt():
    try:
        f = open("gushi.txt","r",encoding="utf-8")
        read = f.readlines()
        f.close()
        return read
    except Exception as error:
        print("[read_txt]open file faluse ! ERROR:")
        print(error)
    finally:
        print("读函数已执行!")
def write_txt(content):
    try:
        f = open("copy.txt","w",encoding="utf-8")
        for s in content:
            f.write(s)
        f.close()
    except Exception as error:
        print("[write_txt]open file faluse ! ERROR:")
        print(error)
    finally:
        print("写函数已执行!")

read_con = read_txt()
write_txt(read_con)










Wow!

恭喜少侠完成Python基础学习,入门爬虫可以移步|>>>Python爬虫 小白 3天 入门笔记<<<|尽享免费\音乐\小说\电影\图片。

posted @ 2020-07-12 14:59  HUGBOY  阅读(197)  评论(0编辑  收藏  举报