Jan N.
Jan N.

Reputation: 57

outputting strings and function outputs in Python

I am coding a simple program to add all positive integers not greater than a given integer n. My code:

print("Enter an integer:")
n=input()

def add(k):
    sum=0
    for i in range(k+1):
        sum=sum+i
    return sum
    
#print("1+2+3+...+"+str(n)+"="+str(add(n)))

print(add(100))

The function works.

Why does the line in the one line comment not work, if I remove the hash tag? It should - there is a concatenation of four strings. Thank you.

EDIT: the whole output:

Enter an integer:
12
Traceback (most recent call last):
File "<string>", line 10, in <module>
  File "<string>", line 6, in add
TypeError: can only concatenate str (not "int") to str
>

Upvotes: 0

Views: 94

Answers (3)

Danyal Imran
Danyal Imran

Reputation: 2605

The problem exists in your input, it's current data type is str, and must be converted into int.

Also, it's best if you use .format() when printing strings.

print("Enter an integer:")
n = int(input())

def add(k):
    sum=0
    for i in range(k+1):
        sum=sum+i
    return sum
    
print("1 + 2 + 3 + ... + {} = {}".format(n, add(n)))

Upvotes: 1

ForceBru
ForceBru

Reputation: 44926

input returns a string, so add(n) will look something like add("1234"). Then, range(k+1) inside the function will be range("1234" + 1), but "1234" + 1 is an error since it's not possible to add a string and a number.

Upvotes: 1

Tamir
Tamir

Reputation: 1331

input() returns a string. You are passing n=input() which is a string so it is not working as expected. change it to n=int(input())

Also sum is a reserved keyword and it will be best to change that to a different name

Upvotes: 1

Related Questions