1.条件判断
- 1.1 条件判断语句(if语句)
*执行的流程:
+ if语句在执行时,会先对条件表达式进行求值判断,
+ 如果为True,则执行if后的语句。
+ 如果为False,则不执行。
比如:- 语法:if 条件表达式 :
代码块 - 代码块代码块中保存着一组代码,同一个代码块中的代码,要么都执行要么都不执行
- 代码块以缩进开始,直到代码恢复到之前的缩进级别时结束
- 代码块就是一种为代码分组的机制
- 语法:if 条件表达式 :
a = 4
if a > 3:
print("hello world")
- 1.2 input() 函数
- 该函数用来获取用户的输入
- input()调用后,程序会立即暂停,等待用户输入
- 用户输入完内容以后,点击回车程序才会继续向下执行
- 用户输入完成以后,其所输入的的内容会以返回值得形式返回
1.
- 1.3 if-elif-else 语句
month = int(input('请输入月份:')) if month == 3 or month == 4 or month == 5: print('春节') elif 6<= month <=8: print('夏季') elif 9<= month <=11: print('秋季') elif month == 12 or month == 1 or month == 2: print('冬季') else: print('我也不知道是什么季节')
- 语法:
if 条件表达式 :
代码块
elif 条件表达式 :
代码块
elif 条件表达式 :
代码块
…
else :
代码块 - 执行流程:
-if-elif-else语句在执行时,会自上向下依次对条件表达式进行求值判断,- 如果表达式的结果为True,则执行当前代码块,然后语句结束
- 如果表达式的结果为False,则继续向下判断,直到找到True为止
- 如果所有的表达式都是False,则执行else后的代码块
- 总结: if-elif-else中只会有一个代码块会执行
- 1.4 while语句 - 循环语句可以使指定的代码块重复指定的次数.循环语句分成两种,while循环 和 for循环
- 语法:
while 条件表达式 :
代码块
else:
代码块
- 语法:
a = 0
while a < 10:
print('好好')
a += 1
else:
print('哈哈')
# 2.求100以内(包括100)所有的偶数之和
# 首先可以拿到1-100的所有的数
# 拿到偶数
# 再相加
g = 0
i = 0
while i < 100:
i += 2
g += i
print(g)
- 1.5 循环嵌套
- Python 语言允许在一个循环体里面嵌入另一个循环。
while 表达式:
while 表达式:
代码块
代码块
例:99乘法表
count = 0
while count < 9:# 控制的行
j=0
count += 1
while j < count:# 控制的排
j += 1
print(f'{j}*{j}', end=' ')
print()
- ** 1.6 break和continue**
- 1.contine:
用来跳过当次循环
- 1.contine:
流程图:
实例:
i = 0
while i < 10:
if i == 3:
continue
print(i)
i += 1
else:
print('循环结束')
- 3.break
1.图例:
2.实例:
i = 0
while i < 10:
i += 1
if i == 3:
break
print(i)
else:
print('循环结束')
作业
- 1
# import random
# 1.求1000以内所有的水仙花数
# 水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身(例如:1^3 + 5^3 + 3^3 = 153)
i = 100
while i<1000:
g = i%10
s = i%100//10
b = i//100
k = g**3+s**3+b**3
if i == k:
print(k)
i += 1
- 2
user_num = int(input('请输入数字:'))
i = 1
while i <= user_num:
if user_num % i == 0 and user_num != i and i != 1:
print('这不是质数')
break
else:
if i < user_num:
i += 1
continue
else:
print('质数')
break
3.简单版
# 1. 猜拳游戏:
# • 出拳 玩家:手动输入 电脑:随机输入
# • 判断输赢: 玩家获胜 电脑获胜 平局
# 拳头(0) 剪刀(1) 布(2)
import random
user = int(input('请打出你的选择:'))
computer = random.randint(0,2)
while True:
if user == computer:
print('平局')
break
elif (user == 0 and computer == 1) or (user == 1 and computer == 2) or (user == 2 and computer == 0):
print('玩家获胜')
break
else:
print('电脑获胜')
break
注:random
import random
print( random.randint(1,10) ) # 产生 1 到 10 的一个整数型随机数
print( random.random() ) # 产生 0 到 1 之间的随机浮点数
print( random.uniform(1.1,5.4) ) # 产生 1.1 到 5.4 之间的随机浮点数,区间可以不是整数
print( random.choice('tomorrow') ) # 从序列中随机选取一个元素
print( random.randrange(1,100,2) ) # 生成从1到100的间隔为2的随机整数
a=[1,3,5,6,7] # 将序列a中的元素顺序打乱
random.shuffle(a)
print(a)