逻辑运算符2(py.)

41 阅读2分钟

while循环基础

count = 1 # 初始值 while count <= 5: print("我在学习while循环") count +=1 # count = count + 1

累加计算

count = 1 # 初始值 total = 0 # 总和的初始值 while count <= 5: total += count # total = total + count print(count) count += 1 # count = count + 1 print("总和为: ",total)

喝水

cup = 1 # 初始值 target = 8 while cup <= target: print(f"喝了第{cup}杯水") cup += 1 print("喝水任务完成")

计算50以内所有能被7整除的数的和

count = 7 # 初始值 total = 0 # 总和的初始值 while count <= 50: total += count # total = total + count print(count) count += 7 # count = cout +n 7 print("总和为: ",total)

#计算100以内所有能被3和5整除的数的和 count = 7 # 初始值 total = 0 # 总和的初始值 while count <= 50: if count % 15 == 0: total += count # total = total + count print(count) count += 7 # count = count + 7 print("总和为:",total)

逻辑运算符

a = 0 b = 1 c = 0 d = 2

and

e = a and b e = b and a # 当左右两边有一个False值,则返回False的值 print(e) e = a and c e = b and d # 当左右两边都为False时, 则返回左边的值 print(e) e = b and d # 当左右两边都为True时, 则返回右边的值 print(e)

or

e = a or b e = b or a # 当左右两边有一个True时, 则返回True的值 e = a or c e = b or d # 当左右两边都为False时,则返回右边的值 print(e) e = b or d # 当左右两边都为True时, 则返回左边的值 print(e) ### 当有一个True时, 则返回遇到的第一个True值

not

e = not a e = not b print(e)

import random target = random.randint(1,10) guess = int(input("猜1-10之间的整数:"))

if guess > 10: print("猜的数大于范围1-10") elif guess < 1: print("猜的数小于范围1-10") else: if guess == target: print("猜对了") else: print("猜错了") if guess > target: print("猜大了") else: print("猜小了") print(target) print("游戏结束")

运行结果如下: image.png