Tải bản đầy đủ (.pdf) (3 trang)

034 if elif else statements tủ tài liệu training

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (380.77 KB, 3 trang )

if-elif-else statements
In previous lesson, we have learned if-else statements. In this lesson, we are going to see if-elif-else statements.

if-elif-else blocks
Sometimes a situation arises when there are several conditions.
To handle this situation Python allows us adding any number of elif clause after an if and before an else clause.
Here is the syntax of if-elif-else statement:
if expression1:
do something
...
...
elif expression2:
do something else
...
...
elif expression3:
do something else
...
...
...
...
else:
do another thing
...
...

In our programs, we can create as many elif blocks as we need. also it's not mandatory to write else .
In if - elif - else statements, which condition is satisfied the program executes that condition block and the if block is ended.

The Complete Python 3 Programming Course: (Beginner to Advanced)



In [1]: print("""
===========================
Simple Calculator
===========================
Please select an operation:
1) Add
2) Subtract
3) Multiply
4) Divide
""")
choice = input("Please enter a choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", num1+num2)
elif choice == '2':
print(num1,"-",num2,"=", num1-num2)
elif choice == '3':
print(num1,"*",num2,"=", num1*num2)
elif choice == '4':
print(num1,"/",num2,"=", num1/num2)
else:
print("Invalid input")
===========================
Simple Calculator
===========================
Please select an operation:
1) Add
2) Subtract

3) Multiply
4) Divide
Please enter a choice(1/2/3/4):1
Enter first number: 4
Enter second number: 5
4 + 5 = 9

Python Program to Calculate Grade of Student
In [2]: mark = float(input("Please, enter your score: "))
if mark >= 90:
print('Your grade is : A+')
elif mark >= 85:
print('Your grade is : A')
elif mark >= 80:
print('Your grade is : B')
elif mark >= 70:
print('Your grade is : C')
elif mark >= 60:
print('Your grade is : D')
else:
print('Failed! Your grade is : F')
Please, enter your score: 80
Your grade is : B

The Complete Python 3 Programming Course: (Beginner to Advanced)


If we use if instead of elif keywords; our program would not work properly.
In [4]: mark = float(input("Please, enter your score: "))
if mark >= 90:

print('Your grade is : A+')
if mark >= 85:
print('Your grade is : A')
if mark >= 80:
print('Your grade is : B')
if mark >= 70:
print('Your grade is : C')
if mark >= 60:
print('Your grade is : D')
else:
print('Failed! Your grade is : F')
Please, enter
Your grade is
Your grade is
Your grade is

your score: 80
: B
: C
: D

In [ ]:

The Complete Python 3 Programming Course: (Beginner to Advanced)



×