简体   繁体   中英

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
>

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

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.

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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM