Please clarify the explanation of Homework 2.2

It has been mentioned that the original procedure and procedure-1 are equivalent i.e.

Original procedure:

def proc(a,b):
  if test(a):
    return b
  return a

Procedure #1:

def proc1(x,y):
  if test(x):
    return y
  else:
    return x

Please clarify the following in this respect:

Q: Can a Python procedure return two values? For example can it return both a and b? I am asking this because in the original procedure b is returned only if test(a) becomes true. On the other hand the statement "return a" is outside the if... condition. So it should execute anyway. Now if test(a) evaluates to false, only a is returned. But if test(a) evaluates to true then b is returned as well as a .... is my understanding correct or wrong?

If so, how is Procedure #1 equivalent to the original procedure? It either returns x or y, depending on test(x), but not both.

asked 07 Mar '12, 21:55

Santanu%20Acharya's gravatar image

Santanu Acharya
516
accept rate: 133%

edited 07 Mar '12, 21:57


3 Answers:

A return automatically ends execution of the procedure and returns the parameters. So in that code there, ONLY b is returned if test(a) is true. the program never actually reaches the return a code.

Also, yes, you can return multiple values, for example; return a,b,c

link

answered 07 Mar '12, 22:01

Ioan-Victor%20Pantazi's gravatar image

Ioan-Victor ...
1.2k41541

edited 07 Mar '12, 22:02

I think the first proc use the shortcut instead of else keyword?? I also think you can return two things like this: return a, b. I do not know for sure if you can return two things consecutively, like this:
return a
return b
Because immediately the first return is reached, the second one will not be reached. Good luck.

link

answered 07 Mar '12, 21:59

Eenvincible's gravatar image

Eenvincible
3.6k164179

Ok...I think I get it. Once a return statement is issued, the execution of the procedure stops and it exits (that's the general behavior of return in most other languages...which I forgot :( ). So, if two separate return statements are there, only one should execute. As for returning two variables in the same return statement, maybe that would work. I'd check. Thanks for replying.

link

answered 07 Mar '12, 22:05

Santanu%20Acharya's gravatar image

Santanu Acharya
516

Your answer
Question text:

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "Title")
  • image?![alt text](/path/img.jpg "Title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×15,285
×74
×15

Asked: 07 Mar '12, 21:55

Seen: 109 times

Last updated: 07 Mar '12, 22:05