**while 循环体:
循环是如我们生活中 吃饭,睡觉,歌曲的单去循环。
while 条件
循环体
# 1,初识循环|
while True:
print(‘海草’)
print(‘女儿情’)
print(‘二泉映月’)
print(‘牧马城市’)
如何终止循环
‘’’
1,改变条件。
2,break
3,调用系统命令:quit() exit() (不建议使用)
‘’’
flag = True
while flag:
print(‘海草’)
print(‘女儿情’)
flag = False
print(111)
print(222)
四个都打印
从 1 ~ 100 利用while循环
计数器的概念
count = 1
flag = True
while flag:
print(count)
count = count + 1
if count == 101:
flag = False
count = 1
while count < 101:
print(count)
count = count + 1
count = 1
count = 2
count = 3
print(count)
count = 1
count = count + 1
count = count + 1
print(count)
while break continue
break:循环中遇到break 直接退出循环,
print(111)
while True:
print(222)
print(333)
break
print(555)
print(666)
打印 1~100 所有的偶数。
方法一
count = 2
while count < 101:
print(count)
count = count + 2
count = 2
while True:
if count % 2 == 0:
print(count)
count = count + 1
if count > 100:
break
count = 2
while count < 101:
if count % 2 == 0:
print(count)
count = count + 1
continue
结束本次循环,继续下一次循环
while True:
if
print(111)
print(222)
continue
print(333)
计算 1 + 2 + 3 + 4 + 5 + …100 结果
s = 0
count = 1
while count < 101:
s = s + count
count = count + 1
print(s)
固定搭配: 循环只要被break打断,则就不会执行else的程序。
#while else
count = 1
while count < 5:
count = count + 1
print(count)
else:
print(666)
count = 1
count < 5:
count = count + 1
print(count)
if count == 10:
break
else:
print(666)
格式化
name = input(‘请输入姓名:’)
age = input(‘请输入年龄:’)
job = input(‘请输入工作:’)
hobby = input(‘请输入爱好:’)
‘’’
这样做很麻烦,用格式化输出
s1 = '------------ info of ‘+ name + ’ -----------\n’
s2 = 'Name : ’ + name + ‘\n’
‘’’
# % 占位符 s:字符串类型 d:数字 i:数字 # r 原形毕露
msg = ‘’’------------ info of %s -----------
Name : %s
Age : %d
job : %s
Hobbie: %s
------------- end -----------------’’’ % (name,name,int(age),job,hobby)
print(msg)
格式化输出 如果你只是想要表示百分号%,而不是占位符。
msg = ‘我叫%s,今年%s岁,学习进度为0.5%%’ % (‘alex’, 40)
print(msg)
运算符
算术运算,赋值运算,比较运算,身份运算,位运算,逻辑运算等等。
算数运算: + - * / % ** //
比较运算: == > < >= <= !=
赋值运算: = += -= *= /= ....
count = count + 1 count += 1
逻辑运算:and or not
成员运算:in not in
例子:
逻辑运算
优先级
()>not>and> or,同一个优先级从左至右一次计算。
1,运算符两边全部是比较运算。
print(1 > 2 or 3 < 4 and 1 < 2 or 3 > 7)
print(1 > 2 or True or 3 > 7)
print(2 > 1 and 3 < 4 or 4 > 5 and 2 < 1)
print(1 > 2 and 3 < 4 or 4 > 5 and 2 > 1 or 9 <10)
2 ,运算符两边全部是数字。
‘’’
x or y if x is True, return x,else y
‘’’
print(1 or 3)
print(2 or 3)
print(10 or 3)
print(0 or 3)
print(-3 or 3)
print(1 and 3)
print(-1 and 3)
print(0 and 3)
#int bool
int —> bool 非0即True
print(bool(-2))
print(bool(2))
print(bool(0))
bool —> int True 1 Flase 0
print(int(True))
面试题:
print(1 and 3 or 4 and 5)
第三种,思考题:
print(1 > 2 or 3 and 4 < 5 or 7)
成员运算:
s = ‘alex 中’
s1 = ‘a’
s = ‘alexsb’