What does ( + str(x) + ) mean?

hello,
In the tutorial I’m currently using, they give these examples to define a function, without explaining how the functions themselves work:

def multiply(x, y):
print(f’You called multiply(x,y) with the values x = {x} and y = {y}‘)
print(f’x * y = {x * y}’)

multiply(3, 2)

def f(x,y):
print('You called f(x,y) with the value x = ’ + str(x) + ’ and y = ’ + str(y))
print('x * y = ’ + str(x*y))

f(3,2)

I can understand the first one, not the second one.

  1. What is the meaning of “+ str(x) +” and why only one “+” in “+ str(y)”? I tried to remove those “+” but that results in an error. It must be a number, that’s all I can figure out.
  2. Is one of these functions better than the other?
1 Like

Here you have the following strings:

  1. "You called f(x,y) with the value x = "
  2. str(x)
  3. " and y = "
  4. str(y)

The + between those mean that the strings get concatenated (appended/combined).
str(<any variable>) just means that you convert the variable, for example the number x, to a string. Because you can only really concatenate strings, it is done here to turn x into a string, so it can be concatenated.

1 Like

About your second question:
The functions do the same thing but in a different way to show the different possibilities to do the same thing in Python.

The first function is “better” in today’s standards due to the following reasons:

  1. It is called multiply which is very descriptive, compared to the other function simply called f
  2. It uses f-strings, which are strings with an f before them. They are more readable because you can put the variables directly inside the string and they will automatically get converted to their str(variable) form instead of having to type it out.

That’s good news for me, because I can understand it. As for the second version, I still don’t understand how to extract the numerical values that will be multiplied. But since you’ve given me the necessary information, that should be enough to find the answer to this problem.

Thank you for your answers.

PS1: I should have thought of concatenation since I had already encountered it… but I see that since I didn’t reuse it, I quickly forgot about it.

PS2: Now that I know that ( + str(x) + ) has nothing to do with the value assigned to x, I understand that f(x, y) takes its values in the same way as multiply(x, y).

1 Like