If I have a function with multiple functions, let say, calculating an area or adding three numbers.
The user chose 1 for calculating area and 2 for adding numbers via input
def func_calculate(numberOne, numberTwo, numberThree, userChoise):
if userChoise == "1":
calculate Area
do something
if userChoise == "2":
calculate addition
do something
userChoise is the input from user
If user wants to calculate area there is only two arguments to the function instead of three, if user wants to make an addition.
So, finally to the question...
What is the most appropriate way to handle it?
When I call the function, when the user wants to calculate area, should I just set the numberThree variable to zero or something or is it a more "right" way do do it?
if userChoie == "1":
inputNumberOne = input(...
inputNumberTwo = input(...
inputNumberThree == 0
func_calculate(inputNumberOne, inputNumberTwo, inputNumberThree, userChoise)
If you wan't to perform multiple operations than it is good to have different functions for different operations
choice = input("what user want's to do")
if choice == 1:
add()
elif choice == 2:
multiply()
and than take arguments from user for that operations like
def add():
num1 = input("num1")
num2 = input("num2")
num3 = input("num3")
print(num1 + num2 + num3)
and similarly for other operations
But if you don't wan't to have multiple functions the you can do
def func(choice):
#choice is the integer which user opted
if choice == 1:
num1 = input("num1")
num2 = input("num2")
num3 = input("num3")
print(num1 + num2 + num3)
elif choice == 2:
.........
A good approach to this problem will be to have multiple functions, each with a specific role. You can make two separate functions calculate_area() and add_numbers(). Then, you can simply check the input and call these functions like this:
userChoice = input("Enter choice: ")
if userChoice == "1":
inputNumberOne = input("Enter number 1: ")
inputNumberTwo = input("Enter number 2: ")
calculate_area(inputNumberOne, inputNumberTwo)
elif userChoice == "2":
inputNumberOne = input("Enter number 1: ")
inputNumberTwo = input("Enter number 2: ")
inputNumberThree = input("Enter number 3: ")
add_numbers(inputNumberOne, inputNumberTwo, inputNumberThree)
If you really want to use only one function with a variable number of parameters, you could use *args as argument. For example:
def funct_calculate(*args):
if len(args) == 2:
Calculate Area
else:
Addition
funct_calculate(radius,pi)
funct_calculate(number1,number2,number3)
Related
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 months ago.
I have the following code:
print('''How to use this calculator:
1 - Enter the type of function you want it to do like addition(+), subtraction(-), etc.
2 - Enter your number and it'll keep asking you until you say it to stop
3 - Voila! you have your answer\n''')
while 1 > 0:
function = input("Enter the type of function you want to do:\n")
if function == 'addition' or 'Addition' or 'ADDITION' or 'aDDITION' or '+' or 'add':
num1 = int(input("Enter your number:\n"))
num2 = int(input("Enter your number:\n"))
total = num1 + num2
print('Your answer is ' + str(total))
continue
elif function == 'subtraction' or 'Subtraction' or 'SUBTRACTION' or 'sUBTRACTION' or '-' or 'subtract':
num1 = int(input("Enter the number you want to subtract from:\n"))
num2 = int(input(f"Enter the number you want to subtract from {num1}:\n"))
total = num1 - num2
print('Your answer is' + str(total))
continue
elif function == 'multiplication' or 'multiply' or '*' or 'Multiply' or 'MULTIPLY':
num1 = int(input("Enter the number you want to multiply:\n"))
num2 = int(input(f"Enter the number you want to multiply {num1} wit:\n"))
total = num1 * num2
print('Your answer is' + str(total))
continue
elif function == 'divide' or 'DIVIDE' or '/':
num1 = int(input("Enter the number you want to divide:\n"))
num2 = int(input(f"Enter the number you want to divisor for {num1}:\n"))
total = num1 / num2
print('Your answer is' + str(total))
continue
elif function == 'stop' or 'STOP' or 'Stop' or 'sTOP':
break
else:
print('Can\'t understant what you want to do please write your choice in the format below\n' + '''How to use this calculator:
1 - Enter the type of function you want it to do like addition(+), subtraction(-), etc.
2 - Enter your number and it'll keep asking you until you say it to stop
3 - Voila! you have your answer''')
I have a infinite loop which asks you to enter a function. And I have if-elif-else statements to see, which function the user inputed. I want the function the user inputed to be the one that gets activated, but for a reason it always does addition. Any help is appreciated!
In python a string can get evaluated as a boolean. An empty string returns False and a non-empty one returns True.
Example:
print(bool("A non empty string"))
Output:
True
Example:
print(bool("")) # <---- Empty String
Output:
False
In the if statements you have, you wrote:
if function == 'addition' or 'Addition' or 'ADDITION' or 'aDDITION' or '+' or 'add':
...
Python first checks if function equals "addition" then if not it continues to the next condition and that is simply "Addition". Since there is no comparison or anything like that it simply gets evaluated to True and, thus the if statement becomes True, because you used or (So only one of the conditions have to be True.)
To fix this you have to add function == ... to your every check as such:
if function == 'addition' or function == 'Addition' or function == 'ADDITION' or function == 'aDDITION' or function == '+' or function == 'add':
...
To make this more readable you can use the in keyword and check if function is in the tuple as such:
if function in ('addition', 'Addition', 'ADDITION', 'aDDITION', '+', 'add'):
...
And to make this even better you can upper case the function and check if function is ADDITION only not every combination like "Addition", "aDdition"...
This is how you do it:
if function.upper() in ('ADDITION', '+', 'ADD'):
...
And here is the full working code (I also did a little bit of cleaning):
print('''How to use this calculator:
1 - Enter the type of function you want it to do like addition(+), subtraction(-), etc.
2 - Enter your number and it'll keep asking you until you say it to stop
3 - Voila! you have your answer\n''')
while True:
function = input("Enter the type of function you want to do:\n").upper()
if function in ('ADDITION', '+', 'ADD'):
num1 = int(input("Enter your number:\n"))
num2 = int(input("Enter your number:\n"))
total = num1 + num2
print(f'Your answer is {total}')
continue
elif function in ('SUBTRACTION', '-', 'SUBTRACT'):
num1 = int(input("Enter the number you want to subtract from:\n"))
num2 = int(input(f"Enter the number you want to subtract from {num1}:\n"))
total = num1 - num2
print(f'Your answer is {total}')
continue
elif function in ('MULTIPLICATION', '*', 'MULTIPLY'):
num1 = int(input("Enter the number you want to multiply:\n"))
num2 = int(input(f"Enter the number you want to multiply {num1} wit:\n"))
total = num1 * num2
print(f'Your answer is {total}')
continue
elif function in ('DIVISION', '/', 'DIVIDE'):
num1 = int(input("Enter the number you want to divide:\n"))
num2 = int(input(f"Enter the number you want to divisor for {num1}:\n"))
total = num1 / num2
print(f'Your answer is {total}')
continue
elif function == 'STOP':
break
else:
print('Can\'t understand what you want to do please write your choice in the format below\n' + '''How to use this calculator:
1 - Enter the type of function you want it to do like addition(+), subtraction(-), etc.
2 - Enter your number and it'll keep asking you until you say it to stop
3 - Voila! you have your answer''')
# Pick the numbers you'd like to use
number1 = (input('What is the first number?\n'))
number2 = (input('What is the second number?\n'))
# Choose what to do with those numbers
Choice = input('Would you like to add, subtract, multiply or divide?\n ')
# Where the calculating happens, if it doesn't go through the error message asking you to use numbers will happen
try :
# Converting the numbers from str into float, if this doesnt happen it means numbers were not used
num1 = float(number1)
num2 = float(number2)
if Choice is add :
answer = num1 + num2
elif Choice is subtract :
answer = num1 - num2
elif Choice is divide :
answer = num1/num2
elif Choice is multiply
answer = num1 * num2
print(answer)
# The error message if the numbers you gave werent in numeric form
except :
print('Please choose proper numbers in numeric form instead of letter/words')
This is the code, the issue I get is:
'File "main.py", line 13
elif Choice is subtract :
^
SyntaxError: invalid syntax'
Any help would be appreciated, thanks :). (If this code just wouldn't work at all, please lmk. Im currently going through a book on how to code and thought this would be fun to try since I just learned about booleans and variables)
I think you mean to do this:
if Choice == 'add':
answer = num1 + num2
elif Choice == 'subtract':
answer = num1 - num2
elif Choice == 'divide':
answer = num1/num2
elif Choice == 'multiply':
answer = num1 * num2
Be careful with indentation. If you have a single if / elseif / elseif / elseif / else chain, each condition should be at the same indent level, and each body should match its condition plus one indent (typically 4 spaces or 1 tab).
To compare a string captured from the user with input() to a literal string, you would do:
if Choice == 'add':
You need to specify the quotation marks around 'add', otherwise it would try to reference a variable called add, which isn't defined.
For == vs is when checking the string, see Why does comparing strings using either '==' or 'is' sometimes produce a different result?
Today i decided to learn some python, tried to do a random choice picker just to train and did it good, but unfortunately i made a function for the choice picker, and made an variable to pick how many choices there is and requests input for it, but something doesnt work out. Let me give you an example of what i mean:
def choices(num):
if num == 3:
randchoicez = [input("What is the first choice? "), input("What is the second choice? "),
input("What is the third choice? ")]
rndchoices = random.choice([1, 2, 3])
if rndchoices == 1:
print(randchoicez[0])
if rndchoices == 2:
print(randchoicez[1])
if rndchoices == 3:
print(randchoicez[2])
elif num == 2:
randchoices = [input("What is the first choice? "), input("What is the second choice? ")]
rndchoice = random.choice([1, 2])
if rndchoice == 1:
print(randchoices[0])
if rndchoice == 2:
print(randchoices[1])
print("Hello and welcome to the random choice program. ")
print("How many choices? (Can be up to 5 and start from 2) ")
nr_choices = input()
choices(nr_choices)
if i call the function 'choices' with a number that you pick its gonna return 0 and do nothing
choices(nr_choices)
but if i call it with a number like 2 like this:
choices(2)
its gonna work.
This is what happens when i run the script with the choices(nr_choices)
You're expecting num to be a number in the function but input() returns a string.
So change your input line to:
nr_choices = int(input())
Which would make nr_choices a number.
im pretty new to programming. I made this calculator in python and I was wondering how can I make it more efficient because it seems a bit inefficient to me. I'm still really unfamiliar with python and some programming concepts so it would be nice to get an idea of different ways I may do this. Perhaps there is a better way for me to set up the functions or maybe a way that they can be put into different classes?
Thanks for any responses
def add():
a = int(raw_input("Enter a number!: \n"))
b = int(raw_input("Enter a number!: \n"))
c = a + b
if a + b == c:
print c
menu()
return c
def sub():
a = int(raw_input("Enter a number!: \n"))
b = int(raw_input("Enter a number!: \n"))
c = a - b
if a - b == c:
print c
menu()
return c
def mul():
a = int(raw_input("Enter a number!: \n"))
b = int(raw_input("Enter a number!: \n"))
c = a * b
if a * b == c:
print c
menu()
return c
def div():
a = float(raw_input("Enter a number!: "))
b = float(raw_input("Enter a number!: "))
c = a / b
if a / b == c:
print c
menu()
return c
def square():
a = int(raw_input("Enter a number!: \n"))
c = a * a
if a * a == c:
print c
menu()
return c
def menu():
print """
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square
6. Exit
"""
choices = [1, 2, 3, 4, 5, 6]
choice = int(raw_input("Enter a number!: \n"))
while True:
if choice == 1:
print add()
elif choice == 2:
print sub()
elif choice == 3:
print mul()
elif choice == 4:
print div()
elif choice == 5:
print square()
elif choice == 6:
exit()
else:
for choose in choices:
if choice != choices:
print "Please enter a number 1 - 6!"
menu()
menu()
First, in the else case where the user entered an invalid menu number, you don't need these lines:
for choose in choices:
if choice != choices:
After all, you already know choice is not valid.
Second, when the user enters 6, rather than exit() you should just return. The program will still end. It's often considered "rude" for a function to call exit() directly--let the caller decide what to do when the function ends.
Third, you don't need to call menu() when your operators succeed. It's strange that you do, since menu() contains its own infinite loop anyway. It's just redundant.
Finally, you can collapse all the two-argument math functions into one, by passing in the actual operation as an argument. The operator module makes this easier.
Putting all these ideas together, here's the new code:
import operator
def dobinaryop(op):
a = float(raw_input("Enter a number!: \n"))
b = float(raw_input("Enter a number!: \n"))
return op(a, b)
def square():
a = float(raw_input("Enter a number!: \n"))
return a * a
def menu():
while True:
print """
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square
6. Exit
"""
choice = int(raw_input("Enter a number!: \n"))
if choice == 1:
print dobinaryop(operator.add)
elif choice == 2:
print dobinaryop(operator.sub)
elif choice == 3:
print dobinaryop(operator.mul)
elif choice == 4:
print dobinaryop(operator.div)
elif choice == 5:
print square()
elif choice == 6:
exit()
else:
print "Please enter a number 1 - 6!"
menu()
You could streamline this even further by putting the various operators into a list and indexing by choice, but that's getting slightly arcane for not much benefit given you only have four such operators, plus two special cases and bounds checking.
There are couple of things which you are repeating in all the functions. Like asking user to input two numbers a & b using raw_input multiples times. They can be put into another method say getTwoNumbers() which will take two inputs from user and return the two numbers. This method (i.e getTwoNumbers())need to be invoked in the function(s) which is/are performing binary operation. Also you are storing the result into another variable c, which can be ommited and hence comparison with binary operation with the variable c is also not required. It is better if you can perform return a+b or return a-b etc, based on the current binary operation you want to perform.
Put functions and related index in a dictionary. Use that dictionary to decide which function to execute.
And get duplicated part of every function out. I think these solutions will get your code better.
I am trying to create a simple python calculator for an assignment. The basic idea of it is simple and documented all over online, but I am trying to create one where the user actually inputs the operators. So instead of printing 1: addition, 2: subtraction, etc, the user would select + for addition, - for subtraction, etc. I am also trying to make Q or q quit the program.
Any ideas for how to allow the user to type operators to represent the operation?
Note: I know I still need to define my remainder operation.
import math
loop = 1
choice = 0
while loop == 1:
print("your options are:")
print("+ Addition")
print("- Subtraction")
print("* Multiplication")
print("/ Division")
print("% Remainder")
print("Q Quit")
print("***************************")
choice = str(input("Choose your option: "))
if choice == +:
ad1 = float(input("Add this: "))
ad2 = float(input("to this: "))
print(ad1, "+", ad2, "=", ad1 + ad2)
elif choice == -:
su2 = float(input("Subtract this: "))
su1 = float(input("from this: "))
print(su1, "-", su2, "=", su1 - su2)
elif choice == *:
mu1 = float(input("Multiply this: "))
mu2 = float(input("with this: "))
print(mu1, "*", mu2, "=", mu1 * mu2)
elif choice == /:
di1 = float(input("Divide this: "))
di2 = float(input("by this: "))
print(di1, "/", di2, "=", di1 / di2)
elif choice == Q:
loop = 0
print("Thank-you for using calculator")
First off, you don't need to assign choice to zero
Second, you have your code right, but you need to put quotes around the operators in your if statements like this
if choice == '+':
to show that you are checking for a string
make your loop like this:
while 1: #or while True:
#do stuff
elif choice == 'Q': #qoutes around Q
break #use the `break` keyword to end the while loop
then, you don't need to assign loop at the top of your program
You should try replacing if choice == + by if choice == "+".
What you're getting from the input is actually a string, which means it can contain any character, even one that represents an operator.