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()
Related
I want to produce an endless loop that would to different things depending on some user input.
When the .py is executed the loop starts and does some 'main' programm and the input window opens for the user. When typing 'alt1' the loop jumps in to the function 'main_alt1' and so on.
user_input = 'main'
user_input = input()
while True:
if user_input == 'main'
main()
elif user_input == 'alt1'
main_alt1()
elif user_input == 'exit'
exit()
The problem here is that the input is either given once before the loop (like in the example) or it stops the loop when the input is inside the loop until the input is given.
Does anyone has a smart way to do something like that. It doesn't need to be with input().
I think it's better to use a class to process the user input:
(I updated the code with the process method)
from multiprocessing import Process
from time import sleep
class InvalidAction(Exception):
pass
class Cmd:
def __init__(self):
self._active_thread = None
def _action_hi(self):
while True:
print('Hi!')
sleep(1)
def _action_ping(self):
while True:
print('Pong!')
sleep(1)
#staticmethod
def _get_method_name(action):
return f'_action_{action}'
def process(self, action: str):
method_name = self._get_method_name(action)
if not hasattr(self, method_name):
raise InvalidAction
if self._active_thread is not None:
self._active_thread.terminate()
self._active_thread = Process(target = getattr(self, method_name, None))
self._active_thread.start()
def main():
cmd = Cmd()
while True:
try:
user_input = input('Action: ')
cmd.process(user_input)
except InvalidAction as e:
print(f'Invalid Action!')
except KeyboardInterrupt:
print('Exiting the loop.')
break
except Exception as e:
print(f'Something went wrong - {e}')
if __name__ == '__main__':
main()
user_input = 'main'
user_input = input()
while True:
if user_input == 'main'
main()
elif user_input == 'alt1'
main_alt1()
elif user_input == 'exit'
exit()
user_input = input()
Taking the the input again at the end of loop works. Since it is while True it runs infinitely till user enters exit
after calling every function you can again take update from user to change variable
import keyboard
while True:
if keyboard.read_key() == 'a':
main_alt1()
elif keyboard.read_key() == 'b':
main_alt2()
elif keyboard.read_key() == 'e':
exit()
else:
main()
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".
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 building scientific calculator. After performing the operation it ask do u want to go back in main menu or Exit
def Again():
x=input ("Go back to main menu(Y/N)")
if (x=='Y') or (x=='y'):
continue
else:
break
when user press y it go back to main menu otherwise exit
You can`t use break and continue in function, read tutorial
instead, you can use check in your main loop, and your function must return True or False
def Again():
x=input ("Go back to main menu(Y/N)")
if (x=='Y') or (x=='y'):
return True
else:
return False
while True: # your main loop
# some other code
# check on exit
if Again():
continue
else:
break
This can work!
class Cal:
def main_menu(self):
print ("I am in main menu")
def again(self):
x = raw_input("Go back to main menu(Y/N)")
if x == 'y':
self.main_menu()
if __name__ == '__main__':
c = Cal()
c.again()
When you will enter y it will go to the main menu.
Also, continue and break will not work here as they both are applied in loops.
You can use raw_input instead of input as input does not accept string values.
Thanks to this site I was able to get this far, being the python novice I am, however I'm kind of stuck. I'm trying to loop 'selection', so after a user does some math, rather than just ending it will give them the option to do something else until they select 0 to quit. I tried a bunch of other try and conditional statements but just end up getting answers and such stuck in an infinite loop.
Also, I'm pretty here, but any help is appreciated, also I'm a python nub. I'm writing this with python 2.7, if that matters.
def sum ( arg1, arg2):
total = a + b
return total;
def subtract ( arg1 , arg2):
total = a - b
return total;
def mult ( arg1, arg2):
total = a * b
return total;
def division ( arg1, arg2):
total = (a / b)
return total;
options = ["1", "2", "3", "4", "5", "0"]
print ("Please choose an option for mathing")
print ("1 for addition")
print ("2 for division")
print ("3 for subtraction")
print ("4 for multiplication")
print ("5 ")
print ("0 to exit")
#this will keep prompting the user to provide an input that is listed in 'options'
while True:
selection = input("Please select choose an option to continue")
if selection in options:
break
else:
print("Please choose a valid option")
#user input for mathing
#input will be validated as follows
a = None
while a is None:
try:
a = int(input("please provide a number for A"))
except ValueError:
print "please use a valid integer"
pass
b = None
while b is None:
try:
b = int(input("please provide a number for B"))
except ValueError:
print "please use a valid integer"
pass
#performing the operations
if selection == '1':
print "The sum is", str(sum(a, b))
elif selection == '2':
print "The quotient is", str(division(a, b))
elif selection == '3':
print "The difference is", str(subtract(a, b))
elif selection == '4':
print "The product is", str(mult(a, b))
elif selection == '0':
exit()
heres a few things I would do to make this more efficient..
options should be a dictionary... your in is a lot more efficient on a dictionary than on a list. the beauty of this is the value for each key can be function methods.
ex. options = {1: 'sum', 2: 'subtract' ..... }
then make a class with your math operations in it
class Calculator(object):
def sum(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
#add more operations here
#staticmethod
def start():
while True:
#prompt for input and the operator
whats nice about this is in your checks for the selection you can dynamically call the class method to clean the code up a lot
if selection in options:
getattr(options[selection], Calculator)(a, b)
if you want me to explain more I can finish the example.
for your loop, you can add a method that starts the action and continues looping and doing more operations each time
here is a basic class you can use using those methods I described
class Calculator(object):
loop = None
calculations = 1
current_value = 0
selection = 0
options = {1: 'add', 2: 'subtract', 3: 'multiply', 4: 'divide'}
def __init__(self, loop=True):
self.loop = loop
print 'Welcome to my basic calculator!'
if not self.loop: # dont loop just execute once
self.run()
else:
while True:
self.run()
#staticmethod
def add(x, y):
return x + y
#staticmethod
def subtract(x, y):
return x - y
#staticmethod
def multiply(x, y):
return x * y
#staticmethod
def divide(x, y):
if y != 0: #cant divide by 0
return x / y
#staticmethod
def quit():
exit(0)
def run(self):
if self.calculations == 1:
self.current_value = self.prompt_user_input('please provide a number: ')
self.prompt_operator('Please choose an operator to continue\n1 for addition\n2 for subtraction\n3 for multiplication \n4 for division\n0 to quit\n')
y = self.prompt_user_input('please provide a number: ')
self.current_value = getattr(Calculator, self.options[self.selection])(self.current_value,y)
self.calculations += 1
print 'New value is: ' + str(self.current_value)
def prompt_operator(self, prompt_message):
while True:
self.selection = input(prompt_message)
if self.selection in self.options:
break
elif self.selection == 0:
self.quit()
else:
print("Please choose a valid option")
def prompt_user_input(self, prompt_message):
val = None
while val is None:
try:
val = int(input(prompt_message))
except ValueError:
print "please use a valid integer"
pass
return val
finally to start your calculator off you can just call it and either pass true to continue loops or pass false to only do one calculation
Calculator(loop=True)
Just put a loop around the prompting and calculation. If they enter 0, break from the outer-most loop:
while True:
#this will keep prompting the user to provide an input that is listed in 'options'
while True:
selection = input("Please select choose an option to continue")
if selection in options:
break
else:
print("Please choose a valid option")
if selection == '0':
break
...
#this will keep prompting the user to provide an input that is listed in 'options'
while True:
selection = input("Please select choose an option to continue")
if selection in options:
if selection == 1:
sum()
if selection == 2:
subtract()
.....
if selection == 'q'
break
Change the logic to what I did above, for option,take some action and do break on the quit character/
Firstly, your code should not work as it is now:
if selection == '1': #should return false
That's because using input you are taking a numeric quantity and then comparing it to a string.
change the input of selection to raw_input
Or change the conditional statements like below:
if selection == 1:
Then add a while True over the entire execution block to go through the execution again and again, until 0 is selected.