我在 python 中创建了猜谜游戏,但出现索引错误
i have created the guessing game in python but it's giving an index error
from random import randint
import sys
answer = randint(int(sys.argv[1]), int(sys.argv[2]))
while True:
try:
guess = int(input(f'guess a number {sys.argv[1]}~{sys.argv[2]}: '))
if 0 < guess < 11:
if guess == answer:
print('you are a genius!')
break
else:
print('hey bozo, I said 1~10')
except ValueError:
print('please enter a number')
continue
但是它在第 5 行给出了索引错误!做什么
您没有传递足够的参数。在访问它们的位置之前,您应该检查 argv 的长度:
if len(sys.argv) != 3:
print(f'Not enought params usage: {sys.argv[0]} min_value max_value')
exit(-1)
from random import randint
import sys
answer = randint(int(sys.argv[1]), int(sys.argv[2]))
while True:
try:
guess = int(input(f'guess a number {sys.argv[1]}~{sys.argv[2]}: '))
if 0 < guess < 11:
if guess == answer:
print('you are a genius!')
break
else:
print('hey bozo, I said 1~10')
except ValueError:
print('please enter a number')
continue
但是它在第 5 行给出了索引错误!做什么
您没有传递足够的参数。在访问它们的位置之前,您应该检查 argv 的长度:
if len(sys.argv) != 3:
print(f'Not enought params usage: {sys.argv[0]} min_value max_value')
exit(-1)