Phiếu thực hành lap trinh Python căn bản - Lenh IF -
Phiếu thực hành lap trinh Python căn bản - Lenh IF -
Lệnh IF
Python if Statement
Summary: in this tutorial, you’ll learn how to use the Python if statement to
execute a block of code based on a condition.
The simple Python if statement
You use the ifstatement to execute a block of code based on a specified
condition.
The syntax of the ifstatement is as follows:
if condition:
if-block
The following example illustrates you how to use the if...else statement:
age = input('Enter your age:')
if int(age) >= 18:
print("You're eligible to vote.")
else:
print("You're not eligible to vote.")
Note that the else block is optional. If you omit it and no condition is True, the
statement does nothing.
The following flowchart illustrates the if...elif...else statement:
If the input age is less than 5, the ticket price will be $5.
If the input age is greater than or equal to 5 and less than 16, the ticket price is
$10.
Otherwise, the ticket price is $18.
Summary
Use the if statement when you want to run a code block based on a condition.
Use the if...else statement when you want to run another code block if the
condition is not True.
Use the if...elif...else statement when you want to check multiple
conditions and run the corresponding code block that follows the condition that
evaluates to True.
Python Ternary Operator
Summary: in this tutorial, you’ll learn about the Python ternary operator and how to
use it to make your code more concise.
The following program prompts you for your age and determines the ticket price
based on it:
To make it more concise, you can use an alternative syntax like this:
In this statement, the left side of the assignment operator ( =) is the variable ticket_price.
The expression on the right side returns 20 if the age is greater than or equal
to 18 or 5 otherwise.
The ternary operator evaluates the condition. If the result is True, it returns
the value_if_true. Otherwise, it returns the value_if_false.
if condition:
value_if_true
else:
value_if_true
Code language: Python (python)
Note that you have been programming languages such as C# or Java, you’re familiar
with the following ternary operator syntax:
The following program uses the ternary operator instead of the if statement: