在编程的世界里,switch语句是一个强大的工具,它允许我们根据不同的条件执行不同的代码块。虽然许多现代编程语言都在不断发展,但switch语句依然被广泛使用。下面,我们将通过5个实用的编程例题来解析如何使用switch语句,帮助你从零开始掌握它。
例题1:判断星期几
问题描述: 编写一个程序,根据输入的数字(1-7)来输出对应的星期几。
代码解析:
def print_weekday(day_number):
switcher = {
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday",
7: "Sunday"
}
return switcher.get(day_number, "Invalid day number")
# 使用示例
day = int(input("Enter a number (1-7) for the day of the week: "))
print(print_weekday(day))
在这个例子中,我们使用了一个字典来映射数字到星期几的字符串。switcher.get(day, "Invalid day number")用于处理不合法的输入。
例题2:根据成绩打印等级
问题描述: 编写一个程序,根据输入的成绩(0-100)打印对应的等级。
代码解析:
def print_grade(score):
switcher = {
0: "F",
1: "F",
2: "F",
3: "F",
4: "F",
5: "F",
6: "D",
7: "C",
8: "B",
9: "A",
10: "A"
}
return switcher.get(score // 10, "Invalid score")
# 使用示例
score = int(input("Enter your score (0-100): "))
print(print_grade(score))
在这个例子中,我们使用了整数除法来将分数范围映射到等级。
例题3:根据月份打印季节
问题描述: 编写一个程序,根据输入的月份(1-12)打印对应的季节。
代码解析:
def print_season(month):
switcher = {
1: "Winter",
2: "Winter",
3: "Spring",
4: "Spring",
5: "Summer",
6: "Summer",
7: "Autumn",
8: "Autumn",
9: "Winter",
10: "Winter",
11: "Spring",
12: "Spring"
}
return switcher.get(month, "Invalid month")
# 使用示例
month = int(input("Enter a month (1-12): "))
print(print_season(month))
在这个例子中,我们同样使用了字典来映射月份到季节。
例题4:根据性别和年龄打印建议
问题描述: 编写一个程序,根据输入的性别(M/F)和年龄(1-100)打印相应的建议。
代码解析:
def print_advice(gender, age):
advice = ""
if gender == "M":
advice += "For men, "
elif gender == "F":
advice += "For women, "
else:
return "Invalid gender"
if age < 18:
advice += "it's important to stay focused on education."
elif age < 40:
advice += "it's a great time to build a career."
elif age < 60:
advice += "consider starting a family or pursuing hobbies."
else:
advice += "enjoy your retirement and spend time with loved ones."
return advice
# 使用示例
gender = input("Enter gender (M/F): ")
age = int(input("Enter age (1-100): "))
print(print_advice(gender, age))
在这个例子中,我们使用了条件语句来构建建议。
例题5:根据用户输入打印不同的菜单项
问题描述: 编写一个程序,根据用户输入的数字(1-5)打印对应的菜单项。
代码解析:
def print_menu_option(option):
switcher = {
1: "Option 1: View profile",
2: "Option 2: Edit profile",
3: "Option 3: Logout",
4: "Option 4: View notifications",
5: "Option 5: View settings"
}
return switcher.get(option, "Invalid option")
# 使用示例
option = int(input("Enter a menu option (1-5): "))
print(print_menu_option(option))
在这个例子中,我们使用了一个字典来映射数字到菜单项。
通过以上5个例题,我们可以看到switch语句的灵活性和实用性。无论是在判断星期几、打印成绩等级、根据月份打印季节,还是在根据性别和年龄给出建议,switch语句都能发挥其作用。希望这些例子能帮助你更好地理解和掌握switch语句。
