亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python 程序有時會以“IndexError: string index out ”

Python 程序有時會以“IndexError: string index out ”

UYOU 2023-05-16 15:50:48
我正在學習 Python 并決定升級一個版本的 hangman 游戲,該游戲在我觀看的其中一門課程中用作示例,代碼如下所示:import randomword_dictionary = {    1:  "mouse",    2:  "house",    3:  "show",    4:  "see",    5:  "leave",    6:  "shower",    7:  "showcase",    8: "coding",    9:  "elephant",    10:  "apartment",}random_number = random.randint(1, 10)random_word = word_dictionary[random_number]secret_word = random_wordword_len = len(secret_word)guess = Nonetip = 0tip_num = Nonetip_previous = Nonetip_position = Nonetip_model_formula = "_"*word_lentip_model_list = list(tip_model_formula)send_tip = Noneprint("Word has", word_len, " letters")while guess != secret_word:    guess = input("Enter your guess: ")    if guess != secret_word:        print("Wrong answer! Try again!")        tip += 1        if tip == 5:            tip_num = random.randint(0, word_len)            tip_position = secret_word[tip_num]            tip_model_list[tip_num] = tip_position            send_tip = "".join(tip_model_list)            tip_previous = tip_num            print("here's a tip:\n" + send_tip)        if tip == 10:            tip_num = random.randint(0, word_len)            while tip_num == tip_previous:                tip_num = random.randint(0, word_len)            tip_position = secret_word[tip_num]            tip_model_list[tip_num] = tip_position            send_tip = "".join(tip_model_list)            tip_previous = tip_num            print("here's a tip:\n" + send_tip)(這樣做是從字典中隨機選擇一個單詞作為秘密單詞,讓玩家對其進行猜測,每嘗試 5 次,玩家獲得 1 個小費,即單詞的一個字母,嘗試 16 次后,您輸了并且必須重新啟動)。我不知道為什么會隨機發生這種情況,并且一直試圖找出一個小時但沒有成功。感謝您提前提供幫助。
查看完整描述

1 回答

?
猛跑小豬

TA貢獻1858條經驗 獲得超8個贊

你的錯誤在這里:

            tip_num = random.randint(0, word_len)
            tip_position = secret_word[tip_num]

randint返回其第一個和第二個參數之間的數字,包括兩個。這意味著它可以返回 的結果word_len,這是 的結束后的結果secret_word。


查看完整回答
反對 回復 2023-05-16
  • 1 回答
  • 0 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號