Python if语句的用法(附带实例)
计算机之所以能够自动完成任务,是因为它能够进行判断,根据不同的条件做出不同的响应,此功能的实现取决于编程语言的条件判断。
Python 程序中,可以用 if 语句实现条件判断。if 语句的关键字为 if elif else,在每个条件的后面均使用冒号(:)表示接下来满足条件且要执行语句块,使用缩进划分语句块。if 语句可以嵌套。
需要说明的是,和其它的编程语言不同(如 C语言、Java 等),Python 中没有 switch case 语句。
编写测试程序为:
在 Pyhton 中,if 语句常用的操作运算符如下表所示:
Python 程序中,可以用 if 语句实现条件判断。if 语句的关键字为 if elif else,在每个条件的后面均使用冒号(:)表示接下来满足条件且要执行语句块,使用缩进划分语句块。if 语句可以嵌套。
需要说明的是,和其它的编程语言不同(如 C语言、Java 等),Python 中没有 switch case 语句。
编写测试程序为:
number = int(input('Please input your number:')) if number == 1: print('This is if') elif number == 2: print('This is elif') else: print('This is else')执行 3 次,分别输入 1、2、3,可以看到,程序根据输入的不同,输出也不同:
Please input your number:1
This is if
Please input your number:2
This is elif
Please input your number:3
This is else
在 Pyhton 中,if 语句常用的操作运算符如下表所示:
运算符 | 含义 |
---|---|
== | 等于,两个对象相等 |
!= | 不等于 |
> | 大于 |
>= | 大于或等于 |
< | 小于 |
<= | 小于或等于 |
Python if语句嵌套
在 Python 中,if 语句可以嵌套 if 语句,编写下面的测试程序,分别输入 1、2、3、4 中的一个数字,通过程序可以判断识别输入的数字。var = int(input('Please input a number from 1 to 4:')) if var > 2: if var > 3: print('input number is 4') else: print('input number is 3') elif var < 2: print('input number is 1') else: print('input number is 2')运行结果为:
Please input a number from 1 to 4:1 input number is 1 Please input a number from 1 to 4:2 input number is 2 Please input a number from 1 to 4:3 input number is 3 Please input a number from 1 to 4:4 input number is 4