print(value, ..., sep=' ',end=' ') #默认空格分隔,最后一行打印换行
print(1,2,3,sep=' ', end='***')
isinstance 判断类型
print(isinstance(1,(int,str,bool)))
打印奇偶数
打印10以内奇数
for i in range(1,10,2): print(i)
打印10以内偶数
for i in range(0,10,2): print(i)
倒着打印10以内偶数
for i in range(8,-1,-2): print(i)
三元表达式
真值表达式 if 条件表达式 else 假值表达式
# 判断用户的输入的值,如果为空,输出"empty",否则输出该值 value = input('>>>') if value: print(value) else: print('empty') value = input('>>>') print(value if value else 'empty')
字符串拼接
str(1) + ',' + 'b' # 都转换成字符串拼接到一起 "{}-{}".format(1, 'a') # {}就是填的空,有2个,就使用2个值填充 # 在3.6后,可以使用插值 a = 100; b = 'abc' f'{a}-{b}' # 一定要使用f前缀,在大括号中使用变量名
print(str(1) + ',' + 'b') 1,b print("{}-{}".format(1,'a')) 1-a a = 100 b = 'bc' print(f'{a}-{b}') 100-bc
实战:
1.打印九九乘法表
for i in range(1,10): for j in range(1,i+1): print('{}*{}={} '.format(j,i,j*i),end='') print(' ')
2.账号密码登录
user = 'jerry' password = '123456' count = 3 for i in range(1,count+1): input_user = input('账号:') input_password = input('密码:') if input_user == user and input_password == password: print(input_user + " login success") break else: if i < count: print('user or password is wrong') else: print('wbrong > ' + str(count)) break
username = 'tom' password = 'tom' wrongtimes = 0 while True: if wrongtimes < 3: u = input('Input your username: ') p = input('Input your password: ') if username == u and password == p: print('login successfully') wrongtimes = 0 break else: print('Invalid username or password') wrongtimes += 1 else: print('failed') break