简体   繁体   中英

Python3: Change the items on a list with function and while loop. Why is my code not running properly?

While doing the following task I found my code not running on Jupiter notebooks properly (have restarted the Kernel several times already):

Function Challenge: create replacement function

Create a function, str_replace, that takes 2 arguments: int_list and index

int_list is a list of single digit integers

index is the index that will be checked - such as with int_list[index]

Function replicates purpose of task "replace items in a list" above and replaces an integer with a string "small" or "large"

return int_list

Test the function!

My goal is to change all the elements of the list [0,1,2,3,4] to ["small","small", "small","small","small"] with the following code:

int_list=[0,1,2,3,4]
index=0
def str_replace(int_list,index):
    if index <5:
        int_list[index]="small"
        return int_list
    else:
        int_list[index]="large"
        return int_list

str_replace(int_list,index)
while index <=4:
    index+=index
    str_replace(int_list,index)

When I run it, it keeps running and not giving me back any output. However if I run everything but the last while loop I get: ["small",1,2,3,4]. Can anybody help me understanding why this happens?

You are in an infinite loop: index is always <= 4. See: index is initialised to 0 and the new assignment index+=index will never change the value of index to higher than 0. Did you mean index += 1 ?

You are in an infinite loop because index is always smaller than 4,

you do index += index but because index is 0 nothing adds up and you stay in the loop.

If you change it to index += 1 instead - that should solve your problem.

Also to not get an out of range error change it to while index < 4: or alternatively put the index +=1 at the bottom of the loop.

i think the problem was with the return statement with every chamge

int_list=[0,1,2,3,4]
index=0
def str_replace(int_list,index):
if index <5:
    int_list[index]="small"

else:
    int_list[index]="large"


while index <=4:
str_replace(int_list,index)
index+=1

print(int_list)

An alternative is to use

[ 'small' if index < 5 else 'large' for index in int_list]
int_list=[0,1,2,3,6]
index=0
def str_replace(int_list,index):
    if int_list[index] < 5:
        int_list[index] = "small"
    else:
        int_list[index] = "large"

while index <=4:
    str_replace(int_list,index)
    index+=1

print(int_list)

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