Python basic-09 conditional statement

9. Conditional statement

9.1 basic grammar

                                

1. Basic format

if condition:
   doSomething
elif condition:
   doSomething
   
   ...
   
else:
   doSomething

2. Nesting format

if condition:
   if condition:
      doSomething
   else: 
      doSomething
elif condition:
   if condition:
      doSomething
   elif condition:
      doSomething
   else: 
      doSomething
      
      ...
      
else
   if condition:
      doSomething
   else: 
      doSomething

Schematic diagram of basic variation form of   is as follows:


9.2 ternary operators

                      

[result = ] TrueResult if condition else FalseResult

For the children's shoes of                      .

9.3 dictionary implementation switch condition judgment

                            

def add(x:int,y:int)->int:
    print( x+y)

def sub(x:int,y:int)->int:
    print( x-y)

def mul(x:int,y:int)->int:
    print( x*y)

def div(x:int,y:int)->int:
    if y:
       print( x/y)

def simpleCaculator(operator:str,x:int,y:int)->None:
    dic={
        "+":add,
        "-":sub,
        "*":mul,
        "/":div,
    }
    return dic.get(operator)(x,y)

if __name__ == '__main__':
    simpleCaculator("+", 1, 2)
    simpleCaculator("-", 1, 2)
    simpleCaculator("*", 1, 2)
    simpleCaculator("/", 1, 2)

                     

3
-1
2
0.5

9.4 example code

The    example code is as follows:

tmpStr=int(input("Please enter a number:"))

if tmpStr<0:
    print("The number you entered is less than 0")
elif tmpStr<100:
    if 0<=tmpStr<=50:
         print("The number you entered is between[0,50]")
    elif 50<tmpStr<=100:
        print("The number you entered is between(50,100]")
else:
    if 100<tmpStr<=999:
        print("The number you entered is between(100,999]")
    else:
        print("The number you entered is too large, so the information will not be output for the time being")

This article is synchronously published on wechat subscription number. If you like my article, you can also pay attention to my wechat subscription number: woaitest, or scan the following QR code to add attention:

Tags: Python less

Posted on Wed, 27 May 2020 10:42:37 -0400 by johnali3n