一 字符串拼接方式
1. 用加号(+)拼接
name = ‘eason‘ age = 18 info = ‘‘‘---info:‘‘‘+ name +‘‘‘ age: ‘‘‘ + str(age) print(info)
2. 用占位符(%)拼接
name = "eason" age = 18 info = ‘‘‘-----info----- name: %s age: %d ‘‘‘ % (name,age) print(info)
3. 用format方法拼接
1.关键字拼接(官方推荐) name = "eason01" age = 19 info = ‘‘‘-----info---- name: {_name} age:: {_age} ‘‘‘.format(_name = name,_age = age) print(info) 2.占位符拼接 name = "eason02" age = 20 info = ‘‘‘-----info----- name: {0} age: {1} ‘‘‘.format(name,age) print(info)
二 表达式if...else...
场景一:用户登录验证
name = input("请输入用户名:") pwd = input("请输入密码:") if name == "alex" and pwd == "cmd": print("欢迎,alex!") else: print("用户名密码错误!")
场景二:猜年龄游戏
age_of_oldboy = 22 guess_age = int(input("guess age:")) if guess_age == age_of_oldboy: print("yes,you got it !") elif guess_age < age_of_oldboy: print("think bigger!") else: print("think smaller!")
三 表达式for loop
最简单的循环10次
for i in range(10): print("loop:", i )
需求一,遇到小于5的循环次数就不走了,直接进入下一次循环
for i in range(0,10,2): #0 初始化值,10 序列长度, 2 步长 if i < 5: continue #不往下走了,直接进入下一次loop print("loop",i)
需求二,遇到大于5的循环次数就不走了,直接退出
for i in range(10): #默认初始化值 0 ,步长为 1 if i > 5: break # 不往下走了,直接跳出当前整个loop print("loop",i)
四 表达式while
count = 0 while True: print("11111",count) count += 1 if count == 100: print("2222") break
如何实现让用户不断的猜年龄,但只给最多3次机会,再猜不对就退出程序
my_age = 25 count = 0 while count < 3: user_input = int(input("input your guess num:")) if user_input == my_age: print("you got it!") break elif user_input < my_age: print("think bigger!") else: print("think smaller!") count += 1 else: print("you have tied too many times...")
注:当遇到不正常退出(break)时,则程序不执行循环(for,while)所对应的else下的代码,只有当for循环体中代码正常执行的时,才执行else中的代码
更多python资料:猛击这里