gpt4 book ai didi

python - IndexError : string index out of range, 索引在范围内

转载 作者:行者123 更新时间:2023-11-30 23:01:30 25 4
gpt4 key购买 nike

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 的值时,循环不会重新启动,但会跳出循环。

最佳答案

我会提出这样的解决方案:

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")

关于python - IndexError : string index out of range, 索引在范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34932809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com