In many cases, some programs need conditions to run , Like the name of the car BMW All caps are required , Other car brands may only need capital letters .
cars=['audi','bmw','subaru','toyota']
for car in cars:
if car=='bmw':
print(car.upper())
else:
print(car.title())
Audi
BMW
Subaru
Toyota
In this cycle, first check whether the current car name is bmw, If bmw It will be printed in all capitals , Otherwise, it will be printed in capital letters .
Every one of them if The core of the statement is a value of true a false The expression of , This expression becomes a conditional test .python Decide whether to execute according to the value of condition test if Later code , If the condition is true Is executed , If false Just ignore it .
Compare a value with the previous variable. If it is equal, it is true Inequality is false.
>>>car='bmw'
>>>car=='bmw'
true
>>>car='audi'
>>>car=='bmw'
flase
Use == Check car Whether the value of is equal to the value of the previous variable .
python It is case sensitive when checking for equality
>>>car='audi'
>>>car='Audi'
false
If case is important in your program, it will be an advantage , If you are not case sensitive , You can convert the value of a variable to case for comparison .
>>>car='Audi'
>>>car.lower()=='audi'
ture
>>>car
'Audi'
First capitalize the string 'Audi' Assigned to a variable car, Get variables later car To convert it to lowercase , And 'audi' The comparison , Because the two strings are the same , So the output is ture, From the back car The output of can know lower.() The variables are not affected car Value .
Want to determine whether the two values are not equal , have access to !=, The exclamation point indicates ’ No ‘
The following code uses if Statement demonstrates how to use the inequality operator .
car='bmw'
if car !='toyota':
print("sorry")
sorry
We are going to car The assignment is bmw And then use if Sentence judgment car Is it equal to toyota If it is not equal to, it will output sorry. because car The value of is bmw No toyota So the function will be executed print().