Skip to content Skip to sidebar Skip to footer

Python Integer And String Using

for size in [1, 2, 3, 4]: result = 0 print('size=' + str(size)) for element in range(size): result = result + element print(' adding ' + str(element)+',

Solution 1:

It's about the order things are run:

"Done. size=" + str(size) + " result=" + str(result)

has to be done first, before the print function is called. The print function just gets the single joined string - it has no idea that a + was used to construct it.

In this case:

print("Hello , I am" , x , "years old.")

the print function gets all 4 arguments (actually, a 4 element tuple) and can now work its magic on converting each one to a string itself (see Unnecessary detail below).

By the way, if you object to having to use str() then there are other ways of formatting the string to print. The following lines all produce the same output:

print("Done. size=" + str(size) + " result=" + str(result))
print("Done. size=%d result=%d" % (size, result))
print("Done. size={} result={}".format(size, result))
print(f"Done. size={size:} result={result:}")

The last one f" " requires Python 3.6 or later.

Unnecessary detail:

The conversion to str() in the print() function is actually done (in the C implementation) by the python API call PyFile_WriteObject() using the flag Py_PRINT_RAW. If Py_PRINT_RAW is given, the str() of the object is written.

Solution 2:

Just because two references appear together in a single line doesn't mean they're being concatenated. If the first example, you are concatenating strings (which is why they all have to be strings) and sending them to the print function. In the second example, you are sending multiple arguments to the print function, which will print each one. The print function can handle an arbitrary number of arguments, which don't necessarily have to be of the same type.

Solution 3:

The plus (+) operator is not able to add strings and numbers. That's why you need to use str().

If you try:

"hello" + 2

you will get the error:

Traceback (most recent calllast):
   File "<stdin>", line 1, in<module>
TypeError: cannot concatenate 'str'and'int' objects

When using print(a, "b", c, d) you are passing multiple arguments and there is not need for concatenation. Each argument is transformed to a string before printing.

Post a Comment for "Python Integer And String Using"