Python 条件语句是通过一条或多条语句的执行结果(True 或者 False)来决定执行的代码块。
可以通过下图来简单了解条件语句的执行过程:
代码执行过程:
Python 中用 elif 代替了 else if,所以if语句的关键字为:if – elif – else。
注意:
1、每个条件后面要使用冒号 :,表示接下来是满足条件后要执行的语句块。
2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
3、在Python中没有switch – case语句。
Gif 演示:
if 语句
Python中if语句的一般形式如下所示:
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
- 如果 “condition_1” 为 True 将执行 “statement_block_1” 块语句
- 如果 “condition_1” 为False,将判断 “condition_2”
- 如果"condition_2" 为 True 将执行 “statement_block_2” 块语句
- 如果 “condition_2” 为False,将执行"statement_block_3"块语句
if else 判断交流
判断用户名密码对不对。
import getpass
_username = 'devin'
_password = 'abc123'
username = input("username:")
#password = getpass.getpass("password:")
password = input("password:")
if _username == username and _password == password:
print("Welcome user {name} login...".format(name=username))
else:
print("Invalid username or password!")
注:判断语句,print需要\tab不可以与if并列。强制缩进。
if:条件语句
and:并且
or:或者
==:等于
else:如果不成立就执行下面
注:判断语句
elif:代表如果不成立或者的意思。
python3默认识别的是字符串,数字需要转换为int数字。
if 嵌套
在嵌套 if 语句中,可以把 if…elif…else 结构放在另外一个 if…elif…else 结构中。
if 表达式1:
语句
if 表达式2:
语句
elif 表达式3:
语句
else:
语句
elif 表达式4:
语句
else:
语句
实例:
num=int(input("输入一个数字:"))
if num%2==0:
if num%3==0:
print ("你输入的数字可以整除 2 和 3")
else:
print ("你输入的数字可以整除 2,但不能整除 3")
else:
if num%3==0:
print ("你输入的数字可以整除 3,但不能整除 2")
else:
print ("你输入的数字不能整除 2 和 3")