程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

0 basic learning python (11)

編輯:Python

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().


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved