我正在制作一个循环输出的代码,然后要求用户再次运行它,如果他们愿意
我的代码是:
import random
duplicateNumber=0
def has_duplicates(listToCheck):
number_set = set(listToCheck)
if len(number_set) is not len(listToCheck):
return True
else:
return False
for i in range(0,1000):
birthdayList=[]
for j in range(0,23):
birthday=random.randint(1,365)
birthdayList.append(birthday)
x = has_duplicates(birthdayList)
if x==True:
duplicateNumber+=1
print ("after 1000 simulations with 23 students there were", duplicateNumber,"simulations with at least one match")
code with while loop:
import random
duplicateNumber=0
def has_duplicates(listToCheck):
number_set = set(listToCheck)
if len(number_set) is not len(listToCheck):
return True
else:
return False
i=0
while True:
if i>0:
prompt = input('Do you wish to continue?')
if prompt.lower() == 'no':
break
birthdayList=[]
for j in range(0,23):
birthday=random.randint(1,365)
birthdayList.append(birthday)
x = has_duplicates(birthdayList)
if x==True:
duplicateNumber+=1
i += 1
print ("after ", i," simulations with 23 students there were", duplicateNumber,"simulations with at least one match")
我尝试添加一个while循环,但它会继续询问问题而不显示输出。我希望我的代码显示输出,提示用户是否要再次运行它。如果他们说是,它会再次显示输出,然后询问他们是否想再次运行它。这一直持续到用户说不,程序结束,我该怎么做?
答案 0 :(得分:0)
import random
duplicateNumber=0
def has_duplicates(listToCheck):
number_set = set(listToCheck)
if len(number_set) is not len(listToCheck):
return True
else:
return False
i=0
while True:
if i>0:
prompt = input('Do you wish to continue?')
if prompt.lower() == 'no':
break
birthdayList=[]
for j in range(0,23):
birthday=random.randint(1,365)
birthdayList.append(birthday)
x = has_duplicates(birthdayList)
if x==True:
duplicateNumber+=1
i += 1
print ("after ", i," simulations with 23 students there were", duplicateNumber,"simulations with at least one match")
只需将print()
移到while循环中即可解决问题。