一、格式化输出%
需求:自我介绍模板
1 #格式化输出 2 # % s d %占位符,占个位置 s(字符串),d(数字)替换内容的类型 3 name = input('请输入姓名:') 4 age = input('请输入年龄:') 5 height = input('请输入身高:') 6 msg = "我叫%s,今年%s 身高 %s" %(name,age,height) #按顺序替代 7 print(msg)
现有一练习需求,问用户的姓名、年龄、工作、爱好 ,然后打印成以下格式
------------ info of 太白金星 ----------- Name : 太白金星 Age : 22 job : Teacher Hobbie: girl ------------- end -----------------
1 name = input('请输入姓名:') 2 age = int(input('请输入年龄:')) 3 job = input('请输入职业:') 4 hobbie = input('请输入爱好:') 5 msg = ''' 6 ------------ info of %s ----------- 7 Name : %s 8 Age : %d 9 job : %s 10 Hobbie: %s 11 ------------- end -----------------''' %(name,name,age,job,hobbie) 12 print(msg)
在格式化输出中,若想单纯的输入一个%:
msg = "我叫%s,今年%s 身高 %s 学习进度为5%%" %(name,age,height)
连续输入两个%即可,表示当前%无占位含义。取的是后面的%,前面的%相当于转义。
二、while else(不太常用,特殊需求会用到)
当while循环没有被break打断时,正常执行else语句
当while循环被break打断时,不执行else语句
1 count = 0 2 while count <= 5 : 3 count += 1 4 print("Loop",count) 5 6 else: 7 print("循环正常执行完啦") 8 print("-----out of while loop ------")