一、格式化输出
需求格式化输出:姓名、年龄、工作、爱好
# 格式化输出 name = input('请输入用户名:') age = input('请输入年龄:') job = input('请输入你的工作:') hobbies = input('你的爱好是:') info = ''' -------------info of %s------------ # %s占位符,代表是后面括号里的name Name ; %s Age ; %s Job ; %s Hobbies ; %s ---------------end----------------- ''' % (name, name, age, job, hobbies) # 这里的%是将前面字符串与后面的括号内的变量关联起来 print(info)
结果为:
-------------info of Chris------------ # %s占位符,代表是后面括号里的name Name ; Chris Age ; 27 Job ; IT Hobbies ; girl ---------------end-----------------
如果格式化输出里含有%,需要用%%来表示。
# 特殊情况 name = 'Chris' school = 'OldBoy' msg = ''' 我是%s,就读于%s,学习进度1%% '''% (name, school) # 第一个%是对第二个%的转译,告诉Python解释器这只是一个单纯的%,而不是占位符。 print(msg)
二、基本的运算符
运算符
计算机可以进行的运算有很多种,可不只加减乘除这么简单,运算按种类可分为算数运算、比较运算、逻辑运算、赋值运算、成员运算、身份运算、位运算,今天我们暂只学习算数运算、比较运算、逻辑运算、赋值运算
算数运算
以下假设变量:a=10,b=20
比较运算
以下假设变量:a=10,b=20
赋值运算
以下假设变量:a=10,b=20
逻辑运算
针对逻辑运算的进一步研究:
1,在没有()的情况下not 优先级高于 and,and优先级高于or,即优先级关系为( )>not>and>or,同一优先级从左往右计算。
# 基本运算符 print(3 > 4 or 4 < 3 and 1 == 1) # False print(1 < 2 and 3 < 4 or 1 > 2) # True print(2 > 1 and 3 < 4 or 4 > 5 and 2 < 1) # True print(1 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6) # False print(not 2 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6) # False
2 , x or y , x为真,值就是x,x为假,值是y;
x and y, x为真,值是y,x为假,值是x 。
# 求逻辑运算的值 print(8 or 4) # 8 print(0 and 3) # 0 # 0 意味着是假 print(0 or 4 and 3 or 7 or 9 and 6) # 3
三、流程控制---while语句
1、while 条件:
语句块
# 如果条件为真,则执行语句块
# 如果条件为假,则不执行语句块
2、循环中止语句
如果在循环的过程中,因为某些原因,你不想继续循环了,怎么把它中止掉呢?这就用到break 或 continue 语句
- break用于完全结束一个循环,跳出循环体执行循环后面的语句
- continue和break有点类似,区别在于continue只是终止本次循环,接着还执行后面的循环,break则完全终止循环
例子:break
# while语句
count = 1
while True:
print('--->',count)
count += 1
if count == 6:
break
结果:
---> 1 ---> 2 ---> 3 ---> 4 ---> 5
例子:continue 的用法
# continue的用法 count = 0 while count < 10: count += 1 if 3 <= count <= 8: continue print('--->', count)
结果:
---> 1 ---> 2 ---> 9 ---> 10
3、while ... else ..
与其它语言else 一般只与if 搭配不同,在Python 中还有个while ...else 语句
while 后面的else 作用是指,当while 循环正常执行完,中间没有被break 中止的话,就会执行else后面的语句
# while...else 语句用法 count = 0 while count < 5: count += 1 print(count) else: print('程序执行完成了!')
执行结果为:
1
2
3
4
5
程序执行完成了!
while 后面的else 作用是指,当while 循环正常执行完,中间被break 中止的话,就不会执行else后面的语句
count = 0 while count < 5: count += 1 if count == 3: break print(count) else: print('程序结束!')
结执行果为:
1 2