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 ,
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 .
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 .
When we consider more than two cases, we can use if-elif-else structure .
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 .
List of articles GET Request a
Todays question I : Simple te