Can't understand a part of the python course

In the full python course, under “3. Control Flow” in lecture number 10. Nested loops.
he writes a code like this:

for x in range(5):
for y in range(3):
print(f"({x}, {y}))

my question is, why format the last line? if this code is the same:

for x in range(5):
for y in range(3):
print((x, y))

The both give the same result…

In Mosh’s code, he is printing a formatted string. It would look the same doing print("(" + str(x) + ", " + str(y) + ")"). What you are creating with that double parentheses is a tuple, which you can verify by changing from a comma to any other symbol.

    print(f"({x}] {y})")

This prints: (4] 1)

But if you try print((x] y)) you will get an error and your program won’t run because you are now not using proper tuple syntax.

You can also verify this by adding the type keyword between your print:

for x in range(5):
    for y in range(3):
        print(type(f"({x}] {y})"))
        print(type((x, y)))

<class ‘str’>
<class ‘tuple’>

1 Like

Oh ok, I get it now, thank you for the information.
It’s probably because I’m very new, but what scenario will I need to format this type of data? because it is possible to print a str+int in the sentence isn’t it?

Example:
x = 1
y = 2
print(x, “This”, y, “Works”)

Yes, you can print a mix of integers and strings using commas, but it is just printing a list of them. That is why the commas are removed in the output.

What string format allows is for you to mix strings and other data types. It is extremely useful for printing a value:

Add a new variable z = “something”

print(f"The numbers are ({x}, {y}). The other variable contains: {z.capitalize()}")

The numbers are (4, 2). The other variable contains: Something