第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

為什么這段代碼會產生錯誤“int is not subscriptable”?

為什么這段代碼會產生錯誤“int is not subscriptable”?

縹緲止盈 2022-01-05 10:39:08
我已將變量轉換為字符串,但是 Python 仍然無法識別這一點,并表示該整數不可下標。我已經嘗試使用相同的“整數不可下標”問題查看其他問題,但沒有一個專門回答我的問題。在發(fā)生錯誤之前,我已將變量顯式轉換為字符串。 import random num = random.randint(1000, 9999) tot_correct = 0 tot_tries = 0 while tot_correct != 4:     tot_correct = 0     tot_tries += 1     guess = input("Guess the number: ")     guess = str(guess)     #check 1st number     if guess[0] == num[0]:         tot_correct += 1     #check 2nd number     if guess[1] == num[1]:         tot_correct += 1     #check 3rd number     if guess[2] == num[2]:         tot_correct += 1     #check 4th number     if guess[3] == num[3]:         tot_correct += 1     print("You got " + tot_correct + " numbers right.")print("You have guessed the number correctly! It took you " + tot_tries + "   tries.")我希望該字符串成為一個字符串數組,(但它仍然沒有,并返回相同的錯誤),然后確定單個數字是否與已經匹配的數字匹配
查看完整描述

2 回答

?
qq_遁去的一_1

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

您的碼沒有按照您的想法行事?,F在您正在輸入一個數字,將其轉換為字符串并將該猜測字符串的第一個字符與不可索引的數字的第一個索引進行比較num[0]。


編輯:您的代碼實際上做錯了很多事情。您遇到的一個大問題是您tot_correct = 0在 while 循環(huán)中進行設置,這意味著它將永遠運行并且永遠不會完成。


但是退一步說,我認為你把這個問題弄得太復雜了。讓我們談談我相信你正在嘗試做的偽代碼。


num_guessed = 0

number_to_guess = 4

total_guesses = 0

while num_guessed < number_to_guess:

    # each pass we reset their guess to 0 and get a new random number

    guess = 0

    # get a new random number here

    while guess != random:

        # have a user guess the number here

        total_guesses += 1 # we can increment their total guesses here too

        # it would be a good idea to tell them if their guess is higher or lower

        # when they guess it right it will end the loop


    num_guessed += 1


# down here we can tell them game over or whatever you want

代碼至少應該讓您了解如何在不為您解決問題的情況下解決問題。


查看完整回答
反對 回復 2022-01-05
?
蝴蝶不菲

TA貢獻1810條經驗 獲得超4個贊

我恭敬地不同意之前的評論。循環(huán)有可能結束。我明白你為什么tot_correct在每個循環(huán)開始時設置為 0。因為tot_correct最多增加 4 次,所以有可能為tot_correct == 4真。

編輯:海報試圖計算提供的正確位數。因此,如果要猜測的數字是“1234”并且用戶輸入“1564”,則發(fā)布者希望代碼返回“2”以指示“1”和“4”是正確的數字。這就像游戲策劃,玩家必須猜測正確的顏色和顏色的方向。但是,如果在錯誤位置添加了正確數字,此代碼不會通知用戶,僅當正確數字位于正確位置時才通知用戶。

但是,他是正確的,您的錯誤在于您對num[<index>]num是一個整數,因此您無法對其進行索引,因此“整數不可下標”。num需要是一個字符串才能對字符進行索引。

編輯:guess已經是一個沒有調用的字符串,str()因為返回的input()是一個字符串

需要考慮的一些事項:您是否希望您的用戶知道他們需要一個 4 位數字?如果添加了空格怎么辦?目前您的代碼不會刪除空格。如果您正在尋找“6543”作為幻數,而我輸入“6543”,您的解決方案將無法識別我的答案是正確的。


查看完整回答
反對 回復 2022-01-05
  • 2 回答
  • 0 關注
  • 193 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

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

公眾號

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