结构判断是几乎所有编程语言中最重要的方面。在此,将根据特定条件的有效性做出决定。条件检查是决策的基础。
在python中,决策由以下语句执行。
Statement | Description |
---|---|
If 语句 | if语句用于测试特定条件。如果条件为真,将执行一个代码块(if-block)。 |
If - else 语句 | if-else语句与if语句类似,如果if语句中提供的条件为false,则将执行else语句。 |
嵌套 if 语句 | 嵌套的if语句使能够使用if? 外部if语句内部的else语句。 |
为了简化编程并简化操作,python不允许在块级代码中使用括号。在Python中,缩进用于声明一个块。如果两个语句处于相同的缩进级别,则它们是同一块的一部分。通常,给定四个空格以使语句缩进,这是python中典型的缩进量。
if语句用于测试特定条件,如果条件为true,它将执行称为if-block的代码块。 if语句的条件可以是可以评估为true或false的任何有效逻辑表达式。
下面给出if语句的语法。
链接:https://www.learnfk.comhttps://www.learnfk.com/python3/python-if-else.html
来源:LearnFk无涯教程网
if expression: statement
输出:
enter the number?10 Number is even
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语句提供一个else块与if语句组合,该if语句在条件为假的情况下执行。
如果条件为真,则执行if块。否则,执行else块。
下面给出了if-else语句的语法。
if condition: #block of statements else: #another block of statements (else-block)
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 !!
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语句的工作方式类似于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
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
marks = int(input("Enter the marks? ")) if marks > 85 and marks 60 and marks 40 and marks 30 and marks
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)