main.py:
import sys
sys.path.append('Pygame Projects')
import sub
from sub import *
loop = True
while loop:
print_hello()
true_the_another_loop()
while anotherLoop:
print_world()
sub.py:
def true_the_another_loop():
loop = False
anotherLoop = True
def print_hello():
print "hello"
def print_world():
print "world"
When I run main.py, it prints only "hello". Why is "world" not being printed?
In true_the_another_loop(), the line loop = Flase does not seem to be working.
You need to return the new values of those variables. Because they were just local variables, they are limited to only that function. You need to pass their values to the other variables.
...
while loop:
print_hello()
loop, anotherLoop = true_the_another_loop()
...
def true_the_another_loop():
loop = False
anotherLoop = True
return [loop,anotherLop]
Related
I am trying to create a list of functions in my program in order to use the random module to randomly choose. in theory it look and work with this
import random
def test1():
print("1st function")
def test2():
print("2nd function")
def test3():
print("3rd function")
def test_func():
test_list = [test1(), test2(), test3()]
apple = random.choice(test_list)
return print(apple)
test_func()
the result of this is it prints out test_list and prints "NONE" for apple is there a way to get it to randomly pick a function and only print that function.
you should add function reference to the list and call the function after.
def test_func():
test_list = [test1, test2, test3]
apple = random.choice(test_list)()
The problem here is that you are assigning the list the return values of the functions you created. Since they do not have a return value, it will be None.
What you need to do is assign the function itself by removing the parenthesis. You would also need to call the apple function by adding the parenthesis to it, not by printing it. So, your code will look like this:
import random
def test1():
print("1st function")
def test2():
print("2nd function")
def test3():
print("3rd function")
def test_func():
test_list = [test1, test2, test3]
apple = random.choice(test_list)
apple()
test_func()
def test1():
print("1st function")
#This returns "None"
The reason you are getting "None" printed to console is because you are printing the function, which does return a NoneType. Return defaults to None if not specified. To make it only print the desired function remove the line return print(apple)
You would also want to store references to your functions:
test_list = [test1, test2, test3]
so that they are not executed. Then you can run apple() to execute them in your main function.
Yes, just don't call the functions when you put them in the list:
import random
def test1():
print("1st function")
def test2():
print("2nd function")
def test3():
print("3rd function")
def test_func():
test_list = [test1, test2, test3]
apple = random.choice(test_list)
return apple() #won't return anything due to it being a print function
test_func()
I have used the following script to run the script directly and just to make a bash command line for running it outside the script (e.g. job scheduler).
def qsubcommand(func):
def wrapper(*args, **kwargs):
if kwargs.get('test', False):
cmdl = ' '.join(['this.py', func.__name__, *map(str, args)])
return cmdl
else:
return func(*args, **kwargs)
return wrapper
#qsubcommand
def calculate(value1, value2):
# do something
if __name__ == '__main__':
if len(sys.argv) > 1:
func, args = sys.argv[1], sys.argv[2:]
if func in locals().keys():
locals()[func](*args)
else:
raise NotImplementedError
I have a lot of functions like 'calculate'.
I'm working with the script for running and testing a program.
# When I want to run directly:
>>> calculate(4, 5)
# When I want to just print command line:
>>> calculate(4, 5, test=True)
'this.py calculate 4 5'
However, I want to use it in a context-dependent manner like below.
# When I want to run directly:
>>> test = False
>>> calculate(4, 5)
# When I want to just print command line:
>>> test = True
>>> calculate(4, 5)
'this.py calculate 4 5'
How can I modify to let the function recognize the variable outside the scope.
Is it possible to access a variable outside the function?
Thank you for your kind answers in advance.
Just put this on the part of the function where you want to check the variable:
if 'test' in globals() and test:
# do test
else:
# do normal
Functions can always access variables which are outside the function scope, they just can't edit them if you don't use the global keyword.
I would like to get the return data from a CAPL function called from python.
Please help me with this.
Currently I can only call the function with parameter in the example .
from win32com import client
import pythoncom
import time
function1 = None
canoe_app = None
is_running = False
class EventHandler:
def OnInit(self):
global canoe_app
global function1
function1 = canoe_app.CAPL.GetFunction('Test1')
def OnStart(self):
global is_running
is_running = True
canoe_app = client.Dispatch('CANoe.Application')
measurement = canoe_app.Measurement
measurement_events = client.WithEvents(measurement, EventHandler)
measurement.Start()
# The following loop takes care of any pending events and, once, the Measurement
# starts, it will call the CAPL function "function1" 10 times and then exit!
count = 0
while count < 10:
if (is_running):
ret = []
function1.Call(count)
function1.Call(count+1)
print(ret)
count += 1
pythoncom.PumpWaitingMessages()
time.sleep(1)
measurement.Stop()
You just have to assign the calling statement to a variable.
var1 = (int)function1.Call(count)
Note that the return variable type should only be int.
My code looks like:
def g_b():
items_in_bag = []
done=False
bugout_bag = 'Bug Out Bag'
while done == False:
item = input('What bags do you have? [Enter x to stop]')
items_in_bag.append(item)
if item == 'x':
done = True
items_in_bag.remove('x')
break
else:
continue
items_in_bag.append(bugout_bag)
print("Your bags\n")
print(items_in_bag)
return items_in_bag
def g_c():
coins_in_bag = []
done=False
while done == False:
coin_item = input('What coins do you have? [Enter x to stop]')
if coin_item == 'x':
done = True
break
else:
coins_in_bag.append(coin_item)
continue
print("Your coins\n")
print(coins_in_bag)
return coins_in_bag
def a_c_t_b(items_in_bag, coins_in_bag):
#print('Here are your coins:\n')
#g_c()
#print('Here are your bags:\n')
#print(items_in_bag)
print (items_in_bag,coins_in_bag)
return (items_in_bag,coins_in_bag)
def main():
g_b()
g_c()
a_c_t_b(items_in_bag,coins_in_bag)
main()
However, when i run this code like: import myfile
It gives me an error of:
File ".\myfile.py", line 51, i
a_c_t_b(items_in_bag,coins_in_bag)
NameError: global name 'items_in_bag' is not defined
I'm simply trying to return the values of items_in_bag,coins_in_bag from their respective functions.
Thank you
Please call your functions more sensible names.
To answer your question, your g_b and g_c functions return values, they don't return names. At the point where you call a_c_t_b, Python has no idea what items_in_bag is, because yo'uve never defined it. Python can't know you mean "the value returned from g_b": you have to tell it.
items_in_bag = g_b()
coins_in_bag = g_c()
a_c_t_b(items_in_bag, coins_in_bag)
You are calling g_b and g_c but never catching their returned values.
You can either do:
def main():
items_in_bag = g_b()
coins_in_bag = g_c()
a_c_t_b(items_in_bag, coins_in_bag)
or:
def main():
a_c_t_b(g_b(), g_c())
When you import the module main function is executed (call in last line). And main function use undefined identifiers items_in_bag and coins_in_bag:
def main():
g_b()
g_c()
a_c_t_b(items_in_bag,coins_in_bag)
Probably you want something like
def main():
items_in_bag = g_b()
coins_in_bag = g_c()
a_c_t_b(items_in_bag,coins_in_bag)
I'm trying to make a program that requires me to pass more than one list to a function. But when I return each list in the function I passed it to, they come up as 'none'.
This is a coding of how one of my lists are made then passed.
def somelist(magslist):
return magslist
def main():
alist = []
for i in range(5):
alist.append(i)
somelist(alist)
main()
try this:
def somelist(magslist):
return magslist
def main():
alist = []
for i in range(5):
alist.append(i)
print somelist(alist) # print it here only, for python3 use print with brackets
main()
Or:
def somelist(magslist):
return magslist
def main():
alist = []
for i in range(5):
alist.append(i)
return somelist(alist)
my_list = main() # my_list will save the list return my main function
print my_list
you dont need somelist function:
def main():
alist = []
for i in range(5):
alist.append(i)
return alist # return alist directly
my_list = main() # my_list will save the list return my main function
print my_list
The somelist() function is fine. The problem is that main() isn't returning anything after calling somelist().
A function which exits either by falling off the end (as yours does) or with a plain 'return' statement actually returns None
Change the last line of main() to
return somelist(alist)
then, you will need to print the results of the call to main() to see what it returns if you are not in a REPL.