如何在Python 3中为不同的结果运行多次函数

时间:2018-01-25 06:59:35

标签: python python-3.x for-loop

编辑:感谢您对解决方案的每个非常详细的解释,这个社区对于想要学习编码的人来说是金色的! @DYZ,@ Rob

我是编程新手,我试图在Python 3中编写一个简单的乐透猜测脚本。

用户输入他们需要多少猜测,程序应该多次运行该功能。

但相反,我的代码会多次打印相同的结果。你能帮我解决这个问题吗?

我在下面粘贴了我的代码,或者我猜您可以直接从这里运行代码:https://repl.it/@AEE/PersonalLottoEn

from random import randint

def loto(limit):
    while len(guess) <= 6: #will continue until 6 numbers are found
        num = randint(1, limit)
        #and all numbers must be unique in the list
        if num not in guess: 
            guess.append(num)
        else:
            continue
    return guess

guess = [] #Need to create an empty list 1st

#User input to select which type of lotto (6/49 or 6/54)

while True:
    choice = int(input("""Please enter your choice:
    For Lotto A enter "1"
    For Lotto B enter "2"
    ------>"""))
    if choice == 1:
        lim = 49  #6/49
        break
    elif choice == 2:
        lim = 54  #6/54
        break
    else:
        print("\n1 or 2 please!\n")

times = int(input("\nHow many guesses do you need?"))

print("\nYour lucky numbers are:\n")

for i in range(times):
    result = str(sorted(loto(lim)))
    print(result.strip("[]"))

1 个答案:

答案 0 :(得分:2)

您的loto函数正在对全局变量guess进行操作。全局变量保持其值,甚至跨函数调用。第一次调用loto()时,guess[]。但是第二次调用时,它仍然具有第一次调用的6个值,因此不会执行while循环。

解决方案是将guess变量置于loto()函数的本地变量。

试试这个:

def loto(limit):
    guess = [] #Need to create an empty list 1st
    while len(guess) <= 6: #will continue until 6 numbers are found
        num = randint(1, limit)
        #and all numbers must be unique in the list
        if num not in guess:
            guess.append(num)
        else:
            continue
    return guess