Python if else和elif是程序中条件逻辑的关键字。在本教程中,我们将学习pythonif
, else
and elif
. Previously we learned about Python运算符和优先级.
Python if else&条件逻辑
到目前为止,我们处理的是一个静态决策程序。这意味着在我们的程序中,我们不必在任何选项中进行选择。但是如果我们必须让我们的程序在不同的条件下表现不同呢。这就是我们将使用条件逻辑的地方。所以条件逻辑就是我们如何在程序中做出逻辑决定。
为了实现条件逻辑,Python的关键字是if
, else
and elif
.
Python if
假设我们要写一个程序,它将决定一个数是奇数还是偶数。如果数字是奇数,我们要打印–;“;数字是奇数”;如果数字是偶数,我们要打印–;“;数字是偶数”;。我们可以用if
keyword.
n=input() #take a input from user
n=int(n) #typecast the raw input into integer
#check if n is odd or even
#logic for odd/even is-
#if we divide an even number by 2, the remainder will be zero
#if we divide an odd number by 2, the remainder will be one
#we can perform this logic with modulus operator (%)
if n%2==0: #(n%2) is the remainder.Check if it"s zero
print("the number is even")
if n%2==1: #Check the remainder is one
print("the number is odd")
如果我们执行这个程序并输入2,输出将如下图所示。
同样,如果我们再次运行这个程序并给出输入3,输出将如下所示。
很酷,对吧?好像我们做了一个情报*
Python else
好吧,在上述情况下,我们提出的条件,n%2
, which has only two possible outcome. Either it’s zero or one. So here we can use else
for the second condition. In that case we don’t have to write the second condition manually. We can write the first condition using a if
and use else
for other case.
n=input() #take a input from user
n=int(n) #typecast the raw input into integer
#check if n is odd or even
#logic for odd/even is-
#if we divide an even number by 2, the remainder will be zero
#if we divide an odd number by 2, the remainder will be one
#we can perform this logic with modulus operator (%)
if n%2==0: #(n%2) is the remainder.Check if it"s zero
print("the number is even")
else: #this will consider every other case without the above-mentioned condition in if
print("the number is odd")
Python elif
如果我们必须编写一个程序来处理三个或更多的条件呢。假设,您必须从用户处获取一个数字,并考虑以下三种情况。
- 如果数字在1到10之间–;打印“;太低”;
- 如果数字在11到20之间–;打印“;中”;
- 如果数字在21到30之间–;打印“;大”;
- 如果数字大于30–;打印“;太大”;
因此,在这个场景中,我们必须使用if
for the first condition and else
for the last condition. That much we know till now. So what about the other two? We will use elif
to specify the other condition just like if
.
n=input() #take a input from user
n=int(n) #typecast the raw input into integer
#Check If the number is between 1 to 10
if n>=1 and n<=10:
print("too low");
#Check If the number is between 11 to 20
elif n>=11 and n<=20:
print("medium");
#Check If the number is between 21 to 30
elif n>=21 and n<=30:
print("large");
#Check if the number is greater than 30
else:
print("too large")
如果我们分别对值3,15,23,45运行这个程序,输出将如下所示-
所以,这就是Python中的条件逻辑。确保你自己运行每一段代码。另外,一个更好的做法是自己解决一些问题。#happy_编码*