Ok I have a code that's basically this....
def create():
#long list of print statements
m_commands()
def get_desc():
#print statement
m_commands()
def m_commands():
while close != True:
input = input(str(">>>"))
If inp == "close" or "quit":
close = True
If inp == "create":
create()
If inp == "describe":
get_desc()
m_commands()
I need to call m_commands() in create() and get_desc() to continue continuity. Is this possible. Sorry in advance, I don't know how to put code in a spoiler thingy. Thanks!
def create():
#long list of print statements
print("hello")
m_commands()
def get_desc():
#print statement
print("world")
m_commands()
def m_commands():
close=False
while close != True:
inp = input(str(">>>"))
if inp == "close" or "quit":
close = True
if inp == "create":
create()
if inp == "describe":
get_desc()
m_commands()
This is working for me though.
Related
I have a bunch of functions that do x y and z, these functions get executed after an exception has occured. so my problem is that instead of writing the functions one by one i want to create a list of functions and a write a function to iterate through those functions in the list.
If you could show me an example that would be of great help.
here is what i have:
def call_va_funcs(self, stop):
self.disableZüruckVA()
while True:
try:
correct = urllib.request.urlopen("http://192.168.167.12", timeout=10).getcode()
print(correct, "192.168.100.2 is reachable: FAIL")
if correct == 200:
self.enableZüruckVA()
self.exitflag == True
break
except Exception:
print('Preflash')
if self.exitflag == True:
self.enableZüruckVA()
break
self.ping_all_va()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
self.run_rxtx()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
self.call_netzteil()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
As you can see here i am repeating the same process over and over again but with a different function. Can anyone help me figure out how to have a list and then just iterate through the bunch of functions.
Thank you
Let's say you have functionA(), functionB() and functionC().
You could put the names of the functions in a list like this:
f_list = [functionA, functionB, functionC]
You can then call these functions one after another:
while True:
# other code here...
try:
#... other code
except:
# ...other code
for func in f_list:
func()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
you could try smth like this
my_methods = []
my_methods.append('ping_all_va')
my_methods.append('run_rxtx')
my_methods.append('next_func')
for cmd in my_methods:
method = getattr(self, cmd)
method()
time.sleep(1)
if self.exitflag == True:
self.enableZüruckVA()
break
I need a way to stop a loop by getting user input without blocking the loop itself which works cross-platform.
Things I have tried:
processes (closes stdin so I can't use input())
threads (can't kill a thread if the while loop terminates and I no longer need the input())
FLAG = False
def break_main_loop(): # how do I get this to execute?
global FLAG
user_in = input()
if user_in == 'stop':
FLAG = True
return
else:
break_main_loop()
def stuff():
pass
def main():
# do stuff, e.g. getting other user input()
while True:
stuff()
if FLAG:
break
return # if I return here, I need to cancel break_main_loop's input()
main()
This will work for you and simple to use. Replace main function with this
def main():
# do stuff, e.g. getting other user input()
try:
while True:
stuff()
except KeyboardInterrupt:
print("Press 1 to quit")
return # if I return here, I need to cancel break_main_loop's input()
main()
I'd love to answer your question. You see, once you are in the main-loop, you don't necessarily need to use a FLAG variable, rather, I'd suggest doing something like this :
def break_main_loop(): # how do I get this to execute?
user_in = input()
if user_in == 'stop':
return True # Returning integer 1 also works just fine
else:
return False # Returning integer 0 also works just fine
def stuff():
pass
def main():
# do stuff, e.g. getting other user input()
while True:
stuff()
if break_main_loop(): # If the user inputs stop, the loop stops via the return statement automatically
return
main()
If you wish to get out of the loop without returning anything else and keep the main() function running for doing stuff:
def break_main_loop(): # how do I get this to execute?
user_in = input()
if user_in == 'stop':
return True # Returning integer 1 also works just fine
else:
return False # Returning integer 0 also works just fine
def stuff():
pass
def main():
# do stuff, e.g. getting other user input()
while True:
stuff()
if break_main_loop():
break
#continue doing stuff
main()
Now, there's a better way to break out of the loop without using the helper function break_main_loop(), and that's done like so:
def stuff():
pass
def main():
# do stuff, e.g. getting other user input()
while True:
stuff()
if str(input("Do you wish to continue:[y/n]")) == 'n':
break
#continue doing stuff
main()
This lets you get rid of the helper function completely.
I hope this answer was helpful. :D
try this:
class new_game:
start_game = True
# end_game = False
def break_main_loop(self): # how do I get this to execute?
print("game is ending!")
def stuff(self):
print("this is stuff happening....now...game is: ", self.start_game)
def game_loop(self):
user_in = int(input("enter '2' to end game or '1' to keep playing:" ))
if user_in == 1:
self.stuff()
self.game_loop()
else:
return self.break_main_loop()
Test_game = new_game()
Test_game.game_loop()
I've defined the following:
class SMSMessage(object):
def __init__(self, hasBeenRead, messageText, fromNumber):
self.hasBeenRead = hasBeenRead
self.messageText = messageText
self.fromNumber = fromNumber
hasBeenRead = "False"
fromNumber = "07189202003"
With the following functions:
def MarkAsRead(self):
if hasBeenRead == "False":
return hasBeenRead == "True"
def add_sms():
sms1 = (hasBeenRead, messageText, fromNumber)
return SMSStore.append(sms1)
def get_count():
return len(SMSStore)
def get_message(i):
for i in SMSStore:
return messageText
def get_unread_messages(i):
for i in SMSStore:
if hasBeenRead == "False":
return messageText
This is the Logic for the SMS simulation where a user is meant to send messages to a list (SMSStore[ ]) and then recall specific messages from the list:
userChoice = ""
while userChoice != "quit":
userChoice = raw_input("What would you like to do - read/send/quit?")
if userChoice == "read":
unreadChoice = raw_input("Would you like to retrieve all unread messages or one of your own choice? - all unread/custom ")
if unreadChoice == "custom":
messageNo = int(raw_input("Please enter which messsage number you want to read: "))
print get_message(messageNo)
print MarkAsRead(messageNo)
elif unreadChoice == "all unread":
print get_unread_messages(hasBeenRead)
else:
print "incorrect entry"
elif userChoice == "send":
messageText = raw_input('Please type in your message')
add_sms()
print SMSStore
My main issue is that I am able to send the (hasBeenRead, messageText, fromNumber) to SMSStore but when trying to read I can't seem to return the messagetext of the user selected messageNo. It always returns the messageText of the last item in the list. I'm still new to coding so any help would be greatly appreciated.
Thanks
I'm not sure what is the role of SMSStore, but this block of code looks suspicious to me:
def get_message(i):
for i in SMSStore:
return messageText
Why are you iterating the SMSStore but just to return messageText ? Would that be a missing Indent over there ?
I keep getting a list index out of range exception when I check the length of the list a. The error pops up for either the if or elif part of the second if statement, depending on what the user inputs. I know that when the user input is split the list is created correctly because I print it out... So I'm a little lost about why I'm getting that error.
if __name__ == '__main__':
for line in sys.stdin:
s = line.strip()
if not s: break
if (str(s) is "quit") == True: quit()
elif (str(s) is "quit") == False:
a = s.split()
print(a)
if (len(a) == 2) == True: first(a)
elif (len(a) == 3) == True: first(a)
else: print("Invalid Input. Please Re-enter.")
The first method is: (The methods it calls in the if statement just print things out at the moment)
def first(self, a = list()):
word = a[0]
if word is ls:
ls(a[1])
elif word is format:
form(a[1]) # EDIT: was format
elif word is reconnect:
reconnect(a[1])
elif word is mkfile:
mkfile(a[1])
elif word is mkdir:
mkdir(a[1])
elif word is append:
append(a[1], a[2])
elif word is delfile:
delfile(a[1])
elif word is deldir:
deldir(a[1])
else:
print("Invalid Prompt. Please Re-enter.")
Other methods:
def reconnect(one = ""):
print("Reconnect")
def ls(one = ""):
print("list")
def mkfile(one = ""):
print("make file")
def mkdir(one = ""):
print("make drive")
def append(one = "", two = ""):
print("append")
def form(one = ""):
print("format")
def delfile(one = ""):
print("delete file")
def deldir(one = ""):
print("delete directory")
def quit():
print("quit")
sys.exit(0)
The problem seems to be the definition of first(). You invoke it as a function:
if (len(a) == 2) == True: first(a)
elif (len(a) == 3) == True: first(a)
But you define it as a method:
def first(self, a = list()):
The array of command and argument gets put into self and a is always an empty list which you attempt to index and fail. Also, you shouldn't use a mutable type like list() as a default value unless you're certain what you are doing. I suggest simply:
def first(a):
As far as your __main__ code goes, simplify:
if __name__ == '__main__':
for line in sys.stdin:
string = line.strip()
if not string:
break
if string == "quit":
quit()
tokens = string.split()
length = len(tokens)
if 2 <= length <= 3:
first(tokens)
else:
print("Invalid Input. Please Re-enter.")
Real issue:
To solve your error you have to remove the self parameter of the first function
def first(a=list())
Basically the self is only used for object orientation creating methods.
Function like yours can't use self otherwise you will passing the first parameter to self not to a which you want to.
My second issue I can point out is that, You are trying to compare using is between a string and a function.
def first(a = list()):
word = a[0]
if word is "ls":
ls(a[1])
elif word is "format":
format(a[1])
elif word is "reconnect":
reconnect(a[1])
elif word is "mkfile":
mkfile(a[1])
elif word is "mkdir":
mkdir(a[1])
elif word is "append":
append(a[1], a[2])
elif word is "delfile":
delfile(a[1])
elif word is "deldir":
deldir(a[1])
else:
print("Invalid Prompt. Please Re-enter.")
Extra
The is function on built in operations in Python. is compare the equity of the objects.
But this expression:
if (str(s) is "quit") == True:
Can be simpler like:
if str(s) == "quit":
Or:
if str(s) is "quit":
The == True is meaningless either == False you can use not more pythonicly.
My code is in a while True loop.
It basically tries something like captcha.
So what I want is something like this
def loop():
toplam = 0
global sayilar
x = br.open(something)
html = x.read()
sayilar = map(str.strip,''.join(kod.findall(html)).split("\xc4\x84\xc5\x95\xc5\xa3\xc4\xb1"))
print sayilar
for i in sayilar:
if i in diction:
toplam += diction[i]
else
#break the function
if __name__ == "__main__":
giris()
while 1:
loop()
it can't find the number in dictionary it will break the function and restart the function again because function is in while loop.
Ok found a good way to restart it.
class CustomError(Exception):
def __init__(self, arg):
# Set some exception infomation
self.msg = arg
def loop():
toplam = 0
global sayilar
x = br.open(something)
html = x.read()
sayilar = map(str.strip,''.join(kod.findall(html)).split("\xc4\x84\xc5\x95\xc5\xa3\xc4\xb1"))
print sayilar
for i in sayilar:
if i in diction:
toplam += diction[i]
else
raise CustomError('Kelime Dictionaryde bulunamadi')
if __name__ == "__main__":
giris()
while 1:
try:
loop()
except CustomError, arg:
print "Can't find in dictionary"
You can literally use break. By using break, you can stop the loop immediately. You will see the use of the return later.
for i in sayilar:
if i in diction:
toplam += diction[i]
else:
return None
break
return True # Anything but None will work in place of True
This goes the same for the while loop:
while True: # Use True instead of 1
loop()
if loop() == None: # The function call is equal to what it returned
break
else:
continue # Optional else statement: continues loop if loop() != None