简体   繁体   中英

Short circuit within if statement loop

I am writing a def to evaluate user-defined numbers into a set list. the def is supposed to check the length and output to the user a printed list of the first ten. The printed statement does not appear. I think it is shortcircuting. I

# 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)

You've defined an empty list and then tested if its length is greater than 10. Since an empty list has length 0, the logic under the if statement will never be processed.

A more useful function will take an input list as an argument:

def Check_Length(input_list):
    if len(input_list) > 10:
        print('The first ten will only be used.', input_list[:10])

For example:

Check_Length(list(range(20)))
# The first ten will only be used. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM