I am trying to use "return" statement in Python it is not working. [closed] - return

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to use the return statement. If the y is negative then program will terminate. But it is showing "ValueError: math domain error"
import math
y=-5
def df(y):
if y<=0:
print y, "is negative"
return
result = math.log(y)
print "The log of y is",result

I have this feeling you wanted to include your log call inside the df() function and just check it for negative first.
import math
y=-5
def df(y):
if y<=0:
print y, "is negative"
return
result = math.log(y)
return result
print "The log of y is", df(y)
To have your function return a value you have to specify what it should return. Otherwise it returns None

Return transfers control back to the caller. In this case, if you wanted to get the value of the function, you would need to call it, and you would need the function to actually return something. Perhaps something along these lines:
import math
def df(v):
if v <= 0:
print v, "is negative"
return
y = -5
df(y)
result = math.log(y)
print "The log of y is",result
Though I'm not really sure what you're trying to do. If you wanted your function to return something, you would use this syntax:
return [something]
... replacing [something] with the value or variable whose value you want to return. math.log returns the logarithm of its argument. You already know how to save the return value of a function:
You expect this to cause the program to exit. Returning will only exit the program if used from the main method, i.e. outside of any functions. Return gives control back to the calling routine (if there is no calling routine, the program exits). You would want to use the exit call instead:
import sys
...
sys.exit(0)
sys.exit will immediately terminate the program, passing the provided value back to the calling program. If you do not know what this is, you can use the value 0.
result = math.log(y)
As for your error message, you can't take the logarithm of a negative number, try a positive one instead. (not 0 either)
I think you want something like this:
import math
def df(v):
if v <= 0:
print v, "is negative"
return True # returns true if the value is negative or zero
return False # otherwise returns false
y = -5
if df(y): # test if negative or positive, branch on return value
return # if value was negative or zero, return (exit program)
result = math.log(y)
print "The log of y is",result

Your return is empty....there is no variable name or value on the same line with "return". For example, if you wanted to return the value 5, you'd put
return 5
If you wanted to return a variable foo, you'd put
return foo
Right now you are returning nothing.
Maybe you want this?
import math
y=-5
def df(y):
if y<=0:
print y, "is negative"
return "impossible to calculate"
result = math.log(y)
return result
print "The log of y is", df(y)

Any function needs 3 parts, as I learned for programming:
(1) input, as you "def" a function, you need to know what you want to put into the function.
For example:
def function (input1, input2):
We also called those inputs as parameters.
(2) you need to show the output:
For example, on the code you provide, if you want to return the number that variable "result" holds, you can do:
return result
or if you do not want to return, or output, anything, you can do:
return None
In python, None means nothing, at least you can think it that way for now.
(3)Function is doing things for you, so the things between
def function(inputs):
to
return None
is what you have to modify the variable from inputs into return (or output).
Hope it helps, and always work before ask any question. Good luck on Python

Related

Infinite loop bug in Lua

I'm new to this platform and I'm still learning to
program in Lua, so, if any newbie errors appear, forgive me.
The following code is from one of the functions in my project that reads the insert
of the user and validates whether or not it is a data of type "Number". If,
the loop will be broken and the function will return the user input, otherwise, the
program will ask the user to enter the data again:
function bin.readnum(text)
local insertion
if text == nil then text = "Text: " end
while (insertion == nil) do
insertion = nil
print(text)
insertion = io.read("number")
if insertion ~= nil then break end
end
return insertion
end
But, if the user enters a wrong data (string) the function prints the text
madly instead of asking the user to re-enter the data.
When io.read fails to parse the data it got into a number, it doesn't discard it, but instead leaves it in the buffer for the next call to it. That means that in your code, instead of letting the user enter something else, it'll just keep trying to parse the same non-number forever. To fix it, in your if insertion ~= nil then block, do io.read() right before break, to read and discard the whole invalid line.
In addition to what Joseph Sible said:
io.read("number") is wrong: 5.1 docs demand "*n" and 5.4 docs demand just "n" for reading numbers. It probably works nevertheless due to Lua just searching for the chars in the string.
I recommend just replacing insertion = io.read("number") withinsertion = tonumber(assert(io.read(), "EOF")) - this will read a line and try to parse it as a number; the assert gracefully deals with nil being returned by io.read for EOF.
You don't need to set insertion to nil, the later assignment will do that already if what was read is not a valid number.
Style: Consider replacing your explicit nil checks with truthiness checks and removing the parentheses around the while-condition. You don't need a break, you can immediately return the read number; finally, you can even replace the entire loop with tail recursion.
All in all I'd rewrite it as follows:
function bin.readnum(text)
print(text or "Text: ")
local num = tonumber(assert(io.read(), "EOF"))
if num then return num end
return bin.readnum(text)
end
or alternatively using a repeat-until loop:
function bin.readnum(text)
local num
repeat
print(text or "Text: ")
num = tonumber(assert(io.read(), "EOF"))
until num
return num
end

