Why doesn't this simple program work please?

Hi there,
Trying to learn Python…and struck an early problem…

What is wrong with this code?

This program adds three numbers

num1 = 2
num2 = 2
num3 = 5

Add two numbers

sum = num1 + num2 + num3

Display the sum

print(‘The sum of {0} and {1} and {3} is {4}’.format(num1, num2, num3,sum))

Error message:
IndexError: Replacement index 4 out of range for positional args tuple

Now I simply tried to use logic to change this example I found online…and added a thrid number…

what am I missing? Thanks!

# This program adds two numbers

num1 = 1.5
num2 = 6.3

# Add two numbers
sum = num1 + num2

# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Lists in python will index from zero. So the fourth element of a list will be at index 3. But you attempt to reference index 4 in your print string. As the list of numbers you’ve passed to format() doesn’t have five elements, that’s an error (you’ve skipped index 2).

Also, that’s a trickier way to print that out. I would instead prefer to use an f-string here and refer to the variables directly.

# Display the sum
print(f'The sum of {num1} and {num2} and {num3} is {sum}')
1 Like

Indices count from zero, so you want {2} and {3}, not {3} and {4}
because your 4 values are numbered 0 through 3.

Also, you could write your print like this:

print('The sum of {num1} and {num2} and {num3} is {sum}'.format(num1=num1, num2=num2, num3=num3, sum=sum))

for less ambiguity and fragileness. not that the names in the string
come from the names in the .format() parameters. I.e. this:

print('The sum of {n1} and {n2} and {n3} is {sum}'.format(n1=num1, n2=num2, n3=num3, sum=sum))

does the same thing, and would not recognise {num1} because that isn’t
what you called it.

Finally, Python has f-string where this stuff is implicit, and uses your
current variables:

print(f'The sum of {num1} and {num2} and {num3} is {sum}')

Here the syntax f’…’ is an f-string (format string) which uses your
current variables as the names which are available for formatting. Even
more direct!

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like

You have four values, which Python indexes starting from zero:

num1, num2, num3, sum
# 0     1     2     3

You try to access them with indexes 0, 1, 3, 4:

'The sum of {0} and {1} and {3} is {4}'

Notice that there is a number missing? The error message tells you that
index 4 is out of range:

IndexError: Replacement index 4 out of range for positional args tuple

I know that counting from zero instead of one takes a bit of getting
used to, but with experience you will discover that actually helps avoid
other, more tricky bugs.

Here’s another way to use the format method to easily apply a set of
values in order:

print('The sum of {} and {} and {} is {}'.format(num1, num2, num3, sum))

The format method will auto-number empty braces {}.

Last but not least, sum is the name of a built-in function. It is best
to avoid re-using that name for your own variables. Better to use
something like “total”.

1 Like

As formatted string literals support full Python expressions inside the braces calculation can be moved inside f-string:

num_1 = 1
num_2 = 2
print(f'The sum of {num_1} and {num_2} is {num_1 + num_2}'

If name is required then assignment expression can be put into f-string in the similar fashion:

>>> num_1 = 1
>>> num_2 = 2
>>> f'Sum of {num_1} and {num_2} is {(total := num_1 + num_2)}'
'Sum of 1 and 2 is 3'
>>> total
3
1 Like

Thanks all…much appreciated…was actually kicking myself when I looked and saw too I made a simple ‘typo’ in my list of numbers (mistake in sequence)…but is also great to see all the other methods mentioned…

is literally like learning a new language…and one where you need to get the grammar actually perfect!!

Thank you…appreciate all the tips from everyone…helps me learn a lot!

So I’m now trying to add the input option to create my num variables…and I get this problem with strings versus integers…

This program adds three numbers

num1 = input(“What is your first number?”)
num2 = 2
num3 = 5

Add three numbers

total = num1 + num2 + num3

print(‘The sum of {} and {} and {} is {}’.format(num1, num2, num3, total))

error: TypeError: can only concatenate str (not “int”) to str

how can I get around this…?

Thanks!

Try this sample code and see if it explains matters. If not, please ask
more questions.

mystring = '5'
mynumber = 5
print('mystring is a', type(mystring))
print('mynumber is a', type(mynumber))

a = int(mystring)
print(type(a))

b = str(mynumber)
print(type(b))

Now inspect the result of input:

value = input('What is your number? ')
print(type(value))

Does that give you enough of a hint to solve the problem?

1 Like

Thanks Steven…that was very helpful…

so if I understand this correctly…whenever we use an input command…it assumes a string…but we need to convert it into an integer?

I did this…using num1int as the conversion piece.

This program adds three numbers

num1 = input(“What is your first number?”)
num2 = 2
num3 = 5

num1int = int(num1)
print(type(num1int))

Add three numbers

total = num1int + num2 + num3

print(‘The sum of {} and {} and {} is {}’.format(num1int, num2, num3, total))

Is there a way to actually do this from the get go? ie. To tell Python that the variable being inputted is an integer…or do you have to go the extra step of converting it like I did with this:

num1int = int(num1)

Thanks so much!

Thanks again Steven…your tip helped me understand what to Google! I found a method to convert to int on input…

I now did this…# This program adds three numbers
num1 = int(input(“What is your first number?”))
num2 = 2
num3 = 5

print(type(num1))

Add three numbers

total = num1 + num2 + num3

print(‘The sum of {} and {} and {} is {}’.format(num1, num2, num3, total))

Is there a reason to do the conversion later?

Anyway thank you…very helpful!

You’re missing an ‘f’ in front of the string to print.

1 Like