Quantcast

Got Homework?

Connect with other students for help. It's a free community.

  • across
    MIT Grad Student
    Online now
  • laura*
    Helped 1,000 students
    Online now
  • Hero
    College Math Guru
    Online now

Here's the question you clicked on:

55 members online
  • 0 replying
  • 0 viewing

David_Novo

Tuples I can't understand what the author means in this passage of "How to think like a computer scientist": "Functions can return tuples as return values. For example, we could write a function that swaps two parameters: def swap(x, y): return y, x Then we can assign the return value to a tuple with two variables: a, b = swap(a, b) In this case, there is no great advantage in making swap a function. In fact, there is a danger in trying to encapsulate swap, which is the following tempting mistake: def swap(x, y): # incorrect version x, y = y, x

  • one year ago
  • one year ago

  • This Question is Closed
  1. David_Novo
    Best Response
    You've already chosen the best response.
    Medals 0

    If we call this function like this: swap(a, b) then a and x are aliases for the same value. Changing x inside swap makes x refer to a different value, but it has no effect on a in __main__. Similarly, changing y has no effect on b. This function runs without producing an error message, but it doesn't do what we intended. This is an example of a semantic error."

    • one year ago
  2. David_Novo
    Best Response
    You've already chosen the best response.
    Medals 0

    When I run the following code: def swap(x,y): x,y = y,x return x,y a=1 b=2 a,b = swap(a,b) a becomes 2 and b becomes 1 Can anyone explain what the author is trying to say plz?

    • one year ago
  3. bwCA
    Best Response
    You've already chosen the best response.
    Medals 1

    the second - incorrect version - does not have a return statement which although it may look like it swaps x and y, it only affects variables local to the function and does not actually swap x and y in __main__.

    • one year ago
  4. David_Novo
    Best Response
    You've already chosen the best response.
    Medals 0

    Oh ok. I assumed that the return was still there. Without the return is quite obvious. Thank you.

    • one year ago
    • Attachments:

See more questions >>>

Your question is ready. Sign up for free to start getting answers.

spraguer (Moderator)
5 → View Detailed Profile

is replying to Can someone tell me what button the professor is hitting...

23

  • Teamwork 19 Teammate
  • Problem Solving 19 Hero
  • You have blocked this person.
  • ✔ You're a fan Checking fan status...

Thanks for being so helpful in mathematics. If you are getting quality help, make sure you spread the word about OpenStudy.

This is the testimonial you wrote.
You haven't written a testimonial for Owlfred.