上篇:Python基础知识(一):数据类型,格式化输出,运算符
目录
if 语句
if True:
print("执行")
注意:if 语句的条件后添加冒号(:)
age = int(input("请输入你的年龄:"))
if age >= 18:
print("你已经成年")
if ... else
注意:else 后面需要添加冒号(:)
age = int(input("请输入你的年龄:"))
if age >= 18:
print("你已经成年")
else:
print("你未成年")
if ... elif ... else
if age < 18:
print("童工")
elif age <= 60:
print("合法工作年龄")
else:
print("退休")
if 嵌套
age = int(input("请输入你的年龄:"))
if age < 18:
print("童工")
elif age <= 60:
print("合法工作年龄")
wantWork = int(input("你是否想工作了吗"))
if wantWork == 1:
print("想工作了")
else:
print("不想工作")
else:
print("退休")
三目运算符
语法
条件成立的表达式 if 条件 else 条件不成立的表达式
a = 1
b = 2
c = a if a > b else b
print(c)
while循环
i = 0
while i < 5:
print("我要睡觉了zzz~")
i += 1
效果
1-100累加
i = 1
res = 0
while i <= 100:
res += i
i += 1
print(res)
效果
1-100偶数累加
i = 1
res = 0
while i <= 100:
if i % 2 == 0:
res += i
i += 1
print(res)
或
i = 0
res = 0
while i <= 100:
res += i
i += 2
print(res)
效果
break和continue
break 终止循环
continue 退出本次循环,继续下次循环
break
i = 1
while i <= 5:
if i == 4:
print("太累了,不做了")
break
print(f"做{i}个俯卧撑")
i += 1
效果
continue
i = 0
while i < 5:
i += 1
print(f"做{i}个俯卧撑")
if i == 3:
print("休息一下,等下再做")
continue
效果
while循环嵌套
i = 0
while i < 3:
i += 1
print(f"第{i}天")
j = 0
while j < 3:
j += 1
print(f"做{j}个俯卧撑")
效果
for 循环
str1 = "hello"
for i in str1:
print(i)
效果
break
str1 = "hello"
for i in str1:
if i == 'l':
break
print(i)
效果
continue
str1 = "hello"
for i in str1:
if i == 'l':
continue
print(i)
效果
while ... else
else下方缩进代码指的是当循环正常结束之后要执行的代码
while循环时遇到break结束时,不会执行else代码
正常情况
i = 1
while i <= 5:
print(f"做{i}个俯卧撑")
i += 1
else:
print("给你个奖励")
效果
添加continue情况
i = 0
while i < 5:
i += 1
print(f"做{i}个俯卧撑")
if i == 3:
print("休息一下,等下再做")
continue
else:
print("给你个奖励")
效果
添加break情况
i = 1
while i <= 5:
if i == 4:
print("太累了,不做了")
break
print(f"做{i}个俯卧撑")
i += 1
else:
print("给你个奖励")
效果
for ... else
与while ... else情况相同,遇到break结束时,不会执行else代码
下篇:Python基础知识(三):字符串