目录
变量
# This is a sample Python script.
import keyword
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
print(f'hi', name)
print('hi' , name)
print(keyword.kwlist)
print(keyword.softkwlist)
# print(*objects, sep=' ', end='\n', file=sys.stdout)
print("fanxil") # 输出字符串 fanxil
print(100) # 输出数字 100
str = 'fanxil'
print(str) # 输出变量 fanxil
L = [1, 2, 'a'] # 列表
print(L) # 输出列表 [1, 2, 'a']
t = (1, 2, 'a') # 元组
print(t) # 输出元祖 (1, 2, 'a')
d = {'a': 1, 'b': 2} # 字典
print(d) # 输出字典 {'a': 1, 'b': 2}
str3 = r'We all know that \'A\' and \'B\' are two capital letters.' # 字符串中的转义字符不进行转义操作
print(str3)
str3 = 'We all know that \'A\' and \'B\' are two capital letters.' # 在单引号里面表示单引号必须进行转义
print(str3)
str4 = "We all know that 'A' and 'B' are two capital letters." # 双引号中的单引号不用转义
print(str4)
"""
这是一条注释
"""
str5 = """\
We all know that 'A' and 'B' are two capital letters.\
""" # 三引号大部分用来写注释或者是跨行赋值
print(str5)
str6 = """\
这是多行注释\
"""
print(str6)
# print('aaaa\taaaa')
# print('a\taaaa')
print('aa\taaaa')
print('aaa\taaaa')
print('-------------------------')
name = 'fanxil'
age = '22'
aaa = """
----------您的姓名和年龄-----------
Name: %s
Age: %s
----------------------------------
""" % (name, age)
print(aaa)
print('-------------------------')
num01, num02 = 200, 300
print("八进制输出:0o%o,0o%o" % (num01, num02))
print("十六进制输出:0x%x,0x%x" % (num01, num02))
print("十进制输出:%d,%d" % (num01, num02))
print("200的二进制输出:", bin(num01), "300的二进制输出为:", bin(num02))
print('-------------------------')
num01 = 123456.8912
print("标准的模式:%f" % num01)
print("保留两位有效数字:%.2f" % num01)
print("e的标准模式:%e" % num01)
print("e的留两位有效数字:%.2e" % num01)
print("g的标准模式:%g" % num01) # 如果是7位保留不了就用科学计数法表示
print("g的留两位有效数字:%.2g" % num01)
print('-------------------------')
str01 = "www.baidu.com"
print("s标准输出:%s" % str01)
print("s的固定空间输出:%20s" % str01) # 右对齐
print("s的固定空间输出:%-20s" % str01) # 左对齐
print("s截取:%.3s" % str01) # 截取前三个字符
print("s截取:%10.3s" % str01)
print("s截取:%-10.3s" % str01)
print('-------------------------')
print('我的名字是:{},今年{}岁'.format('fanxil', 22))
print('我的名字是:{0},今年{1}岁'.format('fanxil', 22))
print('我的名字是:{name},今年{age}岁'.format(name='fanxil', age=22))
age = 25
name = 'fanxil'
print('{0} is {1} years old. '.format(name, age)) # 输出参数
print('{0} is a girl. '.format(name))
print('{0:.3} is a decimal. '.format(1 / 3)) # 小数点后三位
print('{0:_^11} is a 11 length. '.format(name)) # 使用_补齐空位
print('{first} is as {second}. '.format(first=name, second='Wendy')) # 别名替换
print('My name is {0.name}'.format(open('out.txt', 'w'))) # 调用方法
print('My name is {0:8}.'.format('Fred')) # 指定宽度
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
if
# This is a sample Python script.
import keyword
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print('-------------------------')
if 5 > 2:
print("条件成立", "执行语句1")
else:
print('条件不成立', "执行语句2")
# 条件成立 执行语句1
# 根据分数判断等级
score = 60
if score >= 60 and score < 80:
print("成绩及格")
elif score >= 80 and score < 90:
print("成绩良好")
elif score >= 90 and score <= 100:
print("成绩优秀")
else:
print("成绩不及格")
proof = 60
if proof < 20:
print("驾驶员不构成酒驾")
else:
if proof < 80:
print("驾驶员已构成酒驾")
else:
print("驾驶员已构成醉驾")
# 三目运算
a, b, c = -1, 2, 1
print(a if a < b and a < c else b if b < c and b < a else c)
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
input
# This is a sample Python script.
import keyword
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print('-------------------------')
a = input()
print(a, type(a))
b = input()
print(b, type(b))
c = input()
print(c, type(c))
a = input()
# print(a + 1)
# 1 TypeError: can only concatenate str (not "int") to str
a = input() # 10
b = input() # 20
print(a + b)
# 1020
print('-------------------------')
a = int(input('请输入数字:'))
b = list(input('请输入列表:'))
c = tuple(input('请输入元组:'))
print(a, type(a))
print(b, type(b))
print(c, type(c))
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
int
# This is a sample Python script.
import keyword
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print('-------------------------')
num1 = 23
num2 = 0b001001001
num3 = 0x12ab23
num4 = 0o7623
print('八进制:%o' % num4)
print('八进制:%x' % num3)
print('2进制', bin(num2))
print('16进制', hex(num3))
print('8进制', oct(num4))
print('-------------------------')
s = True
print(s)
print('-------------------------')
var1 = 'Hello World!'
print('var1[0]:', var1[0])
print('var1[0]:', var1[0:5])
var1 = 'Hello World!'
var1 = var1[::-1]
print(var1)
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
list= arr /set
# This is a sample Python script.
import keyword
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print('-------------------------')
lis = ['p', 'y', 't', 'h', 'o', 'n']
# 索引 0 1 2 3 4 5
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5]
list3 = ["a", "b", "c", "d"]
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5]
print('list1[0]:', list1[0])
print('list1[1:3]:', list1[1:3])
print('-------------------------')
lst1 = [1, 2, 3, 4, 5, 6, 7]
lst1.append(8)
lst1.extend([1, 2, 3])
print(lst1)
# [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3]
print('-------------------------')
lst2 = [1, 2, 3, 4, 5, 6, 7]
lst2.append(8)
lst3= [1, 2, 3]
lst2.extend(lst3)
print(lst2)
# [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3]
lst = [1, 2, 3, 4]
lst.append([1, 2, 3, 4])
print(lst)
# [1, 2, 3, 4, [1, 2, 3, 4]] 此时append中的[1,2,3,4]以一个元素的形式追加在lst的末尾
lst = [1, 2, 3, 4]
lst.insert(0, 5) # 在列表的0号索引位置添加一个元素5
print(lst)
# [5,1,2,3,4]
lst = [1, 2, 3, 4]
lst[1:1] = [6, 7, 8, 9] # 在列表索引位 1的位置添加6,7,8,9多个元素
print(lst)
# [1, 6, 7, 8, 9, 2, 3, 4]
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
lst.remove(1)
print(lst)
# [2, 3, 4, 5, 6, 7, 8, 9, 10]
# 如果指定的元素不在列表中,则会报一个语法错误
# ValueError: list.remove(x): x not in list
lst.pop(0) # 删除索引为0的元素,也就是2
print(lst)
# [3, 4, 5, 6, 7, 8, 9, 10]
lst[0:4] = [] # 使用一个空列表去填[0:4]的区域
print(lst)
# [7, 8, 9, 10]
del lst[0:2] # 删除0,1索引上的元素
print(lst)
# [9, 10]
lst.clear() # 清空列表
print(lst)
# []
del lst # 删除lst这个列表,lst变量已经不存在了
# print(lst)
# 此时会报一个未声明错误
# NameError: name 'lst' is not defined
lst = [1, 2, 3, 4, 5, 6]
lst[1] = 9
print(lst)
# [1, 9, 3, 4, 5, 6]
lst = [1, 2, 1, 2, 3, 4, 5, 6]
print(lst.count(1)) # 统计元素1在列表中出现的次数
# 2
print(lst.index(2)) # 统计元素2在列表中第一次出现的索引
# 1
lst.reverse()
print(lst)
# [6, 5, 4, 3, 2, 1, 2, 1]
lst.sort(reverse=False) # 升序排序
print(lst)
# [1, 1, 2, 2, 3, 4, 5, 6]
# reverse=False 排序方式,默认为升序排序
lst.sort(reverse=True) # 降序排序
print(lst)
# [6, 5, 4, 3, 2, 2, 1, 1]
lst1 = sorted(lst) # 默认升序,也可以使用gaun'jia'na'z
print(lst1)
# [1, 1, 2, 2, 3, 4, 5, 6]
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
dict==map
# This is a sample Python script.
import keyword
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print('-------------------------')
dic1 = {}
dic2 = dict()
print(dic1)
print(dic2)
dic1 = {'name': '小明', 'age': 22}
dic2 = dict(name='小明', age=22)
print(dic1)
print(dic2)
# {'name': '小明', 'age': 22}
# {'name': '小明', 'age': 22}
# 两种创建方法
dic1 = {'name': '小明', 'age': 22}
print(dic1['name'])
# 小明
dict1 = {'Name': '小明', 'Age': 22, '排名': '第一'}
print(dict)
# {'Name': '小明', 'Age': 22, '排名': '第一'}
dict1['Age'] = 23 # 更新
dict1['居住地'] = "四川" # 添加
print(dict1)
# {'Name': '小明', 'Age': 23, '排名': '第一', '居住地': '四川'}
dict1 = {'Name': '小明', 'Age': 23, 'Class': 'First'}
print(dict1)
del dict1['Name'] # 删除键是'Name'的条目
print(dict1)
dict1.clear() # 清空字典所有条目
print(dict1)
del dict1 # 删除字典
# print(dict1)
dict1 = {'Name': '小明', 'Age': 7, 'Name': '张三'}
print(dict1['name'])
# KeyError: 'name'
dic = {1: 2, 3: 4}
print(dic)
dic = {(1, 2): 2, 3: 4}
print(dic)
dic = {'1': 1, "2": 2}
print(dic)
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
set
# This is a sample Python script.
import keyword
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print('-------------------------')
set1 = {1, 2, 3}
print(set1)
set1.add(4)
print(set1)
set1.update([5, 6, 7])
print(set1)
print('-------------------------')
set1 = {1, 2, 3}
set1.remove(1)
print(set1)
# {2,3}
# set1.remove(4)
print(set1)
# KeyError: 4 元素不存在,会发生错误
print('-------------------------')
set1 = {1, 2, 3}
set1.discard(1)
print(set1)
# {2,3}
set1.discard(4)
print(set1)
# {2,3} 元素不存在,不会发生错误
print('-------------------------')
set = {7, 2, 1, 4, 5, 3, 8, 9}
set.pop()
print(set)
set.pop()
print(set)
set.pop()
print(set)
print('-------------------------')
s = {1, 2, 3, 4}
s1 = {2, 4, 1, 3}
print(s == s1)
# True
s1 = {1, 2, 3, 4, 5, 6}
s2 = {1, 2, 3}
print(s2.issubset(s1)) # s2是s1的子集
# True
s1 = {1, 2}
s2 = {4, 5}
print(s1.isdisjoint(s2))
# True
set1 = {1, 2, 3, 4, 5}
set2 = {2, 3, 6, 7}
print(set1.union(set2))
# {1, 2, 3, 4, 5, 6, 7}
set1 = {1, 2, 3, 4, 5}
set2 = {2, 3, 6, 7}
print(set1.intersection(set2))
# {2,3}
set1 = {1, 2, 3, 4, 5}
set2 = {2, 3, 6, 7}
print(set1.difference(set2)) # 在set1中,减去set2中的元素
# {1,4,5}
set1 = {1, 2, 3, 4, 5}
set2 = {2, 3, 6, 7}
print(set1.symmetric_difference(set2))
# {1,4,5,6,7}
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
tuple
# This is a sample Python script.
import keyword
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print('-------------------------')
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5)
tup3 = "a", "b", "c", "d"
tup1 = ()
tup2 = tuple() # 创建空元组的两种方式,()、tuple()
tup3 = (50,) # 创建单个元素,需要在末尾加上逗号
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7)
print(tup1[0]) # 取索引值为0的元素
print(tup2[1:4]) # 取索引值1至3的元素
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz') # 以下修改元组元素操作是非法的。
# tup1[0] = 100
tup3 = tup1 + tup2 # 创建一个新的元组
print(tup3)
tup = ('physics', 'chemistry', 1997, 2000)
print(tup)
del tup
print(tup) # 删除元组之后,输出会有异常信息
tup1 = ('spam', 'Spam', 'SPAM!')
# 索引 0 1 2 正向
# 索引 -3 -2 -1 逆向
tuple1, tuple2 = (123, 22, 33, 'xyz'), (456, 'abc') # 多变量赋值
print(len(tuple1)) # 输出为4
tuple1, tuple2 = (123, 22, 33, 12345, 0), ('a', 'b', 'C', 'D')
print(max(tuple1)) # 输出为12345
print(max(tuple2)) # 输出为'b'
print(min(tuple1)) # 输出为0
print(min(tuple2)) # 输出为'C'
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
while
# This is a sample Python script.
import keyword
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print('-------------------------')
# 最简单的死循环语句
# while True:
# print('这是一条死循环')
count = 0
while count < 5:
print(count, " is less than 5")
count += 1
else:
print(count, " is not less than 5")
# Press the green button in the gutter to run the script.
add = "https://www.baidu.com"
# for循环,遍历 add 字符串
for ch in add:
print(ch, end="")
# 输出:https://www.baidu.com
print("计算 1+2+...+100 的结果为:")
# 保存累加结果的变量
result = 0
# 逐个获取从 1 到 100 这些值,并做累加操作
for i in range(101):
result += i
print(result)
# 计算 1+2+...+100 的结果为:
# 5050
# 对列表进行遍历
my_list = [1, 2, 3, 4, 5]
for ele in my_list:
print('ele =', ele)
my_set = {1, 2, 3, 4, 5}
for ele in my_set:
print('set =', ele)
dic = {'name': '小明', 'age': 22, 'score': 100}
for di in dic:
print('di = ', di, dic[di])
# 得到字典的每一个键(key)默认
for di in dic.items():
print('items = ', di)
# 得到字典的每一组数据,其结果为一个元组
for di in dic.values():
print('values = ', di)
# 得到字典的每一组键所对应的值
for di in dic.keys():
print('keys = ', di)
# 得到字典的每一键(key) 默认情况
# 一个简单的for循环
for i in range(0, 10):
print("i的值是: ", i)
if i == 2:
# 执行该语句时将结束循环
break
else:
print('else块: ', i) # 这个else语句并不会执行
add = "https://baidu.com,https://zhihu.com"
# 一个简单的for循环
for i in add:
if i == ',':
# 忽略本次循环的剩下语句
print('\n')
continue
print(i, end="")
# https://baidu.com
print('\n')
add = "112131"
print("函数内部 add =", add)
return 123
add = 'http://gogle.com'
print("函数外部 add =",add)
if __name__ == '__main__':
x = print_hi('PyCharm')
print(x)
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
运算符
# This is a sample Python script.
import keyword
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print('-------------------------')
a = 10
b = 4
print(a / b, type(a / b))
# 2.5 <class 'float'>
# print(4 / 0)
# ZeroDivisionError: division by zero
print(7 % 3) # 1
print(7 % -3) # -2
print(-7 % 3) # 2
print(-7 % -3) # -1
"""
进行取余运算时,被除数为正数,那么结果就为正,被除数为负,结果就为负数
"""
print('-------------------------')
num1 = 1
num1 += 2 # 等价于 num1 = num1 + 2
print(num1)
# 3
a = 1
b = 2
print(a == b, type(a == b))
# False <class 'bool'>
a = 1
b = 2
print((a == b) + 1) # False + 1 = 0 + 1;这里的结果为1,需要把a==b单独用括号括起来
lis1 = [1, 2, 3, 4]
lis2 = [4, 3, 2, 1]
print(lis1 == lis2) # False
lis1 = [1, 2, 3, 4]
lis2 = [1, 2, 3, 4]
print(lis1 == lis2) # True
set1 = {1, 2, 3, 4}
set2 = {2, 3, 1, 4}
print(set1 == set2) # True
print('-------------------------')
# not > and > or
# not"非" - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。
# and"与" - 如果 x 为 False,x and y 返回 False,否则它返回 y 的计算值。
# or"或" - 如果 x 是非 0,它返回 x 的值,否则它返回 y 的计算值。
a, b = 0, 4
print(a or b) # 4
a, b = 2, 4
print(a or b) # 2
str1 = 'python'
str2 = ''
list1 = ['python']
list2 = []
print(str1 or str2 and list1 or list2)
# 先计算 str2 and list1 得到 ''
# 再按顺序计算 str1 or ‘ ’ or list2
# 得到 'python' or ' ' or [ ]
# 得到 'python' or []
# 最后返回 'pythpn'
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
func
def func1():
print("这是外部函数")
def func2():
print("这是内部函数")
func2()
if __name__ == '__main__':
func1()
lamda
def test(aaaa):
lis1 = [1, 2, 3, 4, 5, 6, 7]
lis2 = [7, 6, 5, 4, 3, 2, 1]
print(list(map(lambda x, y: x + y, lis1, lis2)))
# [8, 8, 8, 8, 8, 8, 8]
sentence = "Welcome To Beijing!"
words = sentence.split()
lengths = map(lambda x: len(x), words)
print(list(lengths))
# [7,2,8]
return aaaa
if __name__ == '__main__':
aaa = test(123)
print(aaa)