Python str () Function able to increment integers?

re: Python 3 loops section. I do not understand (in the code example below), how a string can be increased by 1. I would have written the print statement as follows: print(promise, (i + 1)) But I do not understand why the results are the same for both print statements. Thank you!

Code Example
promise = "I will finish the python loops module! "
for i in range(5):
print(promise + str(i + 1))

Code Example Output:
I will finish the python loops module! 1
I will finish the python loops module! 2
I will finish the python loops module! 3
I will finish the python loops module! 4
I will finish the python loops module! 5

Link to the code example: https://www.codecademy.com/courses/learn-python-3/lessons/learn-python-loops/exercises/range

1 Like

The string itself isn’t being increased by 1, a number (an int) you are using to make a string that’s printed is what’s being increased.

print(promise + str(i + 1))

Here,
i is an int
i + 1 is an int
str(i + 1) is a string
promise + str(i + 1) is a string
print(promise + str(i + 1)) prints that string to the screen (displays it in the console)

Notice that what’s inside the innermost ( ) gets done first.

1 Like

i think the person is asking why does these two statements can be executed, and resulted in the same answer.

I’m curious to know as well. How did the person get it executed.

print(promise, (i + 1))
# and
print(promise + str(i + 1))

# gives the same result

It’s not quite the same answer. Python will put a space between promise and (i + 1) in the first print statement (might not be clear as promise also ends in a space)

The first is separate variables, printed one after the other with spaces in between.
e.g
"I will finish the python loops module! " 4
The second is concatenating the string value of i+1 with promise to make one long string.
e.g
“I will finish the python loops module! 4”

1 Like

It’ll be nice you can set one documentation link here for @4007s to refer?

Looking forward!

1 Like

No special documentation needed, you can just check print in the standard docs (bookmark worthy for sure :slightly_smiling_face:)-
https://docs.python.org/3/library/functions.html#print

Note that it can take an arbitrary number of objects, when outputting them it uses the sep parameter to separate them which defaults to a single space ' ' so it acts like @pluginmaybe mentioned. If anyone wants to test try something like the following to compare-
print(1, 2, 3)
print(1, 2, 3, sep='\n')

The concatenation with + creates a singular new string object from the two parts before it’s ever passed to print (so the sep parameter is not used in that case).

1 Like

awesome @tgrtim ! Thanks for sharing the link to Python Ver3’s documentation.

Is really helpful to know more on why it behave in such manner despite is something we may/might overlook from day-to-day development practices.

1 Like