Python的基本数据类型:数字和组
数字:int,float,bool,complex
组:序列(str,list,tuple),集合,字典
列表的运算:
增:
student=['小红','小吕','小芬'] student1=['小白','小叶'] #末尾增加/中间插入 student.append('小苹果') student.insert(1,'小橙子') #将第二个列表中的元素倒进第一个列表 student.extend(student2) #列表的加法运算相当于新生成一个列表 student+student1
删:
student=['小红','小吕','小芬'] student1=['小白','小叶'] #删除pop 传递下标,remove 传递元素 del 指定位置删除/student.clear()清空列表 student.pop(1) student.remove('小红') del student[2] student.clear()
改:
#将列表内元素倒置排序 student.reverse() #将列表内数字升序排列 num = [1,2,345,30,21] num.sort() #降序: num.sort(reverse=True)
查:
num = [1,2,345,30,21,21] print(num.count(21)) #嵌套列表/如何查询元素个数 my = [1,3,2,['alice,iris,skylar'],'PPTV'] print(len(my))
字符串格式化:
import datetime date = datetime.datetime.today() date = str(date) user = '小白' score = 3.1415926 print('hello,'+user+',today is '+date) print('hello %s!,today is %s,your score is %.2f'%(user,date,score))
条件判断:
Temp = int(input("what's the weather?")) if Temp < 20: print('please take your underware!') elif Temp > 20 and Temp <30: print('you can wear your short sleeves!') elif Temp > 30 and Temp < 35: print('you can choose run without clothes') else: print('极端天气,好自为之')
while 循环:
一定要有一个计数器,循环就是重复复执行循环体里面的代码
break:立即结束循环
continue:结束本次循环,继续进行下一次循环
import random count = 0
fix_value=random.randint(1,10)
while count < 10:# print('随机数字为d%' % fix_value) ran_value = int(input('please give a number:\n')) if ran_value < fix_value: print('more big') elif ran_value > fix_value: print('more little') else: print('Good job! the number is %d'%fix_value) break count+=1 #如若三次机会用完需要一个提示,while 可以对应一个else else: print('game over!')
For 循环:
不需要计数器
import random count = 0 fix_value = random.randint(1,10) for i in range(3): # print('随机数字为d%' % fix_value) ran_value = int(input('please give a number:\n')) if ran_value < fix_value: print('more big') elif ran_value > fix_value: print('more little') else: print('Good job! the number is %d'%fix_value) break count+=1 #如若三次机会用完需要一个提示,for 也可以对应一个else else: print('game over!')