Python3 Conditional Control
Python contingent articulations are squares of code that are executed by the execution consequence of at least one explanations (True or False).
You can utilize the accompanying figure to quickly comprehend the execution of restrictive statements:
The general type of an if proclamation in Python is as follows:
- If "condition_1" is True, the "statement_block_1" square proclamation will be executed
- If "condition_1" is False, it will decide "condition_2"
- if "condition_2" "Statement_block_2" square proclamation will be executed for True
- If "condition_2" is False, the "statement_block_3" square articulation will be executed
In Python, elif is utilized rather than else if, so the if articulation watchword is: if – elif – else.
- 1. Use a colon : after each condition to indicate that the next statement block is to be executed after the condition is met.
- 2, using indentation to divide the statement block, the same indented number of statements together form a statement block.
- 3. There is no switch-case statement in Python.
The following is a simple if instance:
Execute the above code, the output is:
1 - if The expression condition is true 100 Good bye!
From the result, you can see that the variable var2 is 0, so the corresponding statement in if is not executed.
The following example demonstrates the age calculation of a dog:
Save the above script in the dog.py file and execute the script:
$ python3 dog.py Please enter the age of your dog: 1 equivalent 14 The old man. Click enter Exit
The following are the commonly used operation operators in if:
||is less than|
||is less than or equal to|
||is greater than|
||is greater than or equal to|
||is equal to whether the comparison objects are equal|
||not equal to|
The above example output results:
high_low.py file demonstrates the comparison of numbers:
Executing the above script, the example output is as follows:
$ python3 high_low.py Digital guessing game! Please enter the number you guessed:1 The number guessed is small... Please enter the number you guessed:9 The number of guesses is big... Please enter the number you guessed:7 Congratulations, you guessed it!
In a nested if statement, you can put the if...elif...else structure in another if...elif...else structure.
if expression1: Statement if expression2: Statement elif expression3: Statement else: Statement elif expression4: Statement else: Statement
Save the above program to the test_if.py file. After execution, the output will be:
$ python3 test.py Enter a number:6 The number you enter can be divisible 2 and 3