Jumping to function - python

I have a problem with functions. I want to know is it possible to when calling function second time program jump to that line of code, just like in assembler where would I use jmp directive. So when I firstly call decision_function after that some calc_funcs are done ( it doesn't matter what they do ), but when I call that same decision function second time I don't get execution of calc funcs.
def main():
decision_function()
calc_function1()
calc_function2()
calc_function3()
decision_function(reqierment)
def decision_function(reqierment=None):
if reqierment is None:
do this
else:
do that

I prefer using setting a variable to true:
skipper = true
def main():
decision_function()
calc_function1()
calc_function2()
calc_function3()
decision_function(reqierment)
def decision_function():
if skipper == True:
do this
skipper = False
else:
do that

Related

Is there an easy way to thread or multiprocess a non-intensive function?

I'm self-learning python so I don't know how to describe this in a way that would be clear, so here's the easiest by proxy example I can come up with in pseudo code:
#where r() is a random number function
objCount = 0
def mainfunc()
while playgame= True and objCount < 100:
create(r(time))
time.sleep(1)
return None
def create(tmptime)
global objCount
objCount = objCount+1
newobj = plotSomething(r(x),r(y))
time.sleep(tmptime)
selfDelete..
return None
mainfunc() #run it
Instead of it making a random "lived" object every second, it makes a random lived object every second, but waits for it's "life" to expire. I'm trying to just fire this thing off to a sidechain to timeout on its own while still making new things.
All the documentation is getting super involved using asyncio, multithreading, etc.
Is there an easy way to kick this thing out of the main loop and not hold up traffic?
laziest method for simplicity is :
import concurrent.futures as delayobj
#where r() is a random number function
objCount = 0
def mainfunc()
global objCount
with delayobj:
while objCount < 100:
delayobj.ThreapoolExecutor().submit(create,tmptime=r(time))
time.sleep(1)
return None
def create(tmptime)
global objCount
objCount = objCount+1
newobj = plotSomething(r(x),r(y))
time.sleep(tmptime)
selfDelete..
return None
mainfunc() #run it
thanks again guys

How to return to stop multiple levels up

I want to be able to return to stop the parent function inside a function like this:
def FunctionBeingRan():
#Running Script
def stop():
return #return to stop the parent function
FunctionBeingRan().stop
Anyone know how to do this
you can return some number represent stop such as -1 and add a check statement to it .
def FunctionBeingRan():
#Running Script
def stop():
return #return to stop the parent function
if stop() == -1:
return
as python doesn't have goto statement, but there do have some nice packages that implement it
from goto import with_goto
#with_goto
def fun1(start, stop):
label .begin
# your code here
def stop():
# stop logical here
goto .end
# your remaining code here
label .end
return result
but it is dangerous for making code hard to read.
The best way is refact your logic.

Best way to run code once within while loops?

I'm writing a text-based RPG for a class, and am stuck on a code predicament...
from tkinter import *
...
runOnce = False
nextRun = False
"""Main Loop"""
while True:
#New Game initialize
if you.rName == None and runOnce == False:
log("What is your name, adventurer?", eventLog)
runOnce = True
if you.rName != None and nextRun == False:
log(f'What is your profession, {you.rName}?', eventLog)
nextRun = True
#keypresses
playerInput.bind("<Return>", keyPress)
playerInput.bind("<FocusIn>", focusIn)
top.update()
top.update_idletasks()
What I have currently works, but there are a ton more if-statement type situations that need responses before continuing to the next statement. The loop is to continuously update the GUI as the game is run.
How can I code the something that needs a response once within a while loop efficiently?
Seeing the clarification, I agree with the comments these type of actions shouldn't belong in the loop. These should be all data that are collected prior to the main game loop.
If you're looping through these to validate for inputs, you can have separate loops instead:
while not you.name:
you.name = input('Enter name: ')
# some additional validation text if necessary...
while not you.job:
you.job = input('Enter job: ')
# some additional validation text if necessary...
while True:
# main game loop requiring you.name, you.job
Another approach is a bit contrived. You can pre-define these functions before your mainloop and create a RunOnce class to only execute these functions once:
class RunOnce(object):
def __init__(self, func):
self.func = func
self.ran = False
def __call__(self):
if not self.ran:
self.func()
self.ran = True
# once the function has been called,
# flip self.ran so it won't fire again.
# Decorate your functions with this special class
#RunOnce
def get_name():
you.name = input('Enter Name: ')
#RunOnce
def get_job():
you.job = input('Enter Job: ')
And then when you are in the main game loop:
while True:
get_name() # this will run once
get_job() # this too will run once
get_name() # this won't run anymore
get_job() # this neither.
The benefit of this approach is it gives you the flexibility to re-run the function if necessary:
get_name() # get_name.ran becomes True
get_name.ran = False # reset the flag
get_name() # this will run again.
I'd still say it's much better to just restructure your code so that things that only need to be captured once stay outside the main loop.
Try checking your parameters for null before using them. If you're looking for user input you can do this:
userInput = None
while True:
userInput = input("Do the thing only once") if userInput is None else userInput
...

How to get return value from a CAPL function called from python?

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.

Creating a Stopwatch progam for Python 3.3 only in IDLE

I have an assignment where I need to create a stopwatch, but only for IDLE. Here's what I have so far, I'm not sure how to convert the times to normal time.
import time
start = 0
def stopwatch():
while True:
command = input("Type: start, stop, reset, or quit: \n")
if (command == "quit"):
break
elif (command == "start"):
start = time.time()
print(start)
stopwatch2()
elif (command == "stop"):
stopwatch()
elif (command == "reset'"):
stopwatch()
else :
break
def stopwatch2():
while True:
command = input("Type: stop, reset, or quit: \n")
if (command == "quit"):
break
elif (command == "stop"):
total = time.time() - start
print(total)
stopwatch()
elif (command == "reset'"):
stopwatch()
else:
break
stopwatch()
Thanks for your help!
You can use datetime.timedelta():
import datetime
print(datetime.timedelta(seconds=total))
For example:
In [10]: print datetime.timedelta(seconds=10000000)
115 days, 17:46:40
Think of it like this... Idle is really no different than coding in the interactive python interpreter which I do all the time (well, I use ipython).
Think of your stopwatch like an object. What functionality does it have? Things like start, stop, reset.
This may not be the most efficient way to solve the problem but here is what I would do.
>>> import time
>>> class StopwatchException:
pass
>>> class IsRunningException(StopwatchException):
pass
>>> class NotRunningException(StopwatchException):
pass
>>> class Stopwatch():
def __init__(self):
self._times = []
self._is_running = False
def start(self):
if self._is_running:
raise IsRunningException
self._is_running = True
tracker = {
'start': time.time(),
'stop': None,
}
self._times.append(tracker)
def stop(self):
if not self._is_running:
raise NotRunningException
tracker = self._times[-1]
# the dict is mutable, and tracker is a shallow copy
tracker['stop'] = time.time()
#print(self._times[-1])
self._is_running = False
def reset(self):
if self._is_running:
raise IsRunningException
self._times = []
def total(self):
if self._is_running:
raise IsRunningException
total = 0.0
for t in self._times:
total += t['stop'] - t['start']
return total
>>> s = Stopwatch()
>>> s.start()
>>> s.stop()
>>> s.total()
6.499619960784912
>>> s.reset()
>>> s.total()
0.0
To me, anytime you want to model a real world object or "thing", OOP makes the most sense. Heres a simple argument for each element of the program:
Classes
StopwatchException
Base exception class for the stopwatch class.
IsRunningException
Raised if the stopwatch is running when it should be stopped.
NotRunningException
Raised if the stopwatch is not running when it should be.
Stopwatch
This represents the actual stopwatch.
Stopwatch Class
init
A basic stopwatch class really only needs to instance variables. A variable that stores each start/stop time (allows them to be computed later) and a variable that stores the "state" of the stopwatch (on/off or running/stopped).
start
First we need to make sure the stopwatch isn't already running.
Then we need to set it's state to running and store the time in self._times.
I chose to use a local variable and store each time pair as a dictionary with the keys 'start' and 'stop'. I chose a dictionary because it is mutable. You could also have a list with index 0 being the start time and index 1 being the stop time. You cannot use a tuple for this since tuples are immutable.
Also, the "temporary" variable is not necessary but I used it for readability.
stop
First we need to make sure the stopwatch is actually running.
Then we set the state as 'stopped' (using our boolean self._is_running) and store our stop time, similar to what we did with start. I think it doesn't matter whether you set the boolean at the beginning or the end, although I chose to set it at the beginning of the start function and the end of the stop function so that the times would not include the time needed to update a boolean variable (even though it's a trivial task, it could be much more complex in more complex programs).
reset
Make sure the stopwatch isn't running
Set self._times to be an empty list.
total
Make sure the stopwatch isn't running.
Optional: You can stop the stopwatch here if it's running, but I prefer to raise an exception.
Iterate through each list item in self._times and calculate the difference between stop and start.

Categories

Resources