我是编程新手,我试图在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("[]"))
答案 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