赞
踩
注意windows版本的啊
回到上一行:Ctrl + Alt+Enter
回到下一行:Shift + Enter
格式化代码:Ctrl+Alt + L
import math, copy, random, time
from collections import Counter
def hello_world():
yourname = input('你好,请输入你的名字:')
print('欢迎来到Python的世界', yourname)
print('让我们开始学习')
hello_world()
输出结果:
你好,请输入你的名字:lzk
欢迎来到Python的世界 lzk
让我们开始学习
要注意间隔换行后一半用Tab进行推进,表示属于hello_word()方法的方法体
def hello_twice():
global yourname, yourheight, yourweight
yourname = input("请输入你的名字:")
yourheight = input("请输入你的身高:")
yourweight = input("请输入你的体重:")
global表示全局变量,下文可以使用的一个变量
def deviding_line():
word1 = 'i am line'
word2 = word1.upper()# 全部大写
word3 = word1.lower()# 全部小写
word4 = word1.title()# 首字母大写
words = [word1, word2, word3, word4] # []可以创建一个列表,列表可以存放很多
line = '-' * 40 # 利用*创建字符串,这里有40个‘-’
endReturn = line + words[random.randint(0, 3)] + line # random.randint()可以创建随机整数,0,3为随机数的上下限
return endReturn
对字符串用 * 40,表示40个相同字符串进行拼接
def study_number(): num1 = input("请输入一个数字:") print("你输入的数字%s" % num1, '可它的类型为:', type(num1)) # 你输入的数字das 可它的类型为: <class 'str'> num2 = int(input("请在输入一个数字:")) print("你输入的数字%s" % num2, '可它的类型为:', type(num2)) num3 = float(input("请在输入一个数字:")) print("你输入的数字%s" % num3, '可它的类型为:', type(num3)) # 数字减法 # format()函数格式化输出,在字符串中的{}符号将被替换为format()的参数 print("num1+num2={}".format(int(num1) + num2)) print("num1-num2={}".format(int(num1) - num2)) # 类似于 “-”*11 = “-----------” print("num1*num2={}".format(num1 * num2)) # “1”*2 = 11 # 数字乘法 print("num1*num2={}".format(int(num1) * num2)) print("数字整除:num2//num3={:.3f}".format(num2 // num3)) # 同时{:3f}表示输出格式小数点后面保留三位 print("数字除法:num2/num3={:.4f}".format(num2 / num3)) # 保留小数点后四位 print("num2%num3={:.4f}".format(num2 % num3)) # 28求余数 print("num2%num3={:.2%}".format(num2 % num3)) # 求余数,{:.2%}输出格式为百分比格式 print("num1**num2={}".format(int(num1) ** num2)) # 幂运算 # format多参数,标记位置对应输出 print("This is the {a},and {b}".format(a='numbers', b='some operations')) one, two, three = True, True, False print(one, two, three) print('and运算符:', one and two, one and three) print('or运算符:', one or two, one or three) # not运算符,得到相反的值 print('not运算符:', not one, not two, not three)
占位符方式输出:
通过%s进行占位,在逗号后面通过%num1进行赋值;
例如:
print("你输入的数字%s" % num1, '可它的类型为:', type(num1))
通过{}进行占位,然后通过调用.format()方法进行赋值
print("num1+num2={}".format(int(num1) + num2))
通过{a}占位,然后用format(a='numbers)进行赋值:format多参数,标记位置对应输出
print("This is the {a},and {b}".format(a='numbers', b='some operations'))
类型输出
一般使用type(num),这样可以输出num的类型
print("你输入的数字%s" % num1, '可它的类型为:', type(num1))
输出结果
你输入的数字das 可它的类型为: <class 'str'>
数字运算
print("num1+num2={}".format(int(num1) + num2))
输入:
num1:1
你输入的数字1 可它的类型为: <class 'str'>
num2:2
你输入的数字2 可它的类型为: <class 'int'>
num3:3
你输入的数字3.0 可它的类型为: <class 'float'>
print("数字整除:num2//num3={:.3f}".format(num2 // num3))
同时{:3f}表示输出格式小数点后面保留三位
结果:
数字整除:num2//num3=0.000
print("数字除法:num2/num3={:.4f}".format(num2 / num3))
保留小数点后4位
结果:
数字除法:num2/num3=0.6667
print("num2%num3={:.4f}".format(num2 % num3)) # 28求余数
print("num2%num3={:.2%}".format(num2 % num3)) # 求余数,{:.2%}输出格式为百分比格式
num1=1,num2=2
结果:
num2%num3=2.0000
num2%num3=200.00%
print("num1**num2={}".format(int(num1) ** num2))
num1=1,num2=2
结果:
num1**num2=1
one, two, three = True, True, False
print(one, two, three)
print('and运算符:', one and two, one and three)
print('or运算符:', one or two, one or three)
# not运算符,得到相反的值
print('not运算符:', not one, not two, not three)
结果:
True True False
and运算符: True False
or运算符: True True
not运算符: False False True
def study_list(length): # 创建列表,利用符号[] l1 = [1, 2, 3, 4, 5, 6, 0] # 也可以用list(),range(start,end,step)函数:可以创建一个整数列表 # start:起始数字,end:终止数字,前闭后开,step:步长 l2 = list(range(10, 10 + length, 1)) print("l2::::", l2) print("l1的类型为:", type(l1)) print(l1[1], l2[1]) l3 = l2 # 将l2的引用赋予l3 print(id(l1), id(l2), id(l3)) # id()获取对象的内存地址,在这里可以看到l3和l2的内存地址是一样的 l3[0] = 99 print("l2==l3么?", l2 == l3) # True l4 = l2.copy() l4[0] = 999 print("l4==l2么", l4 == l2) # False print("删除前", l4) del l4[0] print("删除后", l4) l4.append(30) # 给列表最后添加值 print(l4) l4.extend(l1) # 给列表追加一个序列多个值 print("添加l1后", l4) l4.reverse() # 列表翻转 print("l4反转后:", l4) l4.sort() print("l4排序后:", l4)
range()方法:
range(start,end,step)用于创建一个整数列表,参数中:start表示起始位置,end:表示终止数字,且是前闭后开,step:步长,也只列表中每两个数字间之差
“双等于号的作用”:
==在python中是列表或集合中值比较,而在java中双等表示比较内存地址,所以才会有重写equals()方法。这个后续再研究一下
copy()方法:
复制一个相同的列表出来,引用地址不同
append()方法:
往列表后面追加元素
extend()方法:
向一个列表后面追加另一个列表
sort()方法:
排序方法,里面可以有参数,key=len:表示按照每个元素长度排序,key=str:表示按照字典序排序。 例:
list1.sort(key=len)
# 解释参数类型 ->为返回值类型 def study_tuple(length: int) -> bool: # 创建元组,利用()符号,元组的特性是不可以改变 tuple1 = (1, 1, 2, 3, 4) # 利用tuple创建元组 tuple2 = tuple(range(10, 10 + length)) # 元组函数count(),用于输出某个值的数量 print(tuple1.count(1)) # 元组函数index(),可以按照索引得值 print(tuple1.index(1)) # 异常处理 try: # 元组不可变性,该语句会报错 tuple1[0] = 9 except TypeError: print("元组插入失败") finally: # finally内语句不管是否出现错误都会执行 print("不管插入成不成功都会执行") try: print(id(tuple1), id(tuple2)) except: return False else: # 元组虽然不可改变,但是可以通过+号进行合并为另一个元组 tuple3 = tuple1 + tuple2 print(tuple3, id(tuple3)) return True
异常捕获
try:
# 元组不可变性,该语句会报错
tuple1[0] = 9
except TypeError:
print("元组插入失败")
finally: # finally内语句不管是否出现错误都会执行
print("不管插入成不成功都会执行")
try:
print(id(tuple1), id(tuple2))
except:
return False
else:
# 元组虽然不可改变,但是可以通过+号进行合并为另一个元组
tuple3 = tuple1 + tuple2
print(tuple3, id(tuple3))
return True
def study_dict(): # 以下为创建字典的5种方法 dict1 = {1: "一", 2: "二", 3: "三", 4: "四"} dict2 = dict(one=1, two=2, three=3) dict3 = dict(zip([6, 7, 8, 9], ['Six', 'Seven', 'Eight', 'Nine'])) dict4 = dict([('One', 1), ('Two', 2), ('Three', 3)]) dict5 = dict({1: '一', 2: "二", 3: "三", 4: "四"}) print(type(dict1), dict1 == dict5) print(dict1[1], dict2['one'], dict3[6], dict4['One'], dict5[1]) # 通过字典的键访问 print(dict1.get(4)) dict1[1] = '医' dict1[5] = '五' print(dict1) # in和not in 关键字可以判断值是否在序列中 print(1 in dict1, 6 in dict1, 7 not in dict1) dict6 = dict1.copy() dict6[1] = 'One' print(dict1, '<dict1-------dict6>', dict6) # 字典清空 dict1.clear() print(dict1) # 删除字典,也可以用del dict[key]的方式删除某个键 del dict1, dict2, dict3, dict4, dict5, dict6
个人觉得:dict1 = dict(one=1,two=2,three=3)创建会更快
dict2 = dict(zip([6,7,8,9],['six','seven','eight','nine']))适合两个相同长度列表去生成字典
字典访问类似于访问列表
dict1[1]:[]中放入key值
判断该key是否在字典中
一般使用in,not in:
print(1 in dict1, 6 in dict1, 7 not in dict1)
字典清空
clear()清空字典内容
删除字典
使用del:
# 删除字典,也可以用del dict[key]的方式删除某个键
del dict1, dict2, dict3, dict4, dict5, dict6
# 集合中不存在相等的值,即集合中的元素不可重复,也类似于java中的set集合 def study_set(): # 利用set()函数进行创建集合 set1 = set(['You', 'Are', 'Not', 'Beautiful']) # 利用{}创建集合,创建空集合的时候不能用{},因为这个代表字典 set2 = {'You', 'Are', 'So', 'Beautiful'} # 集合的复制 set3 = set2.copy() print(type(set1)) print(set1, set2) # 集合或运算符,得到两个集合中的所有元素 print(set1 | set2)# {'Not', 'Are', 'You', 'Beautiful', 'So'} # 集合与运算符,得到两个集合的共同元素 print(set1 & set2)# {'Beautiful', 'You', 'Are'} # 不同时包含set1和set2的元素也就是 并集-交集 print(set1 ^ set2)# {'Not', 'So'} # 集合差运算,得到set1有,set2没有的元素 print(set1 - set2)# {'Not'} # <=符号,判断是否为子集,<符号,判断是否为真子集(除本身以外的) print(set1 <= set2, set3 <= set2, set3 < set2)# False True False set1.add('Me Too') # is 和 is not 语句,用于判断对象是否一样,==判断值是否一样 print('is语句用法', set3 == set2, set3 is set2, set1 is not set2)# is语句用法 True False True set3.clear() print(set3) del set3
set集合特性
元素不重复,放入元素后默认按照字典序排序
add()
不同于列表的是set集合是通过add()方法进行追加元素的,而列表通过append()方法
is、is not
is 和 is not 语句,用于判断对象是否一样,个人感觉像是对象内存地址的比较,==判断值是否一样
def study_Some_functions(): list1 = [1, 2, 3, 4, 5, 6] tuple1 = (11, 12, 13, 14, 15, 16) # 元组 set1 = set(list1) # 集合 dict1 = dict(zip([1, 2, 3, 4, 5], ["one", "two", "three", "four", "five"])) # 集合 # 对字典的操作是相对于key的 print("max()函数,得到序列中最大值", max(list1), max(tuple1), max(set1), max(dict1)) print("min()函数,得到序列中最小值", min(list1), min(tuple1), min(set1), min(dict1)) print("sum()函数,得到序列中和", sum(list1), sum(tuple1), sum(set1), sum(dict1)) print("len()函数,得到序列长度", len(list1), len(tuple1), len(set1), len(dict1)) print("divmod()函数,计算两个数的商和余数", divmod(list1[0], tuple1[0])) # (0, 1) # enumerate(),给元组添加一个索引 [(0, 11), (1, 12), (2, 13), (3, 14), (4, 15), (5, 16)] print("enumerate(),给元组添加一个索引", list(enumerate(tuple1))) # 利用list()将元组,字典等等转换为列表 list2 = list(tuple1) list3 = list(set1) list4 = list(dict1) # 利用tuple()将列表,字典转换为元组 tuple2 = tuple(list1) print(list2, list3, list4, tuple2) # for循环 for i in range(len(list1)): # print的属性end,可以使输出格式为end的内容 # 1 - 2 - 3 - 4 - 5 - 6 - print(list1[i], end=' - ') print() for i in dict1: # 1 one 2 two 3 three 4 four 5 five print(i, dict1[i], end=" ") # reversed()函数,可以反转序列 # list起到强制转换的作用 list5 = list(reversed(list1)) list6 = reversed(list1) # list5 [6, 5, 4, 3, 2, 1] print('\nlist5', list5) # list6 <list_reverseiterator object at 0x000001B2B170F648> print('list6', list6) testStr = 'The mountains and rivers are different , the wind and ' \ 'the moon are the same' # split()函数,以split()内参数分割字符串,返回一个列表 words = testStr.split(' ') print(words) # sort()函数,进行排序,参数key==len时,以字符串长度为排序标准 words.sort(key=len) print('以长度排序', words) words.sort(key=len, reverse=True) print('以长度排序,并且翻转', words) # 以字典序进行排序 words.sort(key=str) print('以字典序进行排序', words) # collections 模块中的Counter,可以得到字符串中每个数字出现次数 ct = Counter(testStr) print(ct) # [(' ', 14), ('e', 10), ('n', 7)] print(ct.most_common(5)) # 得到字符数最多的前五位
def study_Slice(): str1 = 'I hope one dat,I can find you,my sweet dream' list1 = list(range(10)) tuple1 = tuple(list1) # 切片格式为str[start:end:step],前闭后开,step可为正负,默认步长为1 # I hop print(str1[0:5]) # 步长为负数的时候,反转 # maerd teews ym,uoy dnif nac I,tad eno epoh I print(str1[::-1]) # I can find you,my sweet dream print(str1[15:]) # I hope one dat, print(str1[:15]) print(str1[::2]) print(str1[1::2]) print(list1[:]) print(list1[2:]) print(list1[:2]) print(list1[::-1]) # 切片赋值,右边必须为一个可以遍历的序列 list1[1:5] = [10] # list1[1:5] = 10,这样会报错 print(list1)
def study_loop_select(): list1 = [1, 2, 3, 4, 5] num = int(input('while循环,输入你想要循环的次数:')) i = 1 while i <= num: # if...elif...else选择语句 if i < 5: print('我打印了', i, '次') elif i < 10: print('我打印了', i, '次,真累啊') elif i < 15: print("打印太多了,在打印我就要停止了") elif i < 20: print('continue') i += 1 # continue,用在循环中,continue后的所有语句都不允许,直接进入下次循环 continue print('我想我可能输出不了了') else: print("累死我了,休息。都", i, '次了··') # break语句,运用在循环中,直接退出循环,所以,在本例子中,这个循环最多循环20次 break i += 1 # time库为python中的时间库,time.sleep(second)可以使程序暂停运行second秒 time.sleep(0.5) # while循环后接一个else语句,当执行完所有循环后执行一次,可以省略 else: print('while结束了') for i in list1: print(i, end=' ') print() for i in range(5): print(i, end=' ')
python的时间库函数:time.sleep(ms),参数位毫秒级别的数字
选择函数:
if...elif...else,与java中的关键词不太一样:if ...else if ... else
while循环函数:
在while循环完后可以加一个else,执行一次else中的代码
def study_expression_deduction(): # 利用该语句推导出列表 list1 = [i for i in range(10)] # 语句中增加if,满足if表达式的才会是列表 list2 = [x for x in range(20) if x % 2 == 0] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] list1----list2 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] print(list1, 'list1----list2', list2) # 函数可以在任何地方被调用,如果是自己调用自己就可以称为递归调用 print(deviding_line()) # [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] list3 = [['_'] * 3 for i in range(3)] # ['___', '___', '___'] list4 = ['_' * 3 for i in range(3)] print(list4) print(list3) fruits = ['Apple', 'Banana', 'Pear'] colors = ['Red', 'Yellow', 'Green'] # 两个列表合并 # [('Red', 'Apple'), ('Yellow', 'Banana'), ('Green', 'Pear')] suitcolor = [(color, fruit) for color, fruit in zip(colors, fruits)] print(suitcolor) # 两个列表的笛卡尔积:也就是全排列 # [('Red', 'Apple'), ('Red', 'Banana'), ('Red', 'Pear'), ('Yellow', 'Apple'), # ('Yellow', 'Banana'), ('Yellow', 'Pear'), ('Green', 'Apple'), ('Green', 'Banana'), ('Green', 'Pear')] cartesian = [(color, fruit) for color in colors for fruit in fruits] print(cartesian) # 字典的推导,只要是带有键值对的任何序列,都可以推导字典 # {'Red': 'Apple', 'Yellow': 'Banana', 'Green': 'Pear'} dict1 = {fruit: color for fruit, color in suitcolor} print(dict1)
def study_files(): filepath = input('请输入你的文件路径(输入quit退出):') if filepath == 'quit': return True try: # 打开文件,'w'为写格式打开 file = open(filepath, 'w') # 向文件写入字符串 file.write('哈哈,现在开始写文件') # 关闭文件 file.close() # 以’r'读格式打开 file = open(filepath, 'r') # read()函数可以得到内容 print('从文件中读出的内容:\n', file.read()) except FileNotFoundError: print('文件为找见请重新输入') # 递归调用 study_files() except: print('出现错误,请重新输入路径') study_files()
open()方法:
open()方法中参数,第一个是文件路径,第二个是读/写全写,也就是‘w’/‘r’
切记write完数据后关闭流,使用close()方法关闭
# 面向对象编程,python中创建类class,类包含有属性和方法,包括有私有变量,共有变量等等
class Users():
# 类的构造方法,创建实例时自动调用
def __init__(self, name, height, weight):
self.name = name
self.height = height
self.weight = weight
self.yanzhi = 100
# 类方法
def display(self):
print('大家好,我是{},身高{},体重{},颜值超高{}'.format(self.name, self.height,
self.weight, self.yanzhi))
# 无论之前有什么,程序都会从这里开始运行 if __name__ == "__main__": # 调用函数 hello_world() deviding_line() try: # hello_world()中有一个变量,看是否能找到该变量 print(yourname) except: print('未能找到该变量') deviding_line() # global语句,定义了yourname,所以该函数中的变量在以下程序中都可以使用 hello_twice() user = Users(yourname, yourheight, yourweight) user.display() # 在python中,可以用三引号进行多行注释,但是如果用变量接收注释的话也可以是一个有格式的字符串,如下: chooseinformation = '''Input the number of the function you want to Run(quit is exit): 1、study_number 2、study_list 3、study_tuple 4、study_dict 5、study_set 6、study_Some_functions 7、study_Slice 8、study_loop_sleep 9、study_expression_deduction 10、study_files ''' deviding_line() # while循环进行运行程序,只有当输入quit时才会退出循环(不过你强制退出当然也可以退出) while True: # 为了让输出不那么快,等待按钮后才输出以后内容 input('按键继续') print(chooseinformation) num = input('输入序号:') # 在以下if...elif...else选择中,我们来选择运行不同的函数 if num == 'quit': break elif num == '1': study_number() elif num == '2': study_list(10) elif num == '3': study_tuple(10) elif num == '4': study_dict() elif num == '5': study_set() elif num == '6': study_Some_functions() elif num == '7': study_Slice() elif num == '8': study_loop_select() elif num == '9': study_expression_deduction() elif num == '10': study_files() deviding_line() print('哈哈,恭喜你,这个程序结束咯~')
本次python学习基础语法结束,为了以后方便复习发布于此,如果有大佬愿意指导,评论区恭迎!!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。