Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
>

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading