Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python3 condition control


May 10, 2021 Python3



The general form of an if statement in Python is as follows:

if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3

If "condition_1" is True, the "statement_block_1" block statement is executed, if "condition_1" is False, "condition_2" is judged, and if "condition_2" is True, the "statement_block_2" block statement is executed, and if "condition_2" is False, the statement is executed _block_3" block statement.

The eelse if is replaced by elif in Python, so the keyword for the if statement is: if - elif - else.

Attention:

  • 1, each condition is followed by a colon (:), indicating that the next is to meet the condition after the statement block to be executed.
  • 2, the use of indentation to divide the statement block, the same indentation of the statement together to form a statement block.
  • 3. There is no switch-case statement in Python.

Instance

The following example demonstrates the age calculation of a dog:

age = int(input("Age of the dog: "))
print()
if age < 0:  
    print("This can hardly be true!") 
elif age == 1:  
    print("about 14 human years") 
elif age == 2:  
    print("about 22 human years") 
elif age > 2:
  human = 22 + (age -2)*5
  print("Human years: ", human)

### 
input('press Return>')

Save the above script in dog.py file and execute the script:

python dog.py
Age of the dog: 1

about 14 human years

Here are the operators commonly used in if:

Operator Describe
< Less than
<= Less than or equal to
> Greater than
>= Is greater than or equal to
== Equal to, compare whether the object is equal
!= Not equal to

Instance

# 程序演示了 == 操作符
# 使用数字
print(5 == 6)
# 使用变量
x = 5
y = 8
print(x == y)

The above example output results:

False
False

high_low.py file:

#!/usr/bin/python3 
# 该实例演示了数字猜谜游戏
number = 7
guess = -1
print("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.")