简介
小菜最近学了点python,今天整理了一点python基础的知识。希望和大家一起交流
1、python基础
'''
基本数值运算
'''
print(2+2) #输出4
print(2**3) #幂运算,输出8
str = " hello world"
print(type(str)) #打印变量类型,输出为str
print(str) #输出 hello world
'''
基本数值操作
'''
abs(-4.13) #取绝对值,输出4.13
round(11.7) #取整数,类似于四舍五入,输出12
round(11.4) #输出11
min(1,2,3) #输出最小值1
2、字符串操作
str1 = 'hello'
str2 = 'python'
print(str1 + str2) #输出hellopython
print(str1*3) #输出hellohellohello
len(str1) #str1的字符串长度为5
s1 = '1,2,3,4,5'
print(s1.split(',')) #输出['1', '2', '3', '4', '5']
s2 = ' '
s2.join(s1)
print(s2) #输出'1 2 3 4 5'
s3 = 'hello'
print(s3.upper()) #输出HELLO
s4 = 'WORLD'
print(s4.lower()) #输出world
s5 = ' hello python'
print(s5.strip()) #输出hello python
3、索引
t = 'hi how are you'
print(t[0]) #输出'h'
t[-1] #输出'u',对于索引结构,从前是从0开始,从后是从-1开始
'''
切片
.表示从哪到哪,左闭又开的区间
'''
print(t[0:3]) #输出'hi'
print(t[7:]) #输出'are you'
print(t[::2]) #隔两个输出 h o r o
4、for
example_list = [1,2,3,4,5]
for i in example_list:
print(i)
#输出为
# 1
# 2
# 3
# 4
# 5
for i in range(1,10,2): #range函数相当与从1到10,间隔数为2
print(i) #输出为 1 3 5 7 9
5、 if和while
'''
if条件语句
'''
x = 2
y = 2
z = 3
if x>y:
print('x is greater to y')
elif x<y:
print ('x is less than y')
else:
print('x is equal y')
#输出x is equal y,python中控制代码块是看缩进的,因此要注意格式‘’
'''
while语句
'''
condition = 1
while condition<10:
print(condition)
condition +=2
#输出 1 3 5 7 9
6、函数
def car_mession(price,brand='BMW',color='black',is_used_car=True):
print('price:',price,
'brand:',brand,
'color:',color,
'is_used_car:',is_used_car)
car_mession(50000,) #输出 price: 50000 brand: BMW color: black is_used_car: True
7、列表和元祖
a_tuple = (3,4,1,67,23) #元祖
a_list = [66,223,90,'inn',90.999] #列表
b_list = [[1,2,3],
[4,5,6],
[7,8,9]] #两层列表,类似于二维数组
print(b_list[0][:3]) #输出[1,2,3]
a_list.append(-1) #在a_list添加-1这个数
a_list.remove('inn') #在a_list中删除'inn'
print(a_list.index(223)) #输出223的下标,下标为1
a_list.sort(reverse=True) #排序,加上reverse相当于从大到小输出。
print(a_list) #输出为[223, 90.999, 90, 66, -1]
print(a_list[-3:]) #输出为[90, 66, -1]
for index in range(len(a_tuple)):
print('index:',index,'number:',a_tuple[index])
#输出为:
# index: 0 number: 3
# index: 1 number: 4
# index: 2 number: 1
# index: 3 number: 67
# index: 4 number: 23
for index in range(len(a_list)):
print('index:',index,'number:',a_list[index])
#输出为:
# index: 0 number: 223
# index: 1 number: 90.999
# index: 2 number: 90
# index: 3 number: 66
# index: 4 number: -1
8、文件操作
txt = open('cao_write.txt','w') # 打开一个文件进行写入
txt.write('jin tian tian qi bu cuo')
txt.write('\n')
txt.write('hello python')
txt.close() #关闭文件,注意当我们打开一个文件时一定要把它关闭
data = open('./cao_write.txt') #打开这个文件,默认是读的
lines = data.readlines() #逐行读取数据
for line in lines:
print(line)
#输出为 jin tian tian qi bu cuo
#
# hello python
txt = open('./tang_write.txt','a') #对文件进行追加操作
txt.write('\n')
txt.write('you look good\n')
txt.write('good lucky to you\n')
txt.close()
tx2 = open('./tang_write.txt','r')
print(tx2.read())
tx2.close()
# jin tian tian qi bu cuo
#
# hello python
#
# you look good
# good lucky to you