我正在编写一个 def 来将用户定义的数字评估到一个集合列表中。 def 应该检查长度并向用户输出前十个的打印列表。打印的声明不出现。我认为这是短路。我
# Function to check the length of the list
def Check_Length():
Number_List_A =[]
if len(Number_List_A) >10:
Number_List_A = Number_List_A[0:10]
print ('The first ten will only be used.', Number_List_A)
最佳答案
您定义了一个空列表,然后测试其长度是否大于 10。由于空列表的长度为 0,因此 if
语句下的逻辑将永远不会被处理。
一个更有用的函数将采用输入列表作为参数:
def Check_Length(input_list):
if len(input_list) > 10:
print('The first ten will only be used.', input_list[:10])
例如:
Check_Length(list(range(20)))
# The first ten will only be used. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
关于python - if 语句循环内短路,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54134133/