我是python的新手,仅在1周前开始学习。该程序非常有效,除了当我在以0开头的guess1变量中输入数字时。
import random
import sys
def script():
while True:
number1 = random.randint(1000, 9999)
number1 = int(number1)
while True:
print ("Enter Your Guess")
guess1 = input()
guess1 = int(guess1)
while True:
if guess1 != number1:
break
elif guess1 == number1:
print ("Your Guess Was Right!")
print ("Do you want to play again? Type YES or NO")
ask = input()
ask = str(ask)
if ask == "YES" or ask == "yes":
script()
elif ask == "NO" or ask == "no":
sys.exit()
else:
print ("Invalid input, try again.")
continue
number = list(str(number1))
guess = list(str(guess1))
if len(guess) > 4:
print ("Please type a 4-digit number")
continue
bulls = 0
wr = 0
cows = 0
a = 3
while a >= 0:
if number[a] == guess[a]:
number[a] = 'a'
guess[a] = 'b'
bulls += 1
a -= 1
b = 0
c = 0
while b < 4:
c = 0
while c < 4:
if number[b] == guess[c]:
number[b] = 'a'
guess[c] = 'b'
wr += 1
c += 1
b += 1
z = bulls + wr
cows = 4 - z
bulls = str(bulls)
cows = str(cows)
wr = str(wr)
print ("Cows: "+cows)
print ("Bulls: "+bulls)
print ("Wrongly Placed: "+wr)
break
script()
这是一个为游戏编写的程序,其中要猜测一个4位数字。我们从一个随机数开始,然后以奶牛,公牛和放错位置的形式获得线索。牛意味着数字是错误的,公牛是数字是正确的,放错位置意味着数字是正确的但放错了位置。
整个过程正常运行,但是当我输入一个以0开头的数字时,它显示如下内容:-
Traceback (most recent call last):
File "GuessingGame.py", line 61, in <module>
script()
File "GuessingGame.py", line 36, in script
if number[a] == guess[a]:
IndexError: list index out of range
请帮助,谢谢!
更新:
感谢用户@blue_note的回答,该程序现在可以运行!这就是它的修改方式-
import random
import sys
def script():
while True:
number1 = random.randint(1000, 9999)
number1 = int(number1)
while True:
print ("Enter Your Guess")
guess1 = input()
number = list(str(number1))
guess = list(str(guess1))
if guess[0] == 0:
guess1 = str(guess1)
else:
guess1 = int(guess1)
while True:
if guess1 != number1:
break
elif guess1 == number1:
print ("Your Guess Was Right!")
print ("Do you want to play again? Type YES or NO")
ask = input()
ask = str(ask)
if ask == "YES" or ask == "yes":
script()
elif ask == "NO" or ask == "no":
sys.exit()
else:
print ("Invalid input, try again.")
continue
bulls = 0
wr = 0
cows = 0
a = 3
while a >= 0:
if number[a] == guess[a]:
number[a] = 'a'
guess[a] = 'b'
bulls += 1
a -= 1
b = 0
c = 0
while b < 4:
c = 0
while c < 4:
if number[b] == guess[c]:
number[b] = 'a'
guess[c] = 'b'
wr += 1
c += 1
b += 1
z = bulls + wr
cows = 4 - z
bulls = str(bulls)
cows = str(cows)
wr = str(wr)
print ("Cows: "+cows)
print ("Bulls: "+bulls)
print ("Wrongly Placed: "+wr)
break
script()
由于我的猜测始终是错误的,如果第一个数字为0,则无需将其转换为int。
再次感谢您的帮助!这是我在网站上的第一个问题。这真的是一个很棒的网站。
答案 0 :(得分:0)
当您传递以0开头的整数,例如0123
,并在下一行将其转换为int
时,剩下的是123
(3位数字) )。稍后,您进行number = list(str(number1))
,因此您的number
为['1', '2', '3']
(长度3)。然后,您尝试使用number[a]
来获取a=3
,这就是您得到的错误。
您可以做类似
的操作number = list(str(number1) if number1 > 999 else '0' + str(number1))