blog/docs/code/python/if.md

87 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 控制流 If
date: 2020-09-5 17:25:10
tags: [Python]
categories: [Python]
author: Anges黎梦
---
> 首先,我们可以根据英文的意义来理解一下
>
> 如果 xxx 就 xxx
>
> 那么在写if控制语句时可以按照这个思路来编写相关代码
### **if** 语句的语法
我们通过代码例子来看一下 **if** 语句的语法
**示例代码**
```python
a = 1
if a==1:
# 如果a = 1那么执行下面的语句
print(a)
else:
# 如果a 不等于1 那么执行下面的语句
print(a)
# 多个判断条件可以添加 elif 来判断
if a==1:
print(1)
elif a==2:
print(2)
elif a==3:
print(3)
else:
print(a)
```
### 逻辑运算符
#### 比较
- " > " 大于
- " < " 小于
- " == " 等于
- " != " 不等于
- " <> " 两个对象是否不相等python3废弃
- " >= " 大于等于
- " <= " 小于等于
**示例代码**
```python
print(3>1) # True
```
#### 关键字比较
- and 左右两个语句同时为真
- or 左右两个语句只要有一个为真
- not 右边的语句取反
- in 包含
- not in 不包含
**示例代码**
```python
print(3>1 and 6>4) # True
print(3>1 and 6>8) # False
print(3>1 or 6>8) # True
```
**is not 用于比较两个对象的存储单元**
**x is y 判断引用的是否是同一个对象**
### isinstance
> 内置函数 isinstance 判断对象是否为一个已知类型
**示例代码**
```python
# 目标类型为一个类型
print(isinstance("str", str)) # True
# 目标类型为多个类型
print(isinstance([1,4,"a"], (list, tuple, set))) # True
```