目录
3.range定义一个1-100的奇数数组,for循环求出数组的和
基本运算符
比较运算符
赋值运算符
多变量赋值
a, b, c = 1, 2, 3
# a = b = c = 3
print(b, c)
逻辑运算符
案例:
假设对成长速度显示规定如下:
成长速度为5显示等级1;
成长速度为10显示等级2;
成长速度为12显示等级3;
成长速度为15显示等级4;
其他都显示都显示等级0;实现方案有三种
# 方法1:常规if实现
# 方法2:通过逻辑运算符实现
# 方法3:通过字典来实现
案例实现源码如下
# 方法1:常规if实现
# speed = int(input("请输入成长值"))
# level = 0;
# if speed == 5:
# level = 1
# elif speed == 10:
# level = 2
# elif speed == 12:
# level = 3
# else:
# level = 0
# print(f"当前等级为{level}")# 方法2:通过逻辑运算符实现
# speed = int(input("请输入成长值"))
# level = (speed == 5 and 1) or \
# (speed == 10 and 2) or \
# (speed == 12 and 3) or 0
# print(f"当前等级为{level}")# 方法3:通过字典来实现
speed = int(input("请输入成长值"))
obj = {
5: 1,
10: 2,
12: 3
}
level = obj.get(speed, 0)
print(f"当前等级为{level}")
三元运算符
# 三元运算符 a = 2 b = 3 # c = a > b ? a : b java c = a if a > b else b; print(c)
条件语句
剪刀 1 石头 2 布 3
import random p = int(input("请输入剪刀 0 石头 1 布 2")) c = random.randint(0, 2) data = ["剪刀", "石头", "布"] print(f"玩家出{data[p]},电脑出{data[c]}") # # 方法1.传统做法 # if p == c: # print("平局") # elif p == 0: # if c == 1: # print("玩家输") # elif c == 2: # print("玩家赢") # elif p == 1: # if c == 2: # print("玩家输") # elif c == 0: # print("玩家赢") # elif p == 2: # if c == 0: # print("玩家输") # elif c == 1: # print("玩家赢") # print(f'电脑输出{c}') # 方案2 win = 0 if c + 1 > 2 else c + 1 if p == win: print("玩家赢") elif p == c: print("平局") else: print("玩家输")
循环语句
1.while循环计算0-100的求和
2.for循环数组求和
3.range定义一个1-100的奇数数组,for循环求出数组的和
4.while...else...语法
1.计算0-100的求和
# i = 0;
# sum = 0;
# while i != 100:
# i += 1
# sum += i
# print(sum)
2.for循环数组求和
# arr = [1,2,3,4,5,6,7,8,9,10]
# sum = 0
# for i in arr:
# sum += i
# print(sum)
3.range定义一个1-100的奇数数组,for循环求出数组的和
# arr = range(101)[1::1]
# sum = 0
# for i in arr:
# sum += i
# print(sum)
4.while...else...语法
# i = 1 # while i <= 5: # print('老师,我错了') # i += 1 # break # print('老师原谅我了') """ 1. 书写道歉的循环 2. 循环正常结束要执行的代码---else """ # i = 1 # while i <= 5: # print('老师,我错了') # i += 1 # break # else: # print('老师原谅我了,哈哈哈') i = 1 while i <= 5: if i == 3: print('这遍道歉说的不真诚') break print('老师,我错了') i += 1 else: print('老师原谅我了,哈哈哈')