2016-12-05 159 views
0

要麼我沒有使用正確的搜索字符串,要麼將它埋在深層次的網頁中。我知道我們不應該要求作業答案,但我不想要代碼答案,我想知道在哪裏找到它,導致我的GoogleFu被破壞。選項可將輸出結果保存爲文本文件(Python)

分配是創建一個程序,將滾兩個6面骰子n次,用n被用戶定義的,1和9之間然後,程序顯示結果,與"Snake Eyes!"捲筒是否1-1,如果卷是6-6,則爲"Boxcar!"。它還必須處理ValueErrors(如果某人放置「三」而不是「3」),並返回一條消息,如果用戶選擇一個非整數1-9的數字。

很酷,我明白了。但他也希望它詢問用戶是否要將輸出保存到文本文件中。嗯。是的,仔細檢查了這本書和我的筆記,他沒有提到AT。所以現在我被卡住了。有人能指引我走向正確的方向,還是告訴我專門尋找什麼來尋求幫助?

謝謝!

+0

'打印()'需要該文件描述了輸出參數'file'。默認情況下這是'sys.stdout'。 – AChampion

回答

0

您可以這樣做,將最終輸出存儲到文本文件中。

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) 

我希望這有助於

+0

但我該如何給他們選擇?它不能直接寫入它,他們必須要保存一個文件。我可以導入一個文件並追加它,只是不知道如何在那裏獲得選項。 – JillyBean1899

+0

顯然我沒有正確設置自己的代碼,因爲我不知道我應該把什麼放在「your_result」的位置。它不會讓我把代碼放在這裏,因爲它太長了。我對此感到非常沮喪。我不是編碼員,我正在學習MIS哈哈。 – JillyBean1899

+0

然後上帝保佑你。玩得開心 –

0

嗯,這是不是很漂亮,但我想出了這個:

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 
相關問題