一、注释的写法
二、if else的用法
score = int(input(">>:")) if score > 90: print("A") elif score > 80: print("B") elif score > 70: print("C") elif score > 50: print("D") else: print("不及格")
**缩进级别必须保持一致
三、运算符
2**10:表示2的十次方
5/2:结果为2.5
5//2:结果为2
+ 、-、 *、 /、 //取整、%
四、while循环 continue break
n=1 while n<=100: if n%2==0: print(n) n +=1 if n==10: break
打印99乘法表:
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
n=1 while n<=9: m=1 while m<=n: print(str(m)+"*"+str(n)+"="+str(m*n),end="\t") m+=1 print() n+=1
五、字符格式化输出
占位符 :%s s = string
%d d = digit 整数
%f f = float 浮点数,约等于小数,保留小数点后六位
name = input("name:") age = int(input("age:")) salary = input("salary:") if salary.isdigit(): salary = int(salary) else: # print("must input digit") exit("must input digit") mesg = ''' -------info of %s ------ name: %s age: %s #%d salary: %s you will be retired in %s years ------------------------ ''' %(name,name,age,salary,65-age) print(mesg)
for i in range(1,5,2): #2表示步长
print(i) 结果为1,3
username="gdj" password="123456" for i in range(3): if input("username:")==username and input("password:")==password: print("welcome %s" %username) break else: print("invalide username or password") else: print("太笨了")
六、列表
列表创建方式:a=list() 或者a=[]
统计出现的次数:a=["a","to","tt","to","to"].count("to")
排序: a.sort(reverse=true) 从大到小
七、购物车
product_list=[ ('mars',9000), ('hadoop',120), ('tsl',120000), ('book',99), ('bike',600) ] saving=input("please input your money:") shopping=[] if saving.isdigit(): saving=int(saving) while True: for i,v in enumerate(product_list,1): print(i,'<<<<<<',v) choice=input('输入购买商品的编号[退出:q]') if choice.isdigit(): choice=int(choice) if choice>0 and choice <=len(product_list): if product_list[choice - 1][1] <= saving: shopping.append(product_list[choice - 1]) saving -= product_list[choice - 1][1] else: print('您的余额不足,还剩%s元'%saving) print(shopping) else: print('编码不存在') elif choice=='q': print('您已购买如下商品=============') rest=[] for i in range(0,len(shopping)): id = 1 for j in range(i+1,len(shopping)): if shopping[i]==shopping[j]: id +=1 if not shopping[i] in rest: print(shopping[i],id) rest.append(shopping[i]) print('您还剩%s元'%saving) break else: print('输入的编码不对') else: print('输入的钱格式不对')
来源:https://www.cnblogs.com/gdjgdj/p/9238552.html