[英]How to run a function several times for different results in Python 3
編輯:感謝您對解決方案的每一個非常詳細的解釋,這個社區對於嘗試學習編碼的人來說是黃金! @ 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("[]"))
您的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.