I'm trying to figure out how to direct a function to a function. What I'm trying to do is answer a prompt question y/n that would run a certain function. When I input y, it will run through both functions instead of only function 1.
Thanks!
def company_type(question, public_company, private_company):
print("Is the target company public on NYSE or NASDAQ?")
prompt = f'{question} (y/n)'
ans = input(prompt)
if ans == 'y':
return (public_company)
if ans == 'n':
print("Please enter financial infomation manually.")
return (private_company)
company_type("public_company", "private_company", 1)
# function 1
def public_company():
return (print("Success 1"))
public_company()
# function 2
def private_company():
return (print("Success 2"))
private_company()
You can absolutely return a function to be used later - this is the essence of functional programming, and the reason to have functions as first class objects in python ~ Guido Van Rossum.
The important thing is to remember that parens mean a function call, whereas no parens mean the function object.
def public_company():
print("we do what public companies do")
def private_company():
print("we do what private companies do")
def choose_company():
ans = input("Is the target company public?")
if ans == 'y':
return public_company # no parens
else:
return private_company # no parens
if __name__ == '__main__':
# assign the returned function to selected_company
selected_company = choose_company()
# calling selected_company() will call the selected function
selected_company() # use parens, this is a function call!
You don't really want to return a function. You just want one function to call another function. That's done like this:
# function 1
def public_company():
return print("Success 1")
# function 2
def private_company():
return print("Success 2")
def company_type(question, public_company, private_company):
print("Is the target company public on NYSE or NASDAQ?")
prompt = f'{question} (y/n)'
ans = input(prompt)
if ans == 'y':
return public_company()
else:
print("Please enter financial information manually.")
return private_company()
company_type("some question", public_company, private_company)
And please note that return statements in Python do not use an extra set of parentheses. That's a C idiom.
Errors:-
function is not a keyword.
We can call a function by:- <function_name>().
# function 1
def public_company():
print("Success")
# function 2
def private_company():
print("Success")
def company_type():
print("Is the target company public on NYSE or NASDAQ?")
prompt = 'Is your company a public company? (y/n)'
ans = input(prompt)
if ans == 'y':
public_company()
if ans == 'n':
print("Please enter financial information manually.")
private_company()
company_type()
Related
I am self-learning Python (no prior programming experience) and I am trying this question:
ask the user to input as many bank account numbers as they’d like, and store them within a list initially. once the user is done entering information, convert the list to a frozenset and print it out.
This is my code:
# create global variables
b_accounts = []
fzb_accounts = frozenset()
# Create add account function
def addAccount(account):
b_accounts.append(account)
print('Account number: {} has been added'.format(account))
return b_accounts
# create covert from a list to a frozenset function
def convertFz():
if b_accounts:
globals()['fzb_accounts'] = frozenset(b_accounts)
return fzb_accounts
else:
print('List of account does not exist!')
# create show account function
def showAccount():
convertFz()
if fzb_accounts:
#print('Here your enique entered accounts:{}'.format(fzb_accounts))
for acc in fzb_accounts:
print(acc)
else:
print('No account!')
# create main function
def main():
done = False
while not done:
ans = input('Please select add/show/quit account: ').lower()
if ans == 'add':
account = input('Enter account number: ')
addAccount(account)
elif ans =='show':
showAccount()
elif ans =='quit':
done = True
print('Bye!')
else:
print('Invalid option')
main()
I want to add the following account numbers:
1234
12345
1234
the output should be:
1234
12345
Thank all, code updated and work as expected.
I want to create a function which takes a bunch of code as so-called "argument", so that I can implement any block-of-code I want later on.
Here is a sample:
def loop(c):
while c != (1 or 0):
try:
c = int(input("Choice? (1/2) - "))
except ValueError:
print("Enter a valid value.")
else:
if c == 1:
# i want to have different implementations of loop(c) by writing any (bunch of) statements i want here.
elif c == 0:
print("Goodbye...")
else:
print("Please enter either 1 or 0.")
What I basically want to do is to create a template so that I can use this code snippet with if block (where the comment-line is) is filled (replaced) with anything I want. How can I do it?
You can easily accept functions as arguments:
def loop(c, func):
while c != (1 or 0):
try:
c = int(input("Choice? (1/2) - "))
except ValueError:
print("Enter a valid value.")
else:
if c == 1:
func()
elif c == 0:
print("Goodbye...")
else:
print("Please enter either 1 or 0.")
An example of calling it would be one of these:
def a():
# whatever code you want here
print('in the function')
loop(c, a)
Or even simpler (for simple functions):
loop(c, lambda: print('in a lambda'))
You can pass a callable (function or lambda) to your function as an argument.
def perform_function(func):
if input() == "foo":
func()
perform_function(lambda: print("Hello World"))
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?
def letterChoice():
playerLetter = input('Please choose X or O.').upper()
if playerLetter in ['X','O']:
print('The game will now begin.')
while playerLetter not in ['X','O']:
playerLetter = input('Choose X or O.').upper()
if playerLetter == 'X':
computerLetter = 'O'
else:
computerLetter = 'X'
turnChooser()
def turnChooser():
choice = input("Would you like to go first, second or decide by coin toss?(enter 1, 2 or c) ")
while choice not in ["1","2","c"]:
choice = input("Please enter 1, 2 or c. ")
if choice == 1:
print("G")
cur_turn = letterChoice.playerLetter()
elif choice == 2:
print("H")
else:
print("P")
moveTaker()
I can't figure out how I'm supposed to inherit playerLetter into turnChooser(), I've tried putting playerLetter into the brackets of each function but they don't pass and create an argument error and the print("G") and so on are simply there to see if the code works but whenever I enter 1 or 2 "P" is outputted.
You need to define function Attributes for playerLatter
For EX:
def foo():
foo.playerletter=input('Please choose X or O.').upper()
>>> foo()
Please choose X or O.x
>>> foo.playerLetter
'X'
Accessing from another function
def bar():
variable=foo.playerLetter
print(variable)
>>> bar()
X
>>>
You can always check what Attributes are available for a given function
>>> [i for i in dir(foo) if not i.startswith('_')]
['playerLetter']
>>>
Edit turnchooser() to turnchooser(var), then when calling the function pass the letter to the function like this:
def LetterChoice():
Code...
turnchooser(playerletter)
And,
def turnchooser(var):
Code...
The letter will be placed in a variable called var, which means your code will use the letter as var not playerletter.
Of Course you can change the names to whatever you like.
You could add as many variables to the function however they all should have something assigned to them, aka you can't call the previous function like so:
turnchooser()
Unless you assign it a default value:
def turnchooser(var = 'x')
This way whenever the function is called the value of "var" is x unless stated otherwise.
Note that if you want to pass it from one function to another, u either have to assign the letter to a variable then call the function outside the "LetterChoice" or call it in the definition of "LetterChoice"
Within the function that has the variable in it type:
global variableName
Obviously change variableName to whatever the variable is actually called. Hope this helps!
Tommy
You should try using classes: Python documentation
This should be the code:
class Game:
def __init__(self):
self.cur_turn = ''
self.choise = ''
self.playerLetter = ''
self.computerLetter = ''
def letterChoice(self):
while True:
self.playerLetter = input('Please choose X or O.').upper()
if self.playerLetter in ['X','O']:
print('The game will now begin.')
if playerLetter == 'X':
self.computerLetter = 'O'
else:
self.computerLetter = 'X'
break
else:
print ('Please enter only X or O')
def turnChooser(self):
while True:
self.choice = input("Would you like to go first, second or decide by coin toss? (enter 1, 2 or c) ")
if self.choice in ["1","2","c"]:
if self.choice == 1:
print("G")
self.cur_turn = self.playerLetter()
elif self.choice == 2:
print("H")
else:
print("P")
break
else:
print ('Please enter 1, 2 or c')
game = Game()
game.letterChoice()
game.turnChooser()
# If you want to read any of the variables in Game just write 'self.VARIABLE_NAME'
I have problem with getting output from another function to use in a function.
I don't know the syntax of function in python. How do i take a output of another function to use in a function when i define it.
def hero_attribute(hero_selection()): #This syntax isn't accepted
#This program will calculate the damge of hero with stats
global hero_str_result
global hero_agi_result
global hero_int_result
def hero_selection():
print """1. Life Stealer (strength hero)\n
2. Phantom lancer (agility hero)\n
3. Phantom Assassin (agility hero)\n
4. Wrait King (strength hero) \n
"""
print "Please enter hero selection: "
hero_num = int(raw_input("> "))
return hero_num
def hero_attribute(hero_selection()): #This syntax isn't accepted
if hero_num == 1: # Life stealer
hero_str = 25
hero_agi = 18
hero_int = 15
#Hero growth stats
str_growth = 2.4
agi_growth = 1.9
int_growth = 1.75
elif hero_num == 2: # Phantom lancer
hero_str =
hero_agi = ?
hero_int = ?
#Hero growth stats
str_growth = 2.4
agi_growth = 1.9
int_growth = 1.75
elif hero_num == 3: # Phantom Assassin
hero_str = ?
hero_agi = ?
hero_int = ?
#Hero growth stats
else: #Wraith King
hero_str = ?
hero_agi = ?
hero_int = ?
#hero growth stats
str_growth = ?
agi_growth = ?
int_growth = ?
return (hero_str,hero_agi,hero_int,str_growth,agi_growth,int_growth)
def hero_type(hero_num):
if hero_num == 1:
hero_type = "str"
elif hero_num == 2
hero_type = "agi"
elif hero_num == 3
hero_type = "agi"
else:
hero_type = "str"
#the function will ask user what to do with the hero
def hero_build():
print "What do you want to do with the hero?"
print """1. Build hero with stat
2. Build hero with item (not yet)
3. Build hero with level
"""
user_choice = int(raw_input("> "))
if user_choice == 1:
print "You want to build hero with stats!"
print "Please enter number of stats that you want to add: "
hero_stats = int(raw_input=("> "))
hero_str, hero_agi, hero_int,str_growth,agi_growth,int_growth = hero_attribute() #This function will take the result of hero_str, hero_agi,hero_int
hero_str_result = hero_str + str_growth * hero_stats
hero_agi_result = hero_agi + agi_growth * hero_stats
hero_int_result = hero_int + int_growth * hero_stats
return hero_str_result, hero_agi_result, hero_int_result
print "This is the result of your build: ", hero_build()
A function is a piece of code that receive arguments, and to those arguments you assign a name. For example:
def square(x):
return x * x
this function computes the square of a number; this unknown number in the body of the function will be called x.
Once you have a function you can call it, passing the values you want as arguments... for example
print( square(12) )
will print 144 because it will call the function square passing x=12 and 12*12 is 144.
You can of course pass a function the result of calling another function, e.g.
def three_times(x):
return 3 * x
print( square( three_times(5) ) )
will display 225 because the function three_times will be passed 5 and it will return 3*5, the function square will be passed 15 and will return 15*15.
In the function definition (the def part) you will always just have names for the parameters. What you want to pass to the function will be written at the call site.
What you want is to be able to pass a function as argument. This, however, is already incorporated into python from design: you simply pass it as you pass any other argument.
Example:
def apply(f,x):
return f(x)
def sq(x):
return x*x
def cb(x):
return x*x*x
apply(sq,2)
4
apply(cb,2)
8
Apply is defined with its first argument being a function. You know that only when you actually read the definition of apply. There you see that f is treated as a function, as opposed to x which is treated "as a number".