温馨提示:本文最后更新于
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 / 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 中常见的逻辑运算符,如下所示
名称 | 符号 | 例子 |
---|---|---|
与 | 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
暂无评论内容