If statement
The general form of the IF statement in Python is as follows:
if condition_1:Statement_block_1elif condition_2:statement_block_2Else:Statement_block_3
If "condition_1" is true, the "statement_block_1" block statement is executed, and if "condition_1" is false, "condition_2" is judged, and if "condition_2" is True the " Statement_block_2 "block statement, if" condition_2 "is false, the" STATEMENT_BLOCK_3 "block statement is executed.
Python replaces the else if with elif, so the keyword for the IF statement is: If–elif–else.
Note:
1. Use a colon (:) after each condition to indicate the next block of statements to be executed after the condition is met.
2, using indentation to divide the statement block, the same indentation number of statements together to form a block of statements.
3. There are no switch–case statements in Python.
The following example shows a dog's age calculation:
Age = Int (input ("Age of the Dog:"))print ()if age < 0:print ("This can hardly is true!")elif Age = = 1:print ("About human years")elif Age = = 2:print ("About human years")Elif Age > 2:human = + (age-2)print ("Human years:", Human) ###input (' press return> ')
Save the above script in the dog.py file and execute the script:
python dog.pyAge of the dog:1About human years
The following are the operations operators commonly used in the IF:
operator Description< less than<= less than or equal to> Greater than>= greater than or equal to= = equals, compares objects for equality! = does not equal# The program demonstrates the = = operator# Use digital print (5 = = 6)# using Variablesx = 5y = 8print (x = = y)
The result of the above example output:
FalseFalse
high_low.py file:
#!/usr/bin/python3# This example demonstrates a digital guessing gameNumber = 7guess =-1print ("Guess the number!")While guess! = number:guess = Int (input ("Is it ... "))if guess = = number:Print ("hooray! You guessed it right! ")Elif Guess < number:print ("It s bigger ...")Elif guess > number:print ("It's not so big.")
Python conditional control