Python 使用列表时如何使用if语句
如果他们输入的课程不是可供选择的课程列表中的课程,我希望它可以打印错误,否则就指定他们从列表中输入的课程 这是我的密码:Python 使用列表时如何使用if语句,python,python-3.x,Python,Python 3.x,如果他们输入的课程不是可供选择的课程列表中的课程,我希望它可以打印错误,否则就指定他们从列表中输入的课程 这是我的密码: name = input("Whats your name?: ") age = int(input("Whats your age?: ")) courses_avalible = ["Math", "Business", "Finance", "Code&quo
name = input("Whats your name?: ")
age = int(input("Whats your age?: "))
courses_avalible = ["Math", "Business", "Finance", "Code"]
print("Hello, " + name + ". Your avalible courses to enrolll in are: " + str(courses_avalible))
course = input("What course would you like to enroll in? ")
if course != courses_avalible:
print("Course not avalible, please choose a course from the list above.")
else:
assign = name + " has been enrolled in " + course
print(assign)
Python非常简洁,允许您执行以下操作:
if course not in courses_available:
# code
它只是检查
课程
是否在课程中可用
只需对列表使用不在
操作符即可,即:
if course not in courses_avalible:
print(...)
else:
assign = ...
如果要在列表中找不到值时执行代码,可以使用:
if value not in list:
对于您的具体示例,您可以使用:
if course not in courses_available:
print("Course not available, please choose a course from the list above.")
else:
#code to execute when the input is in the list
简单的方法就是使用Python提供的语法检查值是否在数组中,如下所示:
if course not in courses_avalible:
# do something
else:
# do something else
如果课程不在可用的课程中,您可以使用
。
@Ronan,实际上尝试/期望
更多preferable@theX谢谢,很高兴知道。养成直接发布代码的习惯,而不是发布代码的图片。它使社区更容易根据需要提供帮助和编辑。try/expects
是捕获错误的首选方法。它必须缩进。另外,在pythonyeah中使用#
作为注释刚刚意识到,整天都在使用javascript谢谢你的回答它帮助解决了我的问题+你的回答让我清楚地知道它是如何使用的。非常感谢!