How can a comma-separated return statement in Lua act as a function call?

I'm new to Lua and trying to figure out how the return statement in the squares function below is being used in the following code snippet:
function squares(iteratorMaxCount)
return square,iteratorMaxCount,0
end
The square parameter in the return statement refers to a function with the following signature:
function square(iteratorMaxCount,currentNumber)
What's confusing me is that the return statement looks like it's returning three values. What I think it's actually doing, however, is passing iteratorMaxCount and 0 as the arguments to a square function call.
Can anyone explain to me what's happening with this syntax? How is this serving as a function call as opposed to returning three values? In my mind, it feels as though the return statement should be written return square(iteratorMaxCount, 0) as opposed to return square, iteratorMaxCount, 0. I know that this is obviously wrong, but I can't figure out why.
I've tried searching through the Lua Manual, Lua Reference Guide, and searching Google, but I can't seem to find anything that explains this particular syntax. Can anyone point me in the right direction, please?
Thanks in advance.
Full code below via
Tutorialspoint
function square(iteratorMaxCount,currentNumber)
if currentNumber<iteratorMaxCount
then
currentNumber = currentNumber+1
return currentNumber, currentNumber*currentNumber
end
end
function squares(iteratorMaxCount)
return square,iteratorMaxCount,0
end
for i,n in squares(3)
do
print(i,n)
end
squares really does return three values, the first of which is a function. squares does not call square at all.
The trick here is how the for ... in syntax works. In the Lua 5.3 Reference Manual, section 3.3.5 says:
A for statement like:
for var_1, ···, var_n in explist do block end
is equivalent to the code:
do
local f, s, var = explist
while true do
local var_1, ···, var_n = f(s, var)
if var_1 == nil then break end
var = var_1
block
end
end
So the keyword "in" needs to be followed by three values:
an "iterator function" for getting the variables in each iteration
a "state" value to pass to the function each time
an initial value to pass to the function the first time
After the first time the function is called, the first value from the previous call is passed back into the next function call. When the first value returned from the function is nil, the for loop ends.
So in this example, squares(max) is designed to be used after "in", using square as the iterator function, max as the "state", 0 as the initial value, and a number and its square as the loop data values.

Finding the number of digits in a number restricted number of tools since I am a Python beginner

def digits(n):
total=0
for i in range(0,n):
if n/(10**(i))<1 and n/(10**(i-1))=>1:
total+=i
else:
total+=0
return total
I want to find the number of digits in 13 so I do the below
print digits(13)
it gives me $\0$ for every number I input into the function.
there's nothing wrong with what I've written as far as I can see:
if a number has say 4 digits say 1234 then dividing by 10^4 will make it less than 1: 0.1234 and dividing by 10^3 will make it 1.234
and by 10^3 will make it 1.234>1. when i satisfies BOTH conditions you know you have the correct number of digits.
what's failing here? Please can you advise me on the specific method I've tried
and not a different one?
Remember for every n there can only be one i which satisfies that condition.
so when you add i to the total there will only be i added so total returning total will give you i
your loop makes no sense at all. It goes from 0 to exact number - not what you want.
It looks like python, so grab a solution that uses string:
def digits(n):
return len(str(int(n))) # make sure that it's integer, than conver to string and return number of characters == number of digits
EDIT:
If you REALLY want to use a loop to count number of digits, you can do this this way:
def digits(n):
i = 0
while (n > 1):
n = n / 10
++i
return i
EDIT2:
since you really want to make your solution work, here is your problem. Provided, that you call your function like digits(5), 5 is of type integer, so your division is integer-based. That means, that 6/100 = 0, not 0.06.
def digits(n):
for i in range(0,n):
if n/float(10**(i))<1 and n/float(10**(i-1))=>1:
return i # we don't need to check anything else, this is the solution
return null # we don't the answer. This should not happen, but still, nice to put it here. Throwing an exception would be even better
I fixed it. Thanks for your input though :)
def digits(n):
for i in range(0,n):
if n/(10**(i))<1 and n/(10**(i-1))>=1:
return i

