Python如果不是Elif

时间:2020-02-23 14:42:48  来源:igfitidea点击:

Python if else和elif是程序中条件逻辑的关键字。
在本教程中,我们将学习pythonifelseelif
先前我们了解了Python运算符和优先级。

Python否则-条件逻辑

好,到目前为止,我们已经处理了一个静态决策程序。
这意味着在我们的程序中,我们不必选择任何选项。
但是,如果我们必须使我们的程序在不同条件下表现不同,该怎么办。
那就是我们将使用条件逻辑的地方。
因此,条件逻辑是我们如何在程序中做出逻辑决策的方式。

为了实现条件逻辑,Python的关键字是" if"," else"和" elif"。

Python如果

假设我们要编写一个程序,它将确定数字是奇数还是偶数。
如果数字是奇数,我们要打印–"数字是奇数";如果数字是偶数,我们要打印–"数字是偶数"。
我们可以使用" if"关键字编写该程序。

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

Python其他

好了,在上述情况下,我们提出的条件为" n%2",它只有两个可能的结果。
或者是零,或者是一。
因此,在这里我们可以将" else"用于第二个条件。
在这种情况下,我们不必手动编写第二个条件。
我们可以使用if编写第一个条件,其他情况下使用else

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",对最后一个条件使用" else"。
到目前为止,我们还不知道这些。
那么其他两个呢?我们将使用" elif"来指定其他条件,就像" 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")