0

why doesn't this code does not return the variable I expected ? I know this is not an efficient of doing it just curious what is the problem for this code

def format_name(f_name, t_name):
   switch_name = ""
   switch_name = f_name
   f_name = t_name
   t_name = switch_name

a = "Cinn"
b = "Alex"
format_name(a,b)
print(a)
print(b)
code cinn
  • 33
  • 4
  • 1
    what do you expect to happen? `format_name` never returns anything? –  Jan 03 '22 at 07:51
  • Does this answer your question? [Why can a function modify some arguments as perceived by the caller, but not others?](https://stackoverflow.com/questions/575196/why-can-a-function-modify-some-arguments-as-perceived-by-the-caller-but-not-oth) – Tomerikoo Jan 03 '22 at 09:38

2 Answers2

2

Alternatively you don't need a function for such a simple task use this syntax:

a = "Cinn"
b = "Alex"
a, b = b, a

If you insist on a function then just wanted to add a tiny little trick to @Robo's answer, you can directly store the values in a and b with tuple unpacking and not have to use indices.

# @Robo's code
def format_name(f_name, t_name):
   return t_name, f_name

a = "Cinn"
b = "Alex"
a, b = format_name(a,b) # tuple unpacking
Sujal Singh
  • 532
  • 1
  • 5
  • 14
1

That is happening because you've declared the variables a and b, and after calling the function you've printed a and b which have remained unchanged.

You need to return f_name and t_name in the function, and then print the returned things. So, a working solution would look like this:

def format_name(f_name, t_name):
   switch_name = ""
   switch_name = f_name
   f_name = t_name
   t_name = switch_name
   return f_name, t_name

a = "Cinn"
b = "Alex"
formatted = format_name(a,b)
print(formatted[0])
print(formatted[1])

But this uses way too much storage than is required, so just returning t_name and f_name in order, instead of f_name and t_name` will do everything better.

def format_name(f_name, t_name):
   return t_name, f_name

a = "Cinn"
b = "Alex"
formatted = format_name(a,b)
a, b = formatted
print(a)
print(b)
Robo
  • 660
  • 5
  • 22