Python基础 小白入门笔记
笔记来源
Day-1
基础知识(注释、输入、输出、循环、数据类型、随机数)
#-*- codeing = utf-8 -*-
#@Time : 2020/7/11 11:38
#@Author : HUGBOY
#@File : hello1.py
#@Software: PyCharmprint("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 girlfriendif sex == 1:print("你是小哥哥")if girlfd == 1:print("你个单身狗哈哈")else:print("甜蜜")
else:print("你是小姐姐")print("hello !!!")
''''''
#引入随机库
import random
x = random.randint(1,9)
print(x)
'''#课堂练习 剪刀石头布游戏
import randomprint("游戏规则 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 + nn+=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':passprint("It is o,pass")print(i)
#break continue
c = 0
while c <= 12:c +=1if c == 6:print("-"*60)print("The number is the half of 12,end!!!")break#continueelse:print("The nb is :%d"%c)
#课堂作业 九九乘法表
m = 0
while m <= 9:m+=1n=1while n <= m:print("%d * %d = %d"%(m,n,m*n),end=' ')n += 1else: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 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 + yprint(c)add(20,30)def add2(x,y):c = x + yreturn c
print(add2(100,20))#(多个返回值)
def div(a,b):sh = a//byu = a%breturn sh,yu
s,y = div(9,2)
print("商:%d 余数:%d"%(s,y))#课堂练习
#1
def show():print("-"*60)
show()
#2
def showpp(m):i = 0while i < m:show()i+=1print("%d 条直线打印完毕!"%m)#n = int(input("打印几条直线?:"))
n = 5
showpp(n)
#3
def addthree(x,y,z):sum = x+y+zreturn sum
s = addthree(1,2,3)
print("求和结果:%d"%s)
#4
def mean(a,b,c):sum = addthree(a,b,c)rel = sum // 3return 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+=1f.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("报错已被拦截!")passtry: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:breaktime.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 readexcept 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天 入门笔记<<<|尽享免费\音乐\小说\电影\图片。
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
