Python 2.7.5, using a loop within a function and calling the function - function

I can't seem to get user input for a number of times to display. For example, if the input is
Jeff 6
The output should be
Jeff
Jeff
Jeff
Jeff
Jeff
Jeff
I'm new to functions in Python, but here is my code thus far:
def getName():
name = raw_input("please enter name")
return name
def getRepval():
irepnum = float(raw_input("please enter number to show name entered"))
return irepnum
def inamed(name, irepnum):
count = 1 #the loop to show the name entered by the user
while irepnum != count:
print name
count += 1 #do I need to use return??
def main(): #having the main func like this gives me an infinite loop
irepnum = 0
iname = getName() #I think my problem is somewhere here.
irepnum = getRepval()
inamed(irepnum,name)
main()

You need to call inamed(iname, irepnum), not inamed(irepnum, name), as you are doing now.
Other than the obvious mistake of name not being defined (the actual variable is called iname), the wrong order causes irepnum in the function to be set to a string the user entered as name. Since count, no matter how large, never compares equal to the passed string, the code loops infinitely.
Several tips:
Learn to use the for loop and xrange. The idiom you want is for count in xrange(irepnum):. (Using it would have prevented this bug.)
Give more distinctive names to your identifiers. Currently you have an inamed function and an iname variable. Confusing.
Don't use floats where an int would suffice. Misusing floats is asking for trouble.

Related

Function with for loop - How to return in vb | UFT

I would need support for that. I guess it's an easy one but i would like to get different approach if possible.
I have the following Function and i just want to return value. If possible within a string variable.
StrVal = "123 Test"
Function IsHaving(StrVal)
Set reg1 = New RegExp
reg1.Gloabl=True
reg1.IgnoreCase=False
reg1.Pattern="\d+"
Set mats = reg.Execute(StrVal)
For Each mat In mats
return mat.Value
Next
End Function
And then passing the value returned in another string
StrNum = IsHaving(StrVal)
I would like to do this way but i am not sure that in vb i can return from a loop for ( within the Function).
Some ideas on that ?

Lua - same result of using and not using "self"

Ok here goes...
I have been experimenting on various examples of declaring functions with "self" in the parameters.
I don't have full understanding of this which is what I'm trying to fully understand. I'm a complete beginner, but I am compelled to grasp this fully.
The 2 examples below return the same results, although in example 2, if I don't declare "self = {}" within the function, I need to place "self" (or the ":") in the function parameters for it to work. Is this the whole deal with "self"?
Are there other implications when using "self"?
Example 1
function Character.new(x)
self = {}
self.name = x
return self.name
end
a = Character
b = Character
hobbit = a.new ("Frodo")
dragon = b.new ("Smaug")
print (hobbit)
print (dragon)
Example 2
Character = {}
function Character:new(x)
self.name = x
return self.name
end
a = Character
b = Character
hobbit = a:new ("Frodo")
dragon = b:new ("Smaug")
print (hobbit)
print (dragon)
;^)
Zalokin
You're using global variables when you should be creating instances.
Try these lines instead, they may help you understand:
-- example 1
print (hobbit)
print(self.name)
print (dragon)
print(self.name)
and
-- example 2
print (hobbit)
print(Character.name)
print (dragon)
print(Character.name)
: lets you access the table which includes the function from within the function without an explicit (first argument) pass. It can be used both when defining and calling a function.
The example below contains a table t. The table has 3 functions (a,b and c) and a string entry under the key greeting.
All the function/method calls print the same string "hello user".
Notice how you can still call a method (a function which has its container table as the first argument) the same way as a normal function, but you have to explicitly pass the table as the first argument.
The self argument can be called what ever you want and you can still call the function with a : as long as you use the correct argument name inside the function (not self in this case). The function c serves as an example of that.
It is basically just syntax sugar.
local t = {}
t.greeting = "hello"
function t:a(name)
print(self.greeting, name)
end
function t.b(self, name)
print(self.greeting, name)
end
function t.c(myself, name)
print(myself.greeting, name)
end
t.a(t, "user")
t:a("user")
t.b(t, "user")
t:b("user")
t.c(t, "user")
t:c("user")

Function to convert a decimal into that of any base

I am doing this question via an Online learning platform, and there are test cases assigned which i must pass. The topic is Higher Order Functions.
Here is the question:
Write a function make_decimal_to_n_ary_converter that accepts a number n where 1 < n < 17, and returns a number converter that converts a given decimal number into that of base n.
Below is my code(I am supposed to use an inner function i.e converter(x))
def make_decimal_to_n_ary_converter(n):
def converter(x):
if x==0 or x==1:
return x
i=x
b=('A','B','C','D','E','F')
result = ""
while i>0:
a=i%n #3
if a<10:
result = str(i%n)+result
else:
d=a-10
result = b[d] + result
i=i//n
return result
return converter
#Lines below are not to be changed, part of qn
decimal_to_binary = make_decimal_to_n_ary_converter(2)
decimal_to_octal = make_decimal_to_n_ary_converter(8)
decimal_to_hexadecimal = make_decimal_to_n_ary_converter(16)
Here are some test cases that my code passes:
decimal_to_binary(213)
11010101
decimal_to_octal(213)
325
decimal_to_hexadecimal(213)
D5
make_decimal_to_n_ary_converter(15)(213)
E3
However, my code fails some private test cases, and feedback that i received was that my logic in the while loop is wrong. However, after printing some numbers, i failed to see anything wrong.
Would appreciate any help, thank you!
Solved it. My mistake was that for base cases x , i had to return a string instead.

Reuse coroutine with different arguments per call in lua

