1

I'm trying to enter two numbers in the same line in this program, but I get the following error when I write the 2 numbers (separated by a space):

Traceback (most recent call last):
  File "(the file path)", line 3, in <module>
    for x in range(1, n1 + 1):
TypeError: can only concatenate str (not "int") to str

This is my code:

n1, n2 = input("Insert two numbers: ").split()
sum1 = 0
for x in range(1, n1 + 1):
    sum1 += x ** n2
    print(f'{x} to the power of {n2} is {x ** n2}')
print('The total sum is:', sum1)

I don't understand why I get that error. What am I doing wrong?

In the input of the first line, I have tried adding "str" in case it resolved the error:

n1, n2 = str(input("Insert two numbers: ").split())

But now it returns me another error when I write the 2 numbers:

Traceback (most recent call last):
  File "(the file path)", line 1, in <module>
    n1, n2 = str(input("Insert two numbers: ").split())
ValueError: too many values to unpack (expected 2)

I don't use Python much, I can't understand what I'm doing wrong. Can you give me a hand please?

HeyImGit
  • 25
  • 2
  • Does this answer your question? [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers) – mkrieger1 Jan 31 '21 at 22:15

1 Answers1

0

You need to cast both numbers to int:

n1, n2 = [int(x) for x in input("Insert two numbers: ").split()]

The error is caused by Python's attempt to concatenate as strings the string n1 and and integer 1:

n1 + 1
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47