【发布时间】:2020-03-24 01:39:51
【问题描述】:
所以我正在为我的女朋友构建一个日期生成器,但一旦选择了它,我似乎无法从样本池中删除日期。 dateChoice() 会实际选择有效的日期,但dateRemover() 似乎不起作用。我已经阅读了一堆 .txt 写作和阅读,但我似乎无法让它发挥作用。谢谢!
import random
#Imports date list
dateList = open("file", 'r+')
dates = dateList.readlines()
line = "-----------------------------------------"
choice = ""
date = ""
#Selects a Date
def dateChoice():
date = random.choice(dates)
print("Your date is: {}".format(date)
#Removes date from list
def dateRemover():
choice = input("Would you like to remove the date from the list?")
if str.upper(choice) in ["Y", "YES"]:
print(line)
dateList.seek(0)
for i in dates:
if i != date:
dateList.write(i)
dateList.truncate()
print("All is done")
elif str.upper(choice) in ["N", "NO"]:
print(line)
print("Okay. your date is still in the system!")
else:
print(line)
print("Please answer with either Yes or No")
dateRemover()
#Start of program
def start():
dateChoice()
dateRemover()
#Runs programs
start()
【问题讨论】:
-
您在“dateChoice”中创建了一个局部变量“date”,它会影响全局变量并在函数退出时丢失。在函数开始时将其声明为“全局”。
标签: python python-3.x list for-loop text