一、理解决策制定陈述的使用情况
多选语句if-elif-else是最常见的决策语句。
我们使用这个控制结构来指定程序中的两个不同操作。
我们需要提供一个条件。如果这个条件成立,那么我们的程序将执行某个操作。如果这个条件为假,那么将采取另一个操作。
示例:
if (language_option == "I"):
#{
print("Ciao mondo.")
print("Come stai?")
#}
elif (language_option == "W"):
#{
print("Helo Byd.")
print("Sut wyt ti?")
#}
elif (language_option == "Z"):
#{
print("Sawubona Mhlaba.")
print("Unjani?")
#}
else:
#{
print("Hello World.")
print("How are you?")
#}
二、if-elif例题
编写一个程序,根据以下定价计算成本。
项目数量 | 成本 |
---|---|
1-50 | 每件3美元 ;邮费:10美元 |
超过50 | 每件2美元邮寄:免费 |
num_items = input("Enter the number of items: ")
items = int(num_items)
num_items_str = str(num_items)
if items <= 50 and items >= 1:
print("\nReceipt:")
subtotal = items * 3
subtotal_str = str(subtotal)
print(num_items_str + " items" + " x " + "$3" + " = " + "$" + subtotal_str)
print("Postage: $10")
total = subtotal + 10
total_str = str(total)
print("Total: " + "$" + total_str)
elif items > 50:
print("\nReceipt:")
subtotal = items * 2
subtotal_str = str(subtotal)
print(num_items_str + " items" + " x " + "$2" + " = " + "$" + subtotal_str)
print("Postage: $0")
print("Total: " + "$" + subtotal_str)
else:
print("Please enter the number again!")
总结
🍖if -elif-else语句在题目当中一般不会单独出现,这是一个非常重要的语句,功能也非常强大,需要大量练习,我也准备了一下练习题,供大家参考。今天就先学习到这里吧!