Python3_条件控制语句【IF判断语句】

Python 条件语句是通过一条或多条语句的执行结果(True 或者 False)来决定执行的代码块。

可以通过下图来简单了解条件语句的执行过程:

代码执行过程:

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"块语句
Python 中用 elif 代替了 else if,所以if语句的关键字为:if – elif – else.

注意:

1、每个条件后面要使用冒号 :,表示接下来是满足条件后要执行的语句块。
2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
3、在Python中没有switch – case语句.

#!/usr/bin/python3

age = int(input("请输入你家狗狗的年龄: "))
print("")
if age <= 0:
        print("你是在逗我吧!")
elif age == 1:
        print("相当于 14 岁的人。")
elif age == 2:
        print("相当于 22 岁的人。")
elif age > 2:
        human = 22 + (age -2)*5
        print("对应人类年龄: ", human)

### 退出提示
input("点击 enter 键退出")

###以下为if中常用的操作运算符:

if 嵌套

在嵌套 if 语句中,可以把 if...elif...else 结构放在另外一个 if...elif...else 结构中。

if 表达式1:
    语句
    if 表达式2:
        语句
    elif 表达式3:
        语句
    else:
        语句
elif 表达式4:
    语句
else:
    语句

#eg.例子

# !/usr/bin/python3

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")

#!/usr/bin/python
# -*- coding: utf-8 -*-
#Author: zhaosj

# ###判断语句###
# if condition:
#     do
# else:
#     do
# #注意:冒号和缩进
# if condition:
#     do
# elif condition:
#     do
# else:
#     do
++++++++++++++++++++++++++++++++++++++++++++
#eg.:密码登录判断

#定义确认登录函数
def count_login():
    password = input('password:')
    if password == 123456:
        print ('输入成功!')
    else:
        print ('输入错误!请再次输入')
        count_login()

#函数调用
count_login()

#执行结果:

[root@bigdata script_ce]# python zhaosj_if.py 
password:123
输入错误!请再次输入
password:12345
输入错误!请再次输入
password:123456
输入成功!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值