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

0 basic learning python (13)

編輯:Python

if sentence

In fact, the simplest if A statement is a test and an operation .

if conditional_test:
do something

if As the result of the ture Then the code will be executed , otherwise python The code will be ignored .
If a person wants to know if he is old enough, he can use the following code .

age=19
if age >=18:
print("you age is enough")

stay if Indentation is a necessary presence in statements , and for equally if The following conditional statements need to be indented ,if Manage the indented statements instead of the non indented statements .
Like just now , I want to ask whether a person is old enough , I use code to represent him .

age=19
if age >=18:
print("you age is enough")
print("you is a adult")
you age is enough
you is a adult

if The condition test passed , And two print All indented , So two print Both have been implemented. , Similarly, if this age<18 There will be no output ,

if-else sentence

We often need to execute another condition when the condition test fails , That's what we use python Provided if-else sentence ,if-else Similar to simple if sentence , But in if When the statement condition fails, it will execute else The sentence of .

for example
age=17
if age>=18:
print("you age is enough")
else:
print("sorry,you are too young to vote")
sorry,you are too young to vote

If if The first condition passes the function that will execute the first set of indents print(), But the result is false, So it's the following else To execute print() It's output .
if-else Very useful when there are only two conditions , But if the conditions change a lot , The following statement will be more suitable for judgment if it is changed to three conditions .

if-elif-else structure

When we consider more than two cases, we can use if-elif-else structure .

for example

An age - based amusement park :
4 It's free under
4-18 Annual income 25 dollar
18 Charge over the age of 40 dollar

age=12
if age<4:
print("you admission cost is $0.")
elif age<18:
print("you admission cost is $25.")
else:
print("you damission cost is $25.")

When if detected age discontent 4 The first item will be executed print() Output , When age Greater than 4 Will execute the next statement , If if and elif None of them passed that python It's going to be executed directly else And output .

age=12
if age<4:
price=0
elif age<18:
price=25
else:
price=40
print(f"you admission cost is ${
price}.")

We can convert prices directly into variables
Such code will be more concise .


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