Python3 - If语句

Python3 - If语句 首页 / Python3入门教程 / Python3 - If语句

结构判断是几乎所有编程语言中最重要的方面。在此,将根据特定条件的有效性做出决定。条件检查是决策的基础。

在python中,决策由以下语句执行。

StatementDescription
If 语句if语句用于测试特定条件。如果条件为真,将执行一个代码块(if-block)。
If - else 语句if-else语句与if语句类似,如果if语句中提供的条件为false,则将执行else语句。
嵌套 if  语句嵌套的if语句使能够使用if? 外部if语句内部的else语句。

缩进

为了简化编程并简化操作,python不允许在块级代码中使用括号。在Python中,缩进用于声明一个块。如果两个语句处于相同的缩进级别,则它们是同一块的一部分。通常,给定四个空格以使语句缩进,这是python中典型的缩进量。

if 语句

if语句用于测试特定条件,如果条件为true,它将执行称为if-block的代码块。 if语句的条件可以是可以评估为true或false的任何有效逻辑表达式。

Python If-else statements

下面给出if语句的语法。

链接:https://www.learnfk.comhttps://www.learnfk.com/python3/python-if-else.html

来源:LearnFk无涯教程网

if expression:
	statement

例子1

num = int(input("enter the number?"))
if num%2 == 0:
    print("Number is even")

输出:

enter the number?10
Number is even

示例2:程序打印三个数字中最大的一个。

a = int(input("Enter a? "));
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b and a>c:
    print("a is largest");
if b>a and b>c:
    print("b is largest");
if c>a and c>b:
    print("c is largest");

输出:

Enter a? 100
Enter b? 120
Enter c? 130
c is largest

if-else语句

if-else语句提供一个else块与if语句组合,该if语句在条件为假的情况下执行。

如果条件为真,则执行if块。否则,执行else块。

Python If-else statements

下面给出了if-else语句的语法。

if condition:
	#block of statements 
else: 
	#another block of statements (else-block) 

例子1 : 检查某人是否有资格投票

age = int (input("Enter your age? "))
if age>=18:
    print("You are eligible to vote !!");
else:
    print("Sorry! you have to wait !!");

输出:

Enter your age? 90
You are eligible to vote !!

示例2:检查数字是否为偶数

num = int(input("enter the number?"))
if num%2 == 0:
    print("Number is even...")
else:
    print("Number is odd...")

输出:

enter the number?10
Number is even

elif语句

elif语句使无涯教程能够检查多个条件并根据其中的真实条件执行特定的语句块,使用elif是可选的。

elif语句的工作方式类似于C中的if-else-if阶梯语句。它必须由if语句后接。

if expression 1: 
	# block of statements 

elif expression 2: 
	# block of statements 

elif expression 3: 
	# block of statements 

else: 
	# block of statements
Python If-else statements

例子1

number = int(input("Enter the number?"))
if number==10:
    print("number is equals to 10")
elif number==50:
    print("number is equal to 50");
elif number==100:
    print("number is equal to 100");
else:
    print("number is not equal to 10, 50 or 100");

输出:

Enter the number?15
number is not equal to 10, 50 or 100

例子2

 marks = int(input("Enter the marks? "))
if marks > 85 and marks  60 and marks  40 and marks  30 and marks 

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

从0开始学架构 -〔李运华〕

深入浅出计算机组成原理 -〔徐文浩〕

To B市场品牌实战课 -〔曹林〕

Python自动化办公实战课 -〔尹会生〕

说透芯片 -〔邵巍〕

讲好故事 -〔涵柏〕

说透元宇宙 -〔方军〕

大厂设计进阶实战课 -〔小乔〕

云计算的必修小课 -〔吕蕴偲〕

好记忆不如烂笔头。留下您的足迹吧 :)