简体   繁体   中英

how to use while loop without infinite loop(python 2.7)

I have been trying to create a program with python 2.7. This program creates a random number. ( nlist[r] is saved in list[] )

If list[0] is 'do' or 'ge' or 'gi' , just print list and the program is ended.

If list[0] is 'mo' or 'yu' , the while loop starts.

When list[k]=='yu' or 'mo' , the loop must stop, print list , and also end the program. But this ended up in an infinite while loop...

Here is my code:

nlist=['do','ge','gi','yu','mo']
list=[]
def playYut():
    import random
    r=random.randrange(0,5)
    list.append(nlist[r])

playYut()

if list[0]=='do' or list[0]=='gae' or list[0]=='girl':
    for i in list:
        print i
else:
    k=0
    while list[k]:
        if list[k]=='yut' or list[k]=='mo':
            playYut()
            for i in list:
                print i
        else:
            for i in list:
                print i

It is a very common mistake you did there, my friend. You have to change the value of k for looping or add a break statement for stoping the loop.

I've made a few changes in your code which i will be explaining below.

import random
nlist=['do','ge','gi','yu','mo']
check_list = ['do','ge','gi']
loop_check_list = ['yu' ,'mo' ]
flag =1
your_list=[]
k=0
def playYut():
    r=random.randrange(0,5)
    your_list.append(nlist[r])
playYut()

if your_list[0] in check_list:
    print list1

elif your_list[0] in loop_check_list:
    while flag==1:
        k+=1
        playYut()
        if your_list[k] in loop_check_list:
            print your_list
            flag=0

1) Let import statements be declared at the top of the program it's good practice. Check this out for a detail explanation.

In Python, what happens when you import inside of a function?

2) Instead of this

if your_list[0]=='do' or your_list[0]=='gae' or your_list[0]=='girl':

this is more elegant to look at.

if your_list[0] in some_list_with_those_values:

3) Also instead of naming a list as list define some variable name for it. For ex your_list .

4) Also you can use either break or a flag variable but i prefer using flag variable here. Understanding them is essential. Set a flag variable with a value say 1 and change it to 0 when the condition is changed. This way you can exit out of the while loop.

5) I don't clearly understand what you want to do with your program. But from your description this a working code that you might want.

You need to increase the value of k in every loop you can do so by adding

K+=1

or

k=k+1

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