how to use return statement inside function as it's not working in script but works in interactive mode [duplicate] - return

This question already has answers here:
"inconsistent use of tabs and spaces in indentation" [duplicate]
(29 answers)
Closed 3 years ago.
I'm using python 3.7.2 shell in linux mint 32bit.
when I run my def of factorial(as shown in code) it says that "" operator can't be apply for 'int' & 'nonetype' but i am using "" inside print function but that does no work.
even though i am not able to use return statements inside function in script mode although it works in interactive mode.
help me how can i use return statements inside function in script mode & please fix my factorial code so it works.
def factorial(n):
if n == 0:
results = print(1)
return results
else:
x = factorial(n-1)
result = print(n*x)
return result
factorial(4)
the error that i get when using this is
File "/home/Location", line 12, in factorial
result = print(n*x)
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
when i run in interactive mode it gave this error
SyntaxError: inconsistent use of tabs and spaces in indentation
I expect the factorial evaluation 4! = 24 but it gave the error shown 2nd code in script mode, and 3rd code error in interactive mode.

print(1) will return NoneType and hence when you do a recursive call, instead of 1, you are actually sending NoneType. Separate the assignment and print as shown below and your program works:
def factorial(n):
if n == 0:
results = 1
print(results)
return results
else:
x = factorial(n-1)
result = n*x
print (result)
return result
factorial(4)

The issue is that you try to multiply a number with the result of print, which is of type NoneType, thus the error. Your factorial function should return a number, instead of printing it.
This code works:
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)
And only then should you print your results, for example by:
print(factorial(10))

Related

What does local _, x = ... do in lua?

