1 条件语句
1.1 if 语法
语法:if 条件成立,则执行 if 下面的代码
if 条件 :
条件成立执行代码1
条件成立执行代码2
age = int(input('请输入你的年龄:'))
if age >= 18:
print(f'你的年龄是{age},已经成年,可以上网')
print('系统关闭')
1.2 if…else… 语法
语法:若条件成立,执行 if 下方的代码;条件不成立,执行 else 下方的代码
if 条件 :
条件成立执行代码1
else :
条件不成立执行代码2
age = int(input('请输入你的年龄:'))
if age >= 18:
print(f'你的年龄是{age},已经成年,可以上网')
else:
print(f'你的年龄是{age},回家写作业去')
print('系统关闭')
1.3 多重判断
语法:若条件成立,执行 if 下方的代码;条件不成立,执行 else 下方的代码
if 条件1 :
条件1成立执行代码1
elif 条件2 :
条件2成立执行代码2
else :
以上条件不成立执行代码
age = int(input('请输入你的年龄:'))
if age < 18:
print(f'你的年龄是{age},童工')
elif (age>=18) and (age<=60) :
print(f'你的年龄是{age},合法')
elif age > 60:
print(f'你的年龄是{age},该退休了')
1.4 if 嵌套
语法:
if 条件1 :
条件1成立执行代码1
if 条件2 :
条件2成立执行代码2
else :
以上条件不成立执行代码
money = 0
seat = 1
if money == 1 :
print('土豪请上车')
if seat == 1 :
print('土豪请上座')
else :
print('你站着吧')
else :
print('没带钱就跑步吧')
1.5 猜拳游戏
random模块:产生随机数
import random
num = random.randint(0,2)
print(num)
import random
player = int(input('请出拳:0--石头,1--剪刀,2--布'))
computer = random.randint(0,2)
if ((player == 0) = (computer == 1) or (player == 1) = (computer == 2) or (player == 2) = (computer == 0))
print('玩家获胜!')
elif player == computer
print('平局,再来一局!')
else :
print('电脑获胜!')
1.6 三目运算符
语法:条件成立执行的表达式 if
条件 else
条件不成立执行的表达式
a = 1
b = 2
c = a if a > b else c = b
print(c)
2 循环语句
2.1 while 语法
语法:
while 条件1 :
条件成立执行代码1
i = 0
while i < 5:
print('媳妇,我错了')
i += 1
print('原谅你了')
- 应用1:1-10数字的累加计算
i =1
result = 0
while i <= 10:
result = result + i
i += 1
print(result)
- 应用2:1-10偶数数字的累加计算
i =1
result = 0
while i <= 10:
if i % 2 == 0
result = result + i
i += 1
print(result)
i = 1
result = 0
while i <= 10:
result += i
i += 2
print(result)
2.2 break
和 continue
2.2.1 break:终止整个循环
i = 1
while i < =5:
if i == 3:
print('吃饱了,不吃了')
break
print(f'吃了第{i}个苹果')
i += 1
2.2.2 continue:退出当前循环,继续下一次循环
i = 1
while i < =5:
if i == 3:
print('这个苹果有虫子,不吃这个')
continue
print(f'吃了第{i}个苹果')
i += 1
2.3 while 循环嵌套
语法:
while 条件1 :
条件成立执行代码1
while 条件2 :
条件成立执行代码2
i = 0
while i < 3:
j = 0
while j < 3:
print('媳妇我错了')
j += 1
print('刷今天的晚,一套惩罚结束')
i += 1
应用1:打印星号(正方形)
i = 0
while i < 5:
j = 0
while j < 5:
print('*',end='')
j += 1
#一行星星打印结束,换下一行
print() #作用是换行
i += 1
应用2:打印星号(三角形)
i = 0
while i < 5:
j = 0
while j <= i:
print('*',end='')
j += 1
#一行星星打印结束,换下一行
print() #作用是换行
i += 1
应用3:打印九九乘法表,注意对齐
i = 0
while i < 9:
j = 0
while j <= i:
print(f'{i} * {j} = {i*j}',end='\t') # \t 的作用是对齐
j += 1
#一行表达式打印结束,换下一行
print() #作用是换行
i += 1
2.4 for 循环
语法:
for 临时变量 in 序列 :
重复执行代码1
str = 'hello'
for i in str:
print(i)
注意:break 和 continue 都可以退出 for 循环
2.5 嵌套用法
2.5.1 while 与 else(break与continue)
语法:
while 条件:
条件成立执行的代码
else:
循环正常结束执行的代码
i = 1
while i < 5:
print('媳妇我错了')
i += 1
else:
print('媳妇原谅我了')
2.5.2 for 与 else(break与continue)
语法:
for 临时变量 in 序列:
重复执行的代码
else:
循环正常结束执行的代码
str = 'hello'
for i in str:
print(i)
else:
print('循环结束了')