Can't tell why this if statement throws error

I’m working on the arithmetic_arranger project and I have an if statement on line 31 of my code:

if i < len(problems):

that keeps throwing an invalid syntax error, and I can’t tell what’s wrong with it. Here’s my code:

def arithmetic_arranger(problems, solutions=False):
	#check that problems isn't too long
	if len(problems) > 5:
		return 'Error: Too many problems.'

	arranged_problems = '' 

	#split earch string into its 2 numbers and its operand
	for i, v in enumerate(problems):
		v = v.split()
		#if operand is anything other than + or -, return error
		if (v[1] != '+' and v[1] != '-'):
			return 'Error: Operator must be \'+\' or \'-\'.'
		#if any number is greater than 4 digits, return error
		if (len(v[0]) > 4 or len(v[2]) > 4):
			return 'Error: Numbers cannot be more than four digits.'
		#if any number contains characters other than numbers, return error
		if (~v[0].isdigit() or ~v[2].isdigit()):
			return 'Error: Numbers must only contain digits.'

		#for each math problem there's a width, equal to 2 + len(longest number)	
		if (len(v[0]) > len(v[2])):
			longest = len(v[0])
		else:
			longest = len(v[2])
		width = longest + 2

		#insert spaces before the top number
		i.insert(0, ' ' * (width - len(i[0]))
		#insert spaces after the top number, except for the last problem
		if i < len(problems):
			v.insert(2, '   ')
		else:
			v.insert(2, '\n')
		#insert spaces between operand and bottom number
		v.insert(4, ' ' * (width - 1 - len([4]))
		#insert spaces after the bottom number, except for the last problem
		if i < len(problems):
			v.append('   ')
		else:
			v.append('\n')
		#insert dashes
		v.append('-' * width)
		#insert space after dashes
		if i < len(problems):
			v.append('   ')
		else:
			v.append('\n')
		#insert optional solutions
		if solutions == True:			
			#calculate solution and turn it into a string
			if v[4] == '+':
				v.append(str(int(v[1]) + int(v[6])))
			else:
				v.append(str(int(v[1]) - int(v[6])))
			#insert space before solution
			v.insert(10, ' ' * (width - len(v[10]))
			#insert space after solution
			if i < len(problems):
				v.append('   ')
			else:
				v.append('\n')

	#populate line1
	for i in problems:
		arranged_problems = arranged_problems + i[0] + i[1] + i[2]
	#populate line2
	for i in problems:
		arranged_problems = arranged_problems + i[4] + i[5] + i[6] + i[7]
	#populate line3
	for i in problems:
		arranged_problems = arranged_problems + i[8] + i[9]
	#populate optional line4
	if solutions == True:
		for i in problems:
			arranged_problems = arranged_problems + i[10] + i[11] + i[12]

  return arranged_problems

Issue here is in line with code before that, take a look at brackets:

		v.insert(4, ' ' * (width - 1 - len([4]))
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.