Logic behind COBOL code

I am not able to understand what is the logic behind these lines:
COMPUTE temp = RESULT - 1.843E19.
IF temp IS LESS THAN 1.0E16 THEN
Data definition:
000330 01 VAR1 COMP-1 VALUE 3.4E38. // 3.4 x 10 ^ 38
Here are those lines in context (the sub-program returns a square root):
MOVE VAR1 TO PARM1.
CALL "SQUAREROOT_ROUTINE" USING
BY REFERENCE PARM1,
BY REFERENCE RESULT.
COMPUTE temp = RESULT - 1.843E19.
IF temp IS LESS THAN 1.0E16 THEN
DISPLAY "OK"
ELSE
DISPLAY "False"
END-IF.
These lines are just trying to test if the result returned by the SQUAREROOT_ROUTINE is correct. Since the program is using float-values and rather large numbers this might look a bit complicated. Let's just do the math:
You start with 3.4E38, the squareroot is 1.84390889...E19.
By subtracting 1.843E19 (i.e. the approximate result) and comparing the difference against 1.0E16 the program is testing whether the result is between 1.843E19 and 1.843E19+1.0E16 = 1.844E19.
Not that this test would not catch an error if the result from SQUAREROOT_ROUTINE was too low instead of too high. To catch both types of wrong results you should compare the absolute value of the difference against the tolerance.
You might ask "Why make things so complicated"? The thing is that float-values usually are not exact and depending on the used precision you will get sightly different results due to rounding-errors.
well the logic itself is very straight forward, you are subtracting 1.843*(10^19) from the result you get from the SQUAREROOT_ROUTINE and putting that value in the variable called temp and then If the value of temp is less than 1.0*(10^16) you are going to print a line out to the SYSOUT that says "OK", otherwise you are going to print out "False" (if the value was equal to or greater than).
If you mean the logic as to why this code exists, you will need to talk to the author of the code, but it looks like a debugging display that was left in the program.

Assigning the same value twice in Erlang

Is it a kind of a small bug or made intentionally, that when I assign the same value to a variable more than once, it doesn't throw an error, but, like, assigns it again?
Here is an example:
X = 1,
X = 100 - 99,
X = 1,
X = list_to_integer("1"),
X = X.
Shouldn't it throw an error? Throwing an error could mean that some part of the code is trying to reassign the variable, and it can be just a luck that it's the same as it was before.
It's not actually an assignment, but a match operation (the equal sign is actually the match operator). See http://erlang.org/doc/reference_manual/patterns.html
What actually happens is that you are trying to "pattern match" what's on the left side of the operator (=) against what's on the right side.
If there's a variable on the left side and it's not bounded yet, it will be bounded to the value you have on the right side.
On the other hand, if the variable is already bound and the value is the same as what's on the right side of the operator, nothing happens, the matching just succeeds.
If the values are different, there's a pattern matching error.
Note that the special variable "_" will always succeed when pattern matching any value.
Pattern matching in Erlang is really helpful, because you can fail fast when something's wrong. For example in this code:
{ok, Value} = some_function()
If some_function/0 returns something like {error, _} your code will just crash and you don't risk to continue execution with invalid values.
If some_function returns the expected value, the variable Value will be now be bounded to that result, it's like having an assignment and an assertion in one line of code (if you want to look at it that way).
Makes sense?

Resources