Python Forum
I am trying to swap two variables with a Function....
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I am trying to swap two variables with a Function....
#4
The swapping with temporary variables is error prune.
Here an example with swapping:
def fib(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
        yield(a)
And now the complicated version:
def fib(n):
    a, b = 0, 1
    for _ in range(n):
        x = a + b
        a = b
        b = x
        yield(a)
Also a function should never change values outside of the function. This leads into an unexpected behavior. You can do this with short code.
In bigger projects, this is the opening of hell's gates. You deserve what you get.

In earlier programming languages there was a big difference between functions and procedures. A function is just something to do a calculation without affecting the outside world. A procedure was affecting the outside world, like printing on a terminal or printer.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: I am trying to swap two variables with a Function.... - by DeaD_EyE - Mar-04-2019, 08:53 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to print variables in function? samuelbachorik 3 936 Dec-31-2022, 11:12 PM
Last Post: stevendaprano
  User-defined function to reset variables? Mark17 3 1,694 May-25-2022, 07:22 PM
Last Post: Gribouillis
  How to swap two numbers in fields in python Joni_Engr 5 1,918 Jan-11-2022, 09:43 AM
Last Post: menator01
  Swap key and value of a dictionary - and sort it Omid 4 2,878 Oct-28-2020, 01:24 PM
Last Post: Omid
  Do I have to pass 85 variables to function? Milfredo 10 4,367 Sep-26-2020, 10:13 PM
Last Post: Milfredo
  print function help percentage and slash (multiple variables) leodavinci1990 3 2,524 Aug-10-2020, 02:51 AM
Last Post: bowlofred
  Issues with storing variables outside of a function cerulean747 7 3,770 Apr-30-2020, 08:46 AM
Last Post: DeaD_EyE
  Where to put the global keyword when assigning variables outside a function? new_to_python 8 3,075 Feb-09-2020, 02:05 PM
Last Post: new_to_python
  making a function that writes variables (is possible?) miker2808 3 2,385 Jan-30-2020, 06:27 PM
Last Post: buran
  swap elements in list hshivaraj 3 12,580 Apr-22-2019, 09:23 AM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020