选项可将输出结果保存为文本文件(Python)
要么我没有使用正确的搜索字符串,要么将它埋在深层次的网页中。我知道我们不应该要求作业答案,但我不想要代码答案,我想知道在哪里找到它,导致我的GoogleFu被破坏。选项可将输出结果保存为文本文件(Python)
分配是创建一个程序,将滚两个6面骰子n
次,用n
被用户定义的,1和9之间然后,程序显示结果,与"Snake Eyes!"
卷筒是否1-1,如果卷是6-6,则为"Boxcar!"
。它还必须处理ValueErrors
(如果某人放置“三”而不是“3”),并返回一条消息,如果用户选择一个非整数1-9的数字。
很酷,我明白了。但他也希望它询问用户是否要将输出保存到文本文件中。嗯。是的,仔细检查了这本书和我的笔记,他没有提到AT。所以现在我被卡住了。有人能指引我走向正确的方向,还是告诉我专门寻找什么来寻求帮助?
谢谢!
您可以这样做,将最终输出存储到文本文件中。
def print_text(your_result):
with open('results.txt', 'w') as file:
file.write(your_result)
# Take users input
user_input = input("Do you want to save results? Yes or No")
if(user_input == "Yes"):
print_text(your_result)
我希望这有助于
但我该如何给他们选择?它不能直接写入它,他们必须要保存一个文件。我可以导入一个文件并追加它,只是不知道如何在那里获得选项。 – JillyBean1899
显然我没有正确设置自己的代码,因为我不知道我应该把什么放在“your_result”的位置。它不会让我把代码放在这里,因为它太长了。我对此感到非常沮丧。我不是编码员,我正在学习MIS哈哈。 – JillyBean1899
然后上帝保佑你。玩得开心 –
嗯,这是不是很漂亮,但我想出了这个:
def print_text():
with open('results.txt', 'w') as file:
file.write(str(dice))
loop = True
import random
min = 1
max = 6
dice = []
while loop is True:
try:
rolls = int(input("How many times would you like to roll the dice? Enter a whole number between 1 and 9: "))
except ValueError:
print("Invalid option, please try again.")
else:
if 1 <= rolls <= 9:
n = 0
while n < rolls:
n = n + 1
print("Rolling the dice ...")
print("The values are:")
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
dice.append(dice1)
dice.append(dice2)
print(dice1, dice2)
diceTotal = dice1 + dice2
if diceTotal == 2:
print("Snake Eyes!")
elif diceTotal == 12:
print("Boxcar!")
else: print("Invalid option, please try again.")
saveTxt = input("Would you like to save as a text file? Y or N: ")
if saveTxt == "Y" or saveTxt == "y":
print_text()
break
'打印()'需要该文件描述了输出参数'file'。默认情况下这是'sys.stdout'。 – AChampion