The Python conditional statement determines the code block to be executed based on the execution result (True or False) of one or more statements.
You can simply understand the execution process of the statement through the following figureThe Python programming language specifies any non-zero and non-null values as true, and 0 or null as false.
if judgment condition:
Execute statement...
else:
Execute statement...
When the "judgment condition" is established (not 0), the following statement is executed, and the execution content can be multiple lines, and the same range is distinguished by indentation. Else is an optional statement. When the required condition is not satisfied, the execution content can execute the related statement
Example1
flag = False
name ='luren'if name =='python':
flag = True
print('welcome boss')else:print(name)
# The output of the above example is
luren
The judgment condition of IF statement can use >, <, ==, >=, <= to express its relationship.
When the judgment condition is multiple values, the following methods can be used
if judgment condition 1:
Execute statement 1...
elif judgment condition 2:
Execute statement 2...
elif judgment condition 3:
Execute statement 3...
else:
Execute statement 4...
Example2
num =5if num ==3: #Determine the value of num
print('boss')
elif num ==2:print('user')
elif num ==1:print('worker')
elif num <0: #Output when the value is less than zero
print('error')else:print('roadman') #Output when none of the conditions are met
# The results of the above example are as follows
roadman
Since python does not support switch statement, multiple condition judgments can only be realized with elif. If multiple conditions are required to judge at the same time, or (or) can be used to indicate that the judgment condition is successful when one of the two conditions is true ; When and (and) is used, it means that the judgment condition is successful only when two conditions are satisfied at the same time.
num =9if num >=0 and num <=10: #Determine whether the value is at 0~Between 10
print('hello')
# Output result: hello
num =10if num <0 or num >10: #Determine whether the value is less than 0 or greater than 10print('hello')else:print('undefine')
# Output result: undefine
num =8
# Determine whether the value is at 0~5 or 10~Between 15
if(num >=0 and num <=5)or(num >=10 and num <=15):print('hello')else:print('undefine')
# Output result: undefine
When there are multiple conditions in the if, you can use parentheses to distinguish the order of judgment. The judgments in the parentheses are executed first, and the priority of and and or is lower than the judgment symbols such as> (greater than), <(less than), that is, greater than and less than In the absence of parentheses, it will be judged first than and or.
if nesting
if expression 1:
Statement
if expression 2:
Statement
elif expression 3:
Statement
else:
Statement
elif expression 4:
Statement
else:
Statement
# Example3
num=int(input("Enter a number:"))if num%2==0:if num%3==0:print("The number you enter can divide 2 and 3")else:print("The number you entered can divide 2 but not 3")else:if num%3==0:print("The number you entered can divide 3, but not 2")else:print("The number you entered cannot divide 2 and 3")
Enter a number:15
The number you entered can divide 3, but not 2
Simple statement group
var=100if(var==100):print("The value of the variable var is 100, Good bye!")
**Example4, the dog's age calculation judgment
age =int(input("Please enter the age of your dog:"))print("")if age <=0:print("The dog is not born yet")
elif age ==1:print("The equivalent of 14 years old")
elif age ==2:print("22 year old equivalent")
elif age >2:
human =22+(age -2)*5print("Corresponds to human age:",human)
### Exit prompt
input("Click enter to exit"
Example5, login case
#! /usr/bin/env python3
# - *- coding:utf-8-*-import getpass
username =input('please enter user name: ')
password =input('Please enter password: ')
# If the password is not displayed
# password = getpass.getpass('Please enter password: ')if username =='admin' and password =='admin':print('login successful!')else:print('Login failed!')
Example6 Guess the number
#! /usr/bin/env python3
# - *- coding:utf-8-*-import random
answer = random.randint(1,100)
counter =0while True:
counter +=1
number =int(input('Please enter a number: '))if number < answer:print('Small')
elif number > answer:print('Big')else:print('Congratulations, you guessed it right!')breakprint('You guessed in total%d times'% counter)if counter >7:print('I suggest you go back to elementary school again~')
Example7 Calculate monthly income and actual income in hand
#! /usr/bin/env python3
# - *- coding:utf-8-*-"""
Enter monthly income and five social insurances and one housing fund to calculate personal income tax
"""
salary =float(input('Income this month: '))
insurance =float(input('Five social insurance and one housing fund: '))
diff = salary - insurance -3500if diff <=0:
rate =0
deduction =0
elif diff <1500:
rate =0.03
deduction =0
elif diff <4500:
rate =0.1
deduction =105
elif diff <9000:
rate =0.2
deduction =555
elif diff <35000:
rate =0.25
deduction =1005
elif diff <55000:
rate =0.3
deduction =2755
elif diff <80000:
rate =0.35
deduction =5505else:
rate =0.45
deduction =13505
tax =abs(diff * rate - deduction)print('Personal Income Tax: ¥%s yuan'% tax)print('Actual income: ¥%.2f yuan'%(salary - insurance - tax))
Recommended Posts