2016-01-21 89 views
1
import random 

four_digit_number = random.randint(1000, 9999) # Random Number generated 


def normal(): 
    four_digit = str(four_digit_number) 
    while True: # Data Validation 
     try: 
      guess = int(input("Please enter your guess: ")) 
     except ValueError or len(str(guess)) > 4 or len(str(guess)) < 4: 
      print("Please enter a 4 digit number as your guess not a word or a different digit number") 
     else: 
      break 
    guess = str(guess) 
    counter = 0 
    correct = 0 
    while counter < len(four_digit): 
     if guess[counter] in four_digit: 
      correct += 1 
     counter += 1 
    if correct == 4: 
     print("You got the number correct!") 
    else: 
     print("You got " + str(correct) + " digits correct") 

normal() 

我不明白爲什麼它說索引不在範圍內。當我使用0而不是實際使用計數器時,它可以工作。只有當我輸入一個小於4的值並且當我輸入一個大於4的值時,纔會發生這種情況,循環不會重新啓動,但會跳出循環。IndexError:字符串索引超出範圍,索引是在範圍內

+0

只有在try塊發生錯誤的除塊被執行,則不能使用嘗試測試'LEN(STR(猜測))> 4或LEN (str(guess))<4' –

+0

@PawełKordowski謝謝,你能修復我的代碼嗎?我在數據驗證方面經驗不足,而且我不知道如何完全修復它。 – Navin

+0

沒關係修好它謝謝@PawełKordowski很多! :P – Navin

回答

3

我會提出這樣的解決方案:

def normal(): 
    four_digit = str(four_digit_number) 
    while True: # Data Validation 
     try: 
      guess = str(int(input("Please enter your guess: "))) 
      assert len(guess) == 4 
     except (ValueError, AssertionError): 
      print("Please enter a 4 digit number as your guess not a word or a different digit number") 
     else: 
      break 
    correct = sum(a == b for a, b in zip(four_digit, guess)) 
    if correct == 4: 
     print("You got the number correct!") 
    else: 
     print("You got " + str(correct) + " digits correct") 
+0

謝謝,你能解釋一下sum(a == b for a,b in zip(four_digit,guess))嗎? – Navin

+1

@Navin zip(a,b)創建對(a1,b1),(a2,b2)等,其中ai來自a,bi來自b,然後我遍歷該pais並檢查是否ai == bi,如果是這樣把1其他0然後我總結我得到的數字 –