Day 3 – 控制流域逻辑操作符

Day 3 – 控制流域逻辑操作符

温馨提示:本文最后更新于2024-12-10 16:38:18,某些文章具有时效性,若有错误或已失效,请在下方留言

比较运算符

常见的比较运算符如下所示

常见的比较运算符
操作符 含义
> 大于
< 小于
>= 大于等于
<= 小于等于
== 等于
!= 不等于

条件语句

if / else 语句

条件语句的语法如下所示

if condition:
  do this
else
  do this

示例代码

print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))

if height >= 120:
    print("You can ride the rollercoaster")
else:
    print("Sorry you have to grow taller before you can ride.")

示例代码条件语句的示意图

示例代码示意图

嵌套 if / else 语句

嵌套if语法如下所示

if condition:
  if another condition:
	do this
  else:
	do this
else
  do this

示例代码

print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))

if height >= 120:
    print("You can ride the rollercoaster")
    age = int(input("How old are you? "))
    if age <= 18:
        print("Please pay $7")
    else:
        print("Please pay $12")
else:
    print("Sorry you have to grow taller before you can ride.")

示例代码条件语句的示意图

嵌套 IF ELSE 示意图

if / elif /else 语句

基本的语法如下

if condition1:
  do A
elif condition2:
  do B
elif ...
else:
  do this

取余运算符

Python中取余运算符(Modulo Operator)的符号为百分号 %

print(10 % 3) # 1

# 奇偶数检测
if num % 2 == 0:
  print("Even Number")
else:
  print("Odd Number")

逻辑运算符

Python 中常见的逻辑运算符,如下所示

Python的逻辑运算符
名称 符号 例子
and A and B
or C or D
not not E

示例代码

a = 12
b = 2
# 与
a > 10 and b > 3 # False
# 或
a > 10 or b > 3 # True
# 非
not a > 10 # False
© 版权声明
THE END
喜欢就支持一下吧
点赞1 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容