python--格式化输出,for循环,range
格式化输出
%s: 字符串的占位符, 可以放置任何内容(数字)
%d: 数字的占位符
name = "zouzou" print("%s活了人生的%%2" % name) # 如果字符串中有了占位符. 那么后面的所有的%都是占位. 需要转义,用%转义 print("邹邹活了人生的%5") # 这句话中没有占位符. %还是%
结果:
zouzou活了人生的%2
邹邹活了人生的%5
name = input('name:') age = input('age:') job = input('job:') salary = input('salary:') info = ''' ----------------info fo %s------------ name:%s age:%s job:%s salary:%s ''' % (name, name, age, job, salary) print(info)
结果:
name = input('name:') age = input('age:') job = input('job:') salary = input('salary:') info = ''' ----------------info fo {_name}------------ name:{_name} age:{_age} job:{_job} salary:{_salary} '''.format(_name=name, _age=age, _job=job, _salary=salary) print(info)
结果:
name = input('name:') age = input('age:') job = input('job:') salary = input('salary:') info = ''' ----------------info fo {0}------------ name:{0} age:{1} job:{2} salary:{3} '''.format(name, age, job, salary) print(info)
结果:
for循环,range
range有一个参数:结束为止
两个参数: 1. 起始位置, 2.结束位置
三个参数: 1. 起始位置, 2. 结束位置. 3.步长
age_of_oldboy = 56 for i in range(3): guess_age = int(input('guess age:')) if guess_age == age_of_oldboy: print("yes, you got it. ") break elif guess_age > age_of_oldboy: print("think smaller...") else: print("thing bigger...") else: print("you have tried too many times...")
当for循环执行三次结束后执行else下的print。如果中途遇到break,就结束,不执行else下的print
for i in range(10): print(i) # 打印出了0,1,2,3,4,5,6,7,8,9 for i in range(0, 10, 3): print(i) # 打印出了0,3,6,9,也就是步长为3,默认为1.
age_of_oldboy = 56 count = 0 while count < 3: guess_age = int(input('guess age:')) if guess_age == age_of_oldboy: print("yes, you got it. ") break elif guess_age > age_of_oldboy: print("think smaller...") else: print("thing bigger...") count = count + 1 if count == 3: countine_confirm = input('是否需要继续下去,n键退出,其余键继续') if countine_confirm != 'n': count = 0
当输入错三次是,会提示是否需要继续,如果是n就结束,其余键将count重新赋值0,每三次问一次,输对时直接结束