I'm looking at some lua code on github which consists of many folders and files. Next to external libraries, each file starts with:
local _,x = ...
Now my question is, what is the purpose of this, namely the 3 dots? is it a way to 'import' the global values of x? In what way is it best used?
... is the variable arguments to the current function.
E.g.:
function test(x, y, ...)
print("x is",x)
print("y is",y)
print("... is", ...)
local a,b,c,d = ...
print("b is",b)
print("c is",c)
end
test(1,2,"oat","meal")
prints:
x is 1
y is 2
... is oat meal
b is meal
c is nil
Files are also treated as functions. In Lua, when you, or someone else, loads a file (with load or loadfile or whatever), it returns a function, and then to run the code, you call the function. And when you call the function, you can pass arguments. And none of the arguments have names, but the file can read them with ...
They are arguments from the command line.
Read lua's reference manual, in the chapter Lua Standalone, it says:
...If there is a script, the script is called with arguments arg[1], ···, arg[#arg]. Like all chunks in Lua, the script is compiled as a vararg function.
For example if your lua script is run with the command line:
lua my_script.lua 10 20
In my_script.lua you have:
local _, x = ...
Then _ = "10" and x = "20"
Update when a library script is required by another script, the meaning of the 3 dots changes, they are arguments passed from the require function to the searcher:
Once a loader is found, require calls the loader with two arguments: modname and an extra value, a loader data, also returned by the searcher.
And under package.searchers:
All searchers except the first one (preload) return as the extra value the file name where the module was found
For example if you have a lua file that requires my_script.lua.
require('my_script')
At this time _ = "my_script" and x = "/full/path/to/my_script.lua"
Note that in lua 5.1, require passes only 1 argument to the loader, so x is nil.

.fsx script ignoring a function call when I add a parameter to it

Alright, so I'm a happy fsx-script programmer, because I love how I can have the compiler shout at me when I do mistakes before they show up at runtime.
However I've found a case which really bothers me because I was expecting that by doing some refactoring (i.e.: adding an argument to a function) I was going to be warned by the compiler about all the places where I need to put the new argument. But, not only this did not happen, fsharpi ran my script and ignored the function call completely!! :(
How can I expect to refactor my scripts if this happens?
Here is my code:
let Foo (bar: string) =
Console.WriteLine("I received " + bar)
Foo("hey")
It works.
Now, later, I decide to add a second argument to the function (but I forget to add the argument to all the calls to it):
let Foo (bar: string) (baz: bool) =
Console.WriteLine("I received " + bar)
Foo("hey")
The result of this is: instead of the compiler telling me that I'm missing an argument, it is fsharpi running the script and ignoring the call to Foo! Why?
PS: I know the difference between currying and tuples, so I know Foo("hey") becomes a function (instead of a function call), because of partial application. But I want to understand better why the compiler is not expecting a function evaluation here, instead of seeing a function and ignoring it. Can I enable a warningAsError somehow? I would like to avoid resorting to using tuples in order to workaround this problem.
The fsharpi (or fsi if you're on Windows) interpreter makes no distinction between running a script and typing code at the interactive prompt (or, most often, submitting code from your editor via a select-and-hit-Alt-Enter keyboard shortcut).
Therefore, if you got what you're asking for -- fsharpi issuing a warning whenever a script line has a return value that isn't () -- it would ruin the value of fsharpi for the most common use case, which is people using an interactive fsharpi session to test their code, and rapidly iterate through non-working prototypes to get to one that works correctly. This is one of F#'s great strengths, and giving you what you're asking for would eliminate that strength. It is therefore never going to happen.
BUT... that doesn't mean that you're sunk. If you have functions that return unit, and you want fsharpi to give you a compile-time error when you refactor them to take more arguments, you can do it this way. Replace all occurrences of:
Foo("hey")
with:
() = Foo("hey")
As long as the function Foo has only one argument (and returns null), this will evaluate to true; the true value will be happily ignored by fsharpi, and your script will run. However, if you then change Foo to take two arguments, so that Foo("hey") now returns a function, the () = Foo("hey") line will no longer compile, and you'll get an error like:
error FS0001: This expression was expected to have type
unit
but here has type
'a -> unit
So if you want fsharpi to refuse to compile your script when you refactor a function, go through and change your calls to () = myfunc arg1 arg2. For functions that don't return unit, make the value you're testing against a value of that function's return type. For example, given this function:
let f x = x * 2
You could do
0 = f 5
This will be false, of course, but it will compile. But if you refactor f:
let f x y = x * 2 + y
Now the line 0 = f 5 will not compile, but will give you the error message:
error FS0001: This expression was expected to have type
int
but here has type
int -> int
To summarize: you won't ever get the feature you're looking for, because it would harm the language. But with a bit of work, you can do something that fits your needs.
Or in other words, as the famous philosopher Mick Jagger once put it:
You can't always get what you want. But if you try, sometimes you might find you get what you need.

Lua script wont accept args

I was trying to get an hologram projector working, but in run into these errors:
bad arguments #3 (number expected, got no value)
My script is:
local component = require("component")
local hologram = component.hologram
function setVoxel(x, y, z, value)
print(x)
print(y)
print(z)
print(value)
local current = hologram.get(x, z)
local positiveMask = bit32.lshift(1, y - 1)
if value then
hologram.set(x, z, bit32.bor(current, positiveMask))
else
local negativeMask = bit32.bnot(positiveMask)
hologram.set(x, z, bit32.band(current, negativeMask))
end
end
local args = {...}
print(args[1])
print(args[2])
print(args[3])
print(args[4])
setVoxel(tonumber(args[1]), tonumber(args[2]), tonumber(args[3]), args[4])
I used:
holo-set 8 16 20 true
The print commands returned:
8
16
20
true
but its not working.
I have checked the spelling.
Also the hologram is correctly initialized.
That error means some function (what's the rest of the error?) which expected to get three arguments only got two.
Given that code snippet the only function I can see to which that might apply is hologram.get.
Which, given a quick look at the documentation (thank you Google), does in fact appear to require three arguments.
get(x:number, y:number, z:number):number
Returns the value at the specified position.

Hello metatable.__len world

A beginner's question about Lua and metatables, with a example as simple as an Hello‑World, involving the len event, which unfortunately does not returns the expected result (I'm using Lua 5.1 installed from Ubuntu's official repository).
The case
Here is the example:
Test_Type = {};
function Test_Type.__len (o)
return 1;
end;
function new_test ()
local result = {};
setmetatable(result, Test_Type);
return result;
end;
do
local a_test = new_test();
print (#a_test);
print(getmetatable(a_test).__len(a_test));
end;
And the result I get:
0
1
I was expecting the first print statement to display 1, but it displays 0, to my big surprise.
What did I missed?
According to Lua Reference Manual — Metatables and Metamethods, the # is equivalent to this:
function len_event (op)
if type(op) == "string" then
return strlen(op) -- primitive string length
else
local h = metatable(op).__len
if h then
return (h(op)) -- call handler with the operand
elseif type(op) == "table" then
return #op -- primitive table length
else -- no handler available: error
error(···)
end
end
end
So print (#a_test); and print(getmetatable(a_test).__len(a_test)); should result into the same, isn't it?
By the way, why is the above excerpt from the Reference Manual refers to metatable(op) while it should be getmetatable(op)? At least I've tried print(metatable(a_test).__len(a_test));, and it ends into an error.
Answer
As Nneonneo noticed, this is an issue with the Lua version in use. Lua 5.2 seems to be required for the above to work.
From http://lua-users.org/wiki/LuaFaq:
Why doesn't the __gc and __len metamethods work on tables?
__len on tables is scheduled to be supported in 5.2. See LuaFiveTwo.
Since you're using 5.1, __len on tables does not work. Indeed, running your code on Lua 5.2 produces
1
1
as expected.

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

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

Resources