I found it really useful to reuse a once created coroutine. I found a solution to that and it looks like so:
co = coroutine.create(function (f, args)
while f do
f = coroutine.yield(f(args))
end
end)
function dummyFunc(data)
print("XXX "..data)
coroutine.yield()
print("OOO "..data)
end
coroutine.resume(co, dummyFunc, "1")
coroutine.resume(co, dummyFunc, "2")
coroutine.resume(co, dummyFunc, "3")
coroutine.resume(co, dummyFunc, "4")
That work like a charm except the output is not:
XXX 1
OOO 2
XXX 3
OOO 4
It is:
XXX 1
OOO 1
XXX 1
OOO 1
So is it possible to change the arguments to the dummyFunc between the resume calls?
Think about this. The way coroutines work is like this. When you first resume them, the arguments you pass to resume become the arguments to the coroutine's function. When the coroutine yields, the arguments it passes to yield become the return values from your resume call.
However, the second time you resume the coroutine, it does not reach into the still executing function and change the arguments that were pass in the first time. It would be exceedinly rude to change the value of variables local to the function.
Therefore, the arguments to resume on calls after the first call will be the return values from yield.
co = coroutine.create(function (f, args)
while f do
f = coroutine.yield(f(args))
end
end)
So you'd need to do this:
co = coroutine.create(function (f, args)
while f do
f, args = coroutine.yield(f(args))
end
end)
However, if you want something more flexible, that can do variable numbers of arguments, you'll need to be cleverer:
co = coroutine.create(function (...)
local function capture_args(...)
return {...}, select("#", ...)
end
local tbl, len = capture_args(...)
local f = tbl[1]
while f do
tbl, len = capture_args(coroutine.yield(f(unpack(tbl, 2, len))
f = tbl[1]
end
end)
Some people wouldn't bother with the capture_args stuff, simply relying on {...} and calling unpack on it. This is safer because users can put nil values in parameter lists. ... will record all of the parameters, even embedded nils (but not trailing ones). However, once you put it into an array, the length of the array is based on the first nil value.
Using capture_args, you can get the actual parameter count thanks to a little-known-feature of select. And thanks to the ability of unpack to work on a given range, even if the range exceeds the length of the table, you can effectively store a parameter list.
I could probably make capture_args a bit cleverer by putting the length in the table it returns. But this is good enough for me.
There is a second problem here: you are yielding within dummyFunc, and dummyFunc does not seem to understand what to do with yield's return values (ie: the parameters to your next resume call).
It's not clear how you want dummyFunc to respond to it. If you wanted dummyFunc's parameters to change because of how you resumed it without dummyFunc knowing about it, that's not going to happen.

Lua - Execute a Function Stored in a Table

I was able to store functions into a table. But now I have no idea of how to invoke them. The final table will have about 100 calls, so if possible, I'd like to invoke them as if in a foreach loop. Thanks!
Here is how the table was defined:
game_level_hints = game_level_hints or {}
game_level_hints.levels = {}
game_level_hints.levels["level0"] = function()
return
{
[on_scene("scene0")] =
{
talk("hint0"),
talk("hint1"),
talk("hint2")
},
[on_scene("scene1")] =
{
talk("hint0"),
talk("hint1"),
talk("hint2")
}
}
end
Aaand the function definitions:
function on_scene(sceneId)
-- some code
return sceneId
end
function talk(areaId)
-- some code
return areaId
end
EDIT:
I modified the functions so they'll have a little more context. Basically, they return strings now. And what I was hoping to happen is that at then end of invoking the functions, I'll have a table (ideally the levels table) containing all these strings.
Short answer: to call a function (reference) stored in an array, you just add (parameters), as you'd normally do:
local function func(a,b,c) return a,b,c end
local a = {myfunc = func}
print(a.myfunc(3,4,5)) -- prints 3,4,5
In fact, you can simplify this to
local a = {myfunc = function(a,b,c) return a,b,c end}
print(a.myfunc(3,4,5)) -- prints 3,4,5
Long answer: You don't describe what your expected results are, but what you wrote is likely not to do what you expect it to do. Take this fragment:
game_level_hints.levels["level0"] = function()
return
{
[on_scene("scene0")] =
{
talk("hint0"),
}
}
end
[This paragraph no longer applies after the question has been updated] You reference on_scene and talk functions, but you don't "store" those functions in the table (since you explicitly referenced them in your question, I presume the question is about these functions). You actually call these functions and store the values they return (they both return nil), so when this fragment is executed, you get "table index is nil" error as you are trying to store nil using nil as the index.
If you want to call the function you stored in game_level_hints.levels["level0"], you just do game_level_hints.levels["level0"]()
Using what you guys answered and commented, I was able to come up with the following code as a solution:
asd = game_level_hints.levels["level0"]()
Now, asd contains the area strings I need. Although ideally, I intended to be able to access the data like:
asd[1][1]
accessing it like:
asd["scene0"][1]
to retrieve the area data would suffice. I'll just have to work around the keys.
Thanks, guys.
It's not really clear what you're trying to do. Inside your anonymous function, you're returning a table that uses on_scene's return value as keys. But your on_scene doesn't return anything. Same thing for talk.
I'm going to assume that you wanted on_scene and talk to get called when invoking each levels in your game_level_hints table.
If so, this is how you can do it:
local maxlevel = 99
for i = 0, maxlevel do
game_level_hints.levels["level" .. i] = function()
on_scene("scene" .. i)
talk("hint" .. i)
end
end
-- ...
for levelname, levelfunc in pairs(game_level_hints.levels) do
levelfunc()
end