所以我制作了一个程序,计算并打印在板球比赛中得分的次数,投球的次数,投球手和击球手的次数,但是当我完成代码时:
name = input('enter the name of the bowler\n=') # we ask for the input
bat_strike = input('enter the name of the batter on strike\n=')
bat_non_strike = input('enter the name of the batter on the non strike\n=')
bowls = 6 # this is the max number of bowls in a over
bowls_bowled = 0
runs_list = []
bowls_list = []
batter_list = []
batter_list.append(bat_strike)
for j in range(0, bowls):
bowl_type = int(input('enter the number corresponding to the option regarding the bowl bowled right now\n1)wide bowl\n2)simple bowl\n3)no ball\n4)dead bowl\n5)1D\n= '))
if bowl_type == 1:
bowls_list.append('wd')
runs_list.append(1)
batter_list.append(bat_strike)
bowls += 1
elif bowl_type == 2:
run = int(input('enter the number of runs scored on that bowl 1 for 1 run 2 for 2 runs 3 for 3 runs 4 for 4 runs or 0 for a dot ball\n='))
if run == 1 or run == 3:
batter_on_strike = input('enter wether the batter on strike is on non strike? y or n\n=')
if batter_on_strike == 'y':
c = bat_strike
bat_non_strike = bat_strike
bat_non_strike = c
batter_list.append(bat_strike)
runs_list.append(run)
bowls_list.append(1)
bowls_bowled += 1
elif bowl_type == 3:
bowls_list.append('no ball')
runs_list.append(1)
bowls += 1
batter_list.append(bat_strike)
elif bowl_type == 4:
bowls_list.append('dead bowl')
bowls += 1
batter_list.append(bat_strike)
elif bowl_type == 5:
bowls_list.append('1D')
bowls += 1
runs_list.append(1)
bowls_bowled += 1
batter_list.append(bat_strike)
for i in range(0, bowls-1):
print(f'bowler={name} batter on strike={batter_list[i]} bowl bowled={bowls_list[i]} runs scored={runs_list[i]}')
它产生以下错误
print(f'bowler={name} batter on strike={batter_list[i]} bowl bowled={bowls_list[i]} runs scored={runs_list[i]}') IndexError: list index out of range
我想为每个碗使用for循环来显示结果,但我一直得到这个错误
有人知道我如何解决这个问题或更好的代码吗?你知道吗
如果
bowl_type
曾经是5,或者如果它是2,并且击球手击球或非击球答案不是y
,那么你不需要在batter_list
上附加任何东西。因此,如果发生这种情况,batter_list
将不会像其他列表那样长。你知道吗例如,如果所有6个碗都是类型5,那么
batter_list
将是空的,因此batter_list[4]
当然是一个错误。你知道吗在这种情况下,不清楚您希望发生什么,因此不清楚您应该如何解决它。你知道吗
一种可能性是在这些情况下进行
batter_list.append(None)
。或者batter_list.append("n/a")
,或者……以后你想在print
中出现的任何东西。你知道吗另一种可能性是将所有这些单独的列表替换为一个dict列表:
或者,也许更好,用
class
(可能是namedtuple
或@dataclass
)代替dict相关问题 更多 >
编程相关推荐