How can I restart a function through itself? Here is what the function is:
class thingamajig():
def __init__(self):
pass
def dostuff(self):
number = random.randint(0, 3)
if number == 3:
#restart here??????
thing = thingamajig()
thing.dostuff()
How can I restart the function?
Create a while loop in dostuff, for example:
def dostuff(self):
whatever you need the code to do
doagain = input('Want to do this again? y/n ')
while doagain != 'n':
whatever you need the code to do
doagain = input('Want to do this again? y/n ')
Note that this problem of having to restate the code is solved using a do/while loop in C++, but this will do for Python
How About:
class thingamajig():
def __init__(self):
pass
def dostuff(self):
doagain = input('Want to do this again? y/n ')
if doagain == 'y':
self.dostuff()
thing = thingamajig()
thing.dostuff()
This is how you do it:
class thingamajig():
def __init__(self):
pass
def dostuff(self):
number = random.randint(0, 3)
if number == 3:
self.dostuff()
thing = thingamajig()
thing.dostuff()
The class only knows its parameters, and its own variables. Self is a keyword that will say "this class".
Related
class Calculator:
def get_input(self, get = input("Expression here press q to exit: ")):
pass
def compute(self, res):
pass
def display(self):
pass
calc = Calculator()
while calc.get_input() != "q":
calc.get_input()
calc.display()
exit()
This is calculator like i just remove its data because of review issues here so much code
but the input must be example: 435+422
you must include the operation in input like that, this is done so my problem now is
i dont know how to loop it.
the out put must be
-enter expression or "q" to exit : 2+2
-enter expression or "q" to exit : 1+2
-enter expression or "q" to exit : q
-bye exit
i dont knooow
Try
class Calculator:
def get_input(self):
user_input = input("Expression here press q to exit: ")
return user_input
Instead of invoking input in arguments
The problem is that your get_input doesn't return anything. So calc.get_input() allways evaluates to None
Try:
class Calculator:
def get_input(self):
return input("Expression here press q to exit: ")
def compute(self, res):
pass
def display(self):
pass
calc = Calculator()
while calc.get_input() != "q":
calc.get_input()
calc.display()
exit()
I'm working on a project, and I got a bit stuck. I want the user the of the program to be able to call a function. But it must be easy for the user to call it. For example
def definition():
print("This is a function")
command = input("> ")
if command == definition:
definition()
else:
print("")
in this function I want the user not to write the () in the input. But I want the user just to be able to write 'definition' to call the function. Does anyone have any clue how to do this?
You are missing the quotes from around definition, therefore trying to compare an undeclared variable with an inputted string which will always equate to false.
Try:
def definition():
print("This is a function")
command = input("> ")
if command == 'definition':
definition()
else:
print("")
You are mixing up the function name (callable object in you code) and the name from your input.
For your problem I would use a dictionary of function names for the keys and function references for the value
def function1():
print ('calling function1')
def function2():
print ('calling function2')
def function3():
print ('calling function3')
functions = {}
functions['function1'] = function1
functions['function2'] = function2
functions['function3'] = function3
name = input('Enter the function name:\n')
if name in functions:
functions[name]()
else:
print ('Invalid function name. Use one of: ')
for key in functions.keys():
print (' - ' + key)
Just one command "definition"
def definition():
print("This is a function")
command = input("> ")
if command == "definition":
definition()
else:
print("Wrong command !")
More commands and functions
def definition():
print("This is definition function")
def modify():
print("This is modify function")
func = {"definition":definition, "modify":modify}
command = input("> ").strip().lower()
if command in func:
func[command]()
else:
print("Wrong command !")
You will have to implicitly define the conditions with if statement..
For ease of user you can do like this:
def definition():
#your function here
if __name__=='__main__':
print ("Choose your option:\n1. Definition")
choice = int(input("Enter choice: "))
if choice == 1:
definition ()
Try this
whitelist_funcs = ['definition', 'something else']
command = input("> ")
if command in whitelist_funcs:
exec(f"{command}()")
else:
print("")
I am trying to modify the value of a variable (in this case an integer) that is located inside of a class using a function that's outside of that class. But when I call the function, the value of the variable us_balance stays the same: 42.
class Country:
us_balance = 42
def buy(country, amount):
if country.lower == "us":
Country.us_balance = Country.us_balance - amount
def stats():
print(Country.us_balance)
while True:
user_input = input("> ").lower()
if user_input == "buy":
amount = input("$ ").lower()
balance_to_set = amount.split()
buy(balance_to_set[0], int(balance_to_set[1]))
if user_input == "stats":
stats()
break
Any ideas on how to fix this?
You should create an instance of the class and pass that in to the various functions. By using Country it is creating a new instance of the class each time and that is why the stats function is reporting 42 as the value.
Here's a example that should work for you.
class Country:
us_balance = 42
def buy(ci, country, amount):
if country.lower() == "us":
new = ci.us_balance = ci.us_balance - amount
ci.us_balance = new
def stats(ci):
print(ci.us_balance)
# Create an instance of the class
ci = Country()
while True:
user_input = input("> ").lower()
if user_input == "buy":
amount = input("$ ").lower()
balance_to_set = amount.split()
buy(ci, balance_to_set[0], int(balance_to_set[1]))
if user_input == "stats":
stats(ci)
break
All I had to do was just add parentheses to the .upper() function in the class
Python beginner here. Sorry if it's a basic python concept
over = False
def run():
user_input = input("Over? (y/n): ")
if(user_input == 'y'):
over = True
while not over:
run()
Although the input is 'y' the loop doesn't stop.
You need to write global over, so function run() will change global variable
over = False
def run():
global over
user_input = input("Over? (y/n): ")
if(user_input == 'y'):
over = True
while not over:
run()
You shouldn't be using a global variable here. Return a boolean, and call run as the condition of the loop. (At this point, you may want to reconsider the name run as well.)
def run():
user_input = input("Over? (y/n)")
return user_input == 'y'
while run():
...
You are setting the local variable over inside the function run(), but you aren't passing it out to the scope from which it was called. Instead return the value to the calling scope like this:
over = False
def run():
user_input = input("Over? (y/n): ")
if(user_input == 'y'):
over = True
else:
over = False
return over
while not over:
over = run()
A beginner's problem, here it goes:
I'm writing a program which keeps records of a game of darts. The user types in the players and their respective scores. It's possible to do a query about a player's scores and ask the program for the best overall score between all the players. I have the following functions:
add_score
return_players_score
return_best_score
exit_program
main
In main(), we begin by creating a new empty dictionary (say, players = {}). Then we ask the user to input a number that takes him/her to the function of choice (1: add_score etc.).
Now, once we're in add_score and have added a key:value pair (player:score), we need to go back to inputting the number taking to the function of choice. I implemented it simply by writing main() to the end of add_score.
That, however, takes us to the beginning, where there's players = {} and thus whatever data we input in add_score gets wiped out. This then affects other functions and the program remains useless as long as it forgets everything right away. How to solve this?
I'd paste the actual code but it's not in English and it's an assignment anyway...
Thanks.
Rather than calling main() from each of your other functions, you should just return (or run off the end of the function, which is equivalent to return None). Since you need the main function to run things repeatedly, you should use a loop.
def main():
players = {}
while True: # loop forever (until a break)
choice = input("what do you want to do (1-4)")
if choice == "1":
add_score(players)
elif choice == "2":
return_players_score(players)
#...
elif choice == "4":
break # break out of the loop to quit
else:
print("I didn't understand that.")
If you have a loop that does something like the following..
example:
while True:
players = {}
some code adding to players
This loop will always reset players to {}
However, if you do:
players = {}
while something:
some code adding to players
then players is not being reset at the start of each iteration through the loop
But your question is not clear
If you have something like this:
def add_score(dicccionary):
#do something with diccionary
main()
def main():
dicccionary = {}
while something:
option = input("option")
if option == 1:
addscore(dicccionary)
else:
#otherfunction
main()
your reset problem can be solve like:
dicccionary = {} #global variable
def add_score():
#do something with diccionary
main()
def main():
option = input("option")
if option == 1:
addscore()
else:
#otherfunction
main()
By the way, you shouldn't make it this way, try something as:
dicccionary = {} #global variable
def add_score():
#do something with diccionary
def main():
while somecondition:
option = input("option")
if option == 1:
addscore()
else:
#otherfunction
main()
If I was doing it for real then I would go for something like:
import sys
class ScoreKeeper(object):
def init(self):
self.scores = {}
def add_score(self, player, score):
self.scores[player] = score
def _print_player_score(self, player, score):
print 'player:', player, 'score:', score
def print_scores(self):
for player, score in self.scores.items():
self._print_player_score(player, score)
def best_score(self):
best, player = 0, "no player"
for player, score in self.scores.items():
if score > best:
best, player = score, player
self._print_player_score(player, best)
if __name__ == '__main__':
scorer = ScoreKeeper()
quit = lambda: sys.exit()
choices = quit, scorer.add_score, scorer.print_scores, scorer.best_score
def help():
print 'Enter choice:'
for index, c in enumerate(choices):
print '%d) %s' % (index, c.__name__)
def get_integer(prompt):
res = raw_input(prompt)
try:
return int(res)
except:
print 'an integer is required'
return get_integer(prompt)
def get_choice():
choice = get_integer('choice? ')
if not 0 <= choice < len(choices):
help()
return get_input()
return choice
help()
choice = get_choice()
while(choice):
args = []
if choices[choice] == scorer.add_score:
args.append(raw_input('player name? '))
args.append(get_integer('score? '))
choices[choice](*args)
choice = get_choice()
quit()