Once you are in a function, How would you be able to navigate from function to function within your original function? (I wrote pseudo code because I do not know how to accomplish this)
def main():
do...
if something == 1
access function(Success)
elif something == 2
access function(Failed)
elif something == 3
end script
else
print "choose a proper option idiot"
def menuSuc():
print 1) How many total requests (Code _____)
print 2) How many requests from _____ (IPs starting with 142.204)
print 3) How many requests for isomaster-1.3.13.tar.bz2
print q) Return to Main Menu
def menuFai():
print 1) How many total failed requests (Codes _____)
print 2) How many invalid requests for wp-login.php
print 3) List the filenames for failed requests for files in /apng/assembler/data
print q) Return to Main Menu
def success(argv):
do.....
print menuSuc
print information
def failed(argv):
do.....
print menuFai
print information
Just call the function you want to use inside the function. I would avoid calling a function a function in Python code. Don't forget that in Python 3 print is a function--add "()" around the quotes.
def main():
if something == 1:
Success() # to access function(Success)
elif something == 2:
Failed()
elif something == 3:
return print("script Done")
else:
print("choose a proper option") # no need to call people names :)
main()
Related
Please help me fix this recursive function so that I can successfully prompt the user at each stage. I am trying to make a program that allows users mix, change the playback speed and filter the signal of a wav file. To do that I need create a recursive question that continually prompts the user to use different tools in this program.
def c_function():
print("you have successfully called c_function")# These print statements are just place holders for the actual functions
return
def m_function():
print("you have successfully called m_function")
return
def f_function():
print("you have successfully called f_function")
return
def s_function():
print("you have successfully called s_function")
return
"use these functions as selection tools in the recursive function bellow"
user_question1 = input("Select one of the following four options:\n s see the sample rate of the file\n c change the playback speed\n m mix two signals together\n f filter the signal or\n q quit \n : ")
def recursive_main_function():
if user_question1 == ('c'):
c_function()
recursive_main_function()
if user_question1 == ('m'):
m_function()
recursive_main_function()
if user_question1 == ('f'):
f_function()
recursive_main_function()
else:
print("Invalid response. Please try again" + user_question1)
return
It looks like you'd want to use an infinite while loop. Using if statements with else ifs is good too because if the user input somehow fulfils more than one of the cases, the program won't call several functions at once. Let me know if you have any questions.
def recursive_main_function():
# Infinitely loops unless user presses 'q'
while(True):
# Waits for the question's input
user_question1 = input("Select one of the following four options:\n s see the sample rate of the file\n c change the playback speed\n m mix two signals together\n f filter the signal or\n q quit \n : ")
# Respond based on input provided
if user_question1 == "s":
s_function()
elif user_question1 == "c":
c_function()
elif user_question1 == "m":
m_function()
elif user_question1 == "f":
f_function()
elif user_question1 == "q":
# Breaks the user out of the while loop
break
else:
print("Invalid response. Please try again" + user_question1)
# End of function, exits script
return
# To initiate script
recursive_main_function()
This is a shorter version of my answer to a related question.
Rather than a forest of ifs, you could use a dictionary to match user input to a function.
def c_function(argv):
print("you have successfully called c_function")# These print statements are just place holders for the actual functions
return 0
def m_function(argv):
print("you have successfully called m_function")
return 0
def f_function(argv):
print("you have successfully called f_function")
return 0
def s_function(argv):
print("you have successfully called s_function")
return 0
def help_function(argv):
print('available commands:')
print(' s see the sample rate of the file')
print(' c change the playback speed')
print(' m mix two signals together')
print(' f filter the signal')
print(' help print the list of commands')
print(' quit quit')
return 0
def quit_function(argv):
env['didntQuit'] = False
return 0
def notfound_function(argv):
print('{}: {}: command not found'.format(env['replname'], argv[0]))
return -1
def print_return_value(ret, argv):
if ret != 0:
print('{}: command {} failed with return value {}'.format(env['replname'], argv[0], ret))
env = { 'replname': 'wav-processor-repl', 'prompt': '$ ', 'didntQuit': True }
command_dict = {'c': c_function, 'm': m_function, 'f': f_function, 'h': help_function, 'help': help_function, 'q': quit_function, 'quit': quit_function}
while env['didntQuit']:
argv = input(env['prompt']).strip().split() # read
command = command_dict.get(argv[0], notfound_function) # identify command
ret = command(argv) # execute command
print_return_value(ret, argv) # error message if command failed
Output:
$ c
you have successfully called c_function
$ f
you have successfully called f_function
$ g
waf-processor-repl: g: command not found
waf-processor-repl: command g failed with return value -1
$ f
you have successfully called f_function
$ h
available commands:
s see the sample rate of the file
c change the playback speed
m mix two signals together
f filter the signal
help print the list of commands
quit quit
$ m
you have successfully called m_function
$ q
a python beginner here. My previous programming experience is with basic in the eighties, and logic programming in a proprietary system, neither of which is much help for learning python. So, to my question:
I'm writing a math quiz program (just for learning), and I've made a "main menu" by defining a function block; within it, if input is a then another func addition() is called, if input is s then func subtraction() is called and this works as intended. Within those function blocks, I'm setting a global variable quiztype to name of that function. Then I call yet another function again() from within those, to query if user wants another question of the same sort, if yes, I try to return to the relevant function with quiztype () and this fails with TypeError: 'str' object is not callable.
I did find some seemingly-related topics but either couldn't implement the answers or didn't even understand what they were talking about as I'm a beginner.
What options do I have for returning to the previously executed function?
Here's the code: (notice that variable names are not what above - different language)
from random import randint
def Alku ():
kysy = True
while kysy:
lasku = input('Yhteen, Vähennys, Lopeta? ')
if lasku == 'y':
Yhteenlasku ()
kysy = False
elif lasku == 'l':
break
kysy = False
def Uudestaan ():
kysy = True
while kysy:
samauudestaan = input('uudestaan? (k/e)? ')
if samauudestaan == 'k':
Lasku()
kysy = False
elif samauudestaan == 'e':
Alku ()
kysy = False
def Yhteenlasku ():
global Lasku
Lasku='Yhteenlasku'
n1=(randint(1,10))
n2=(randint(1,10))
a1=n1+n2
print(n1, end="")
print(" + ", end="")
print (n2, end="")
print(" = ", end="")
a2=int(input())
print()
if a1==a2:
print('oikein!')
elif a1!=a2:
print('väärin!')
Uudestaan()
Alku ()
And what is returned in terminal:
Traceback (most recent call last):
File "laskut2.py", line 43, in <module>
Alku ()
File "laskut2.py", line 8, in Alku
Yhteenlasku ()
File "laskut2.py", line 41, in Yhteenlasku
Uudestaan()
File "laskut2.py", line 19, in Uudestaan
Lasku()
TypeError: 'str' object is not callable
Your code is fine as it stands, although your global declaration is in an odd place. Still, remove the inverted comma's around your definition of Lasku which is defining it as a string and it will work.
global Lasku
Lasku=Yhteenlasku
P.S. Welcome back to programming!
In response to your question, globals would normally be declared at the beginning of your code or when the data to define becomes available but in this case you are defining it as a function, so you can't define it until the function has been defined. I guess as long as it works, where it is is fine. Personally, in this case, I'd define it here:
global Lasku
Lasku=Yhteenlasku
Alku ()
We really need to see your code to see what you want to achieve but from the sound of it you want to do something like this. From the question it look like you will be recalling function within functions and returning functions, creating recursions which is not that pythonic and also will eventually throw errors and the other is not really needed in this situation. jedruniu has put really quite a good explanation on function variable assignment too.
Less robust version:
def addition():
pass # Put code here
def subtraction():
pass # Put code here
def menu():
while True:
cmd = input("Addition or subtraction? (a/s): ")
if cmd == "a":
addition()
elif cmd == "s":
subtraction()
menu()
Other version (w/ score):
def addition():
# Put code here
result = True
return result # Will be added to score, so any integer or True/False
def subtraction():
# Put code here
result = True
return result # Will be added to score, so any integer or True/False
def menu():
score = 0
while True:
cmd = input("Addition or subtraction? (a/s/exit): ").strip().lower()
if cmd == "exit":
break
elif cmd == "a":
score += addition()
elif cmd == "s":
score += subtraction()
else:
print("Unknown option...")
# Do something with score or return score
if __main__ == "__main__":
menu()
You can assign function to a variable (because function is in Python first-class citizen), so effectively, for example:
def fun1():
print("fun1")
def fun2():
print("fun2")
def fun3():
print("fun3")
f1 = fun1
f2 = fun2
f3 = fun3
functions = {
"invoke_f1" : f1,
"invoke_f2" : f2,
"invoke_f3" : f3
}
functions["invoke_f1"]()
function_to_invoke = functions["invoke_f2"]
function_to_invoke()
yields:
fun1
fun2
More reading: https://en.wikipedia.org/wiki/First-class_function
In your specific example, modify your Uudestaan function.
def Uudestaan ():
Lasku = Yhteenlasku #Add this line
kysy = True
while kysy:
samauudestaan = input('uudestaan? (k/e)? ')
if samauudestaan == 'k':
Lasku()
kysy = False
elif samauudestaan == 'e':
Alku ()
kysy = False
because you were trying to invoke string, and this is not possible. Try to invoke type(Lasku) in your case and you'll see that it is of type str. Invoke it in function with my modification and you'll see type of function.
However I am not sure what is going on in this code, is this finnish? swedish?
Newish to python, working on a text adventure, testing out the use of functions.
def cell1():
loop = 1
while loop == 1:
print("ONE")
cave1 = input()
if cave1 == ("end?"):
print("\nthis should end program")
loop = 0
break
elif cave1 == ("TWO"):
global testvar
testvar = 1
option1()
else:
print("INVALID")
def option1():
print("TWO")
loop = 1
while loop == 1:
print("test1 definition")
print (testvar)
test1 = input()
if test1 == ("ONE"):
print("you pick up the cheese")
loop = 0
cell1()
elif test1 == ("THREE"):
option2()
else:
print("INVALID")
def option2():
print("THREE")
loop = 1
while loop == 1:
print("This is option 3")
test2 = input()
if test2 == ("ONE"):
print("testering2")
cell1()
elif test2 == ("TWO"):
global testvar
testvar = 2014
option1()
else:
print("INVALID")
run = True
while run == (True):
print ("testing 123")
cell1()
print("restart about to activate")
cont = input("Restart? ")
if (cont) != "yes":
break
This program should allow you to go between options (what would be rooms) and eventually in cell1, the program should be end-able.
if the program is run and "end?" is typed as the first input, the program goes into the continue bit at the bottom, however, if you go between the 'rooms' then back to cell1, typing "end?" will call option 2.
Ive had a look around and it is still baffling me, am i ding something wrong?
Any help is appreciated, thank you.
The reason "end?" only quits for the player when they are within the first cell is because you're only checking for that input therein. The execution contained within option1() and option2() doesn't affect the execution of cell1(). You're not returning anything from your option functions, nor are you changing a sentinel value.
So, there's two basic ways you could go about this.
First, you could return a value from your functions:
if option1() == "END":
break
Or, you could alter your while loop:
# is_running is defined globally
while is_running:
And then just set is_running to False in any of your methods whenever the user types "end?". That'd probably be the easiest way with the design you're using now.
I'm sure you can tell, though, that in general your program is going to get exponentially more complex as you add more rooms and your function calls get further nested.
I'm pretty sure that the issue you're having is because you don't always break out of the loop in one function when you call another function. For instance, if your entries were TWO, ONE then end?, you'd find yourself still in the cell1 loop. That's because when the inner call to cell1 returns, the control flow of the program goes back to where that function was called from, which is option1, since loop is now 0, the loop ends and option1 returns, to the outer call to cell1, where the loop is still running.
Unless you want the game you're designing to have a tree structure, where you can return to where you came from with different semantics than moving to some other place, I'd suggest using a different architecture. Rather than each of your functions calling the next function when appropriate, return that function instead. Then you'd write a single top level loop that calls the function. Here's an example where the function to be called by the top level loop is saved in a variable named state:
def cell1():
print("In cell1!")
while True:
choice = input("pick 'ONE' or 'TWO' (or type 'quit' to exit):")
if choice == "ONE":
return option1
elif choice == "TWO":
return option2
elif choice == "quit":
return None
else:
print("I'm sorry, I didn't understand that.")
def option1(): # these other two functions are very basic in my example
print("In option1!") # but you can make them as complex as you want
return option2
def option2():
print("in option2!")
return cell1
def control_loop(initial_state=cell1):
state = initial_state
while state is not None:
state = state() # the next state is the return value of the previous state
The problem is you are getting deeper and deeper within nested functions. For example, changing
if test1 == ("ONE"):
print("you pick up the cheese")
loop = 0
cell1()
to
if test1 == ("ONE"):
print("you pick up the cheese")
loop = 0
break
will allow you to run your program, enter room two, go back to room one, and "end?" will work properly. This won't fix your issues completely though because there is a similar problem where when you go from two to three where if you simply changed
if test2 == ("ONE"):
print("testering2")
cell1()
to
if test2 == ("ONE"):
print("testering2")
break
it would break the current function and go back into option1() (if you run your program, go to room two, then to room three, then back to one) where "end?" doesn't do anything. Hopefully this gets you on the right track.
im trying to call function inside if statement but it does not work. This is one of my first attempts in using Python. What am I doing wrong?
#!/usr/bin/python
menu = raw_input ("Hello, please choose form following options (1,2,3) and press enter:\n"
"Option 1\n"
"Option 2\n"
"Option 3\n")
if menu == str("1"):
savinginfile = raw_input ("Please, state your name: ")
option1()
elif menu == str("2"):
print ("Option 2")
elif menu == str("3"):
print ("Option 3")
def option1():
test = open ("test.txt", "rw")
test.write(savinginfile)
print ("Option 1 used")
test.close()
Would recommend that you pass savinginfile as a parameter:
def option1(savinginfile):
test = open ("test.txt", "rw")
test.write(savinginfile)
print ("Option 1 used")
test.close()
You need to define option1 before calling. Python interprets from top to bottom.
You need to define your function before you try to call it. Just put def option1(): #and all that code below it above your if statements.
It's also bad practice to throw around too many global variables. You shouldn't use savinginfile the way you are -- instead, pass it to the function as a parameter and let the function operate in its own scope. You'll need to pass the function the name of the file to use before it's able to use savinginfile. Try instead:
def option1(whattosaveinfile):
test = open("test.txt","a+") #probably better to use a with statement -- I'll comment below.
test.write(whattosaveinfile) #note that you use the parameter name, not the var you pass to it
print("Option 1 used")
test.close()
#that with statement works better for file-like objects because it automatically
#catches and handles any errors that occur, leaving you with a closed object.
#it's also a little prettier :) Use it like this:
#
# with open("test.txt","a+") as f:
# f.write(whattosaveinfile)
# print("Option 1 used")
#
#note that you didn't have to call f.close(), because the with block does that for you
#if you'd like to know more, look up the docs for contextlib
if menu == "1": #no reason to turn this to a string -- you've already defined it by such by enclosing it in quotes
savinginfile = raw_input("Please state your name: ")
option1(savinginfile) #putting the var in the parens will pass it to the function as a parameter.
elif menu == "2": #etc
#etc
#etc
I am a beginer python learner. I am trying to create a basic dictionary where random meaning of words will come and user have to input the correct word. I used the following method, but random doesn't work. I always get the first word first and when the last word finishes, I get infinite 'none' until I kill it. Using python 3.2
from random import choice
print("Welcome , let's get started")
input()
def word():
print('Humiliate')
a = input(':')
while a == 'abasement':
break
else:
word()
# --------------------------------------------------------- #
def word1():
print('Swelling')
a = input(':')
while a == 'billowing':
break
else:
word()
# ------------------------------------------------------------ #
wooo = [word(),word1()]
while 1==1:
print(choice(wooo))
is there any faster way of doing this and get real random? I tried classes but it seems harder than this. Also, is there any way I can make python not care about weather the input is capital letter or not?
To answer one part of your question ("is there any way I can make python not care about weather the input is capital letter or not?"): use some_string.lower():
>>> "foo".lower() == "foo"
True
>>> "FOO".lower() == "foo"
True
An this is to help you how you could improve the structure of your code:
import sys
from random import choice
WORDPAIRS = [('Humiliate', 'abasement'), ('Swelling', 'billowing')]
def ask():
pair = choice(WORDPAIRS)
while True:
answer = raw_input("%s: " % pair[0]).lower()
if answer == pair[1]:
print "well done!"
return
def main():
try:
while True:
ask()
except KeyboardInterrupt:
sys.exit(0)
if __name__ == "__main__":
main()
It works like that:
$ python lulu.py
Swelling: lol
Swelling: rofl
Swelling: billowing
well done!
Humiliate: rofl
Humiliate: Abasement
well done!
Swelling: BILLOWING
well done!
Humiliate: ^C
$
wooo = [word, word1]
while 1:
print(choice(wooo)())
But in any case it will print you None, cause both of your functions return nothing (None).