The code uses operator that was chosen in the previous play even after choosing a different operator after opting to play again.
I've checked the functions again and still can't find where exactly the problem is.
import random
print "Welcome!"
def get_choice():
print "What are we practicing? \n1. Addition (+) \n2. Subtraction (-) \n3. Multiplication (*) \n4. Division (/)"
option = raw_input('> ')
while option != '+' and option != '-' and option != '*' and option != '/':
print "You typed %r which is not valid. Please enter \'+, -, *,or /\'" %(option)
option = raw_input('>')
return option
operation = get_choice()
def ask_question (operation):
numbers = []
for y in range(0,2):
x = random.randint(1,100)
numbers.append(x)
num1 = numbers[0]
num2 = numbers[1]
print num1, operation, num2
response = int(raw_input('>'))
return num1, num2, response
num1, num2, response = ask_question(operation)
def check_response(response):
if operation == '+':
answer = num1 + num2
elif operation == '-':
answer = num1 - num2
elif operation == '*':
answer = num1 * num2
else:
answer = num1 / num2
i = 0
if response == answer:
print "Correct!"
elif response != answer:
while i < 2:
print "Wrong! Try again: \n%r + %r" %(num1, num2)
i += 1
response = raw_input()
if response != answer and i >= 2:
print "Sorry. You run out of chances."
check_response(response)
def repeat():
while True:
print "Do you want to play again?"
again = raw_input('>')
if again == 'y' or again == 'Y':
get_choice()
ask_question(operation)
check_response(response)
else:
break
repeat()
Welcome! What are we practicing?
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
*
18 * 4
72 Correct! Do you want to play again?
y
What are we practicing?
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
+
94 * 83
The reason it gets stuck on one operation is you are not catching any return value from get_choice() when you call it within repeat(). I adjusted the raw_input() to input() so I could get it to work (I'm on python 3.X, and you should upgrade also since 2.X will be discontinued this year!), and it seems to work fine for me now:
def repeat():
while True:
print("Do you want to play again?")
again = input('>')
if again == 'y' or again == 'Y':
operation = get_choice() # you need to assign "operator" to the return value
ask_question(operation)
check_response(response)
else:
break
repeat()
Sample output:
Welcome!
What are we practicing?
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
> +
82 + 72
>154
Correct!
Do you want to play again?
>y
What are we practicing?
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
> -
57 - 28 # the sign did in fact change to -
>
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?
I started learning python last week. I have very weak background in programming as I did C++ before but poorly. I started python and wanted to make a complex calculator. I am trying to learn restrictions and if statements better so I decided to make the calculator for positive values only.
However, upon making this statement. The message appears, but the calculated value also appears.
Here is the code:
op = ""
while op != "#":
num1 = float(input("Enter your first number:"))
op = input("Enter an operator: ")
num2 = float(input("Enter your second number: "))
if num1 < 0 or num2 < 0:
print("Calculator accepts positive values only")
if op == "+":
print(num1+num2)
elif op=="-":
print(num1-num2)
elif op=="*":
print(num1*num2)
elif op=="/":
print(num1/num2)
else:
print("end of program")
How to remove the out put of the calculated number? I want the program to restart the loop when I enter negative numbers
Is there a way to "break" the loop then re-do it again?
I humbly apologize if this is a very trivial question, I recently started, and would love to learn from experienced users here on stackoverflow.
All you really need to do is wrap the if statements in an else loop.
op = ""
while op != "#":
num1 = float(input("Enter your first number:"))
op = input("Enter an operator: ")
num2 = float(input("Enter your second number: "))
if num1 < 0 or num2 < 0:
print("Calculator accepts positive values only")
else:
if op == "+":
print(num1+num2)
elif op=="-":
print(num1-num2)
elif op=="*":
print(num1*num2)
elif op=="/":
print(num1/num2)
else:
print("end of program")
The first if statement checks if the number is positive or not. If it is negative, the loop restarts, however, if it is positive, it tests what the operators are equal to.
Your code is displaying the message along with the ans when you enter a negative value because the condition if op == '+' should be elif op == '+'. Its because it checks the first condition which is true so it prints the message but since the 2nd condition has if as well, it comes out to be true if your operator is + and thus the ans is being displayed. Here's how the correct code would look like:
op = ""
while op != "#":
num1 = float(input("Enter your first number:"))
op = input("Enter an operator: ")
num2 = float(input("Enter your second number: "))
if num1 < 0 or num2 < 0:
print("Calculator accepts positive values only")
elif op == "+":
print(num1+num2)
elif op=="-":
print(num1-num2)
elif op=="*":
print(num1*num2)
elif op=="/":
print(num1/num2)
else:
print("end of program")
break and continue are the operators you are looking for
https://www.programiz.com/python-programming/break-continue
break will stop a loop entirely, continue will stop the current iteration of the loop and go onto the next one.
op = ""
while op != "#":
num1 = float(input("Enter your first number:"))
op = input("Enter an operator: ")
num2 = float(input("Enter your second number: "))
if num1 < 0 or num2 < 0:
print("Calculator accepts positive values only")
continue #start again
if op == "STOP":
break #quit
if op == "+":
print(num1+num2)
Is this an efficient calculator in Python?
def calculator():
print("\nBasic Calculator.\n")
num_1 = input("Enter your first number: ")
operation = input("Enter your operation: ")
num_2 = input("Enter your second number: ")
if operation == ("+"):
sum = float(num_1) + float(num_2)
print ("The answer is:",(sum))
elif operation == ("-"):
sum = float(num_1) - float(num_2)
print ("The answer is:",(sum))
elif operation == ("*"):
sum = float(num_1) * float(num_2)
print ("The answer is:",(sum))
elif operation == ("/") and num_2 == ("0"):
print ("\nYou cannot divide by zero.")
elif operation == ("/"):
sum = float(num_1) / float(num_2)
print ("The answer is:",(sum))
else:
print("Invalid Operation.")
restart = input("\nDo you want to enter another equation? Yes or No?").lower()
if restart == ("yes"):
calculator()
else:
print ("\nEnding Program.")
quit()
calculator()
You can use eval()
a = 1
b = 2
operation = '/'
print(eval(f'{a} {operation} {b}'))
0.5
Handle shenanigans by users:
a = 1
b = 0
operation = '/'
try:
print(eval(f'{a} {operation} {b}'))
except Exception as exp:
print(exp)
Here is another basic example:
operations = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y,
}
try:
x, sign, y = input("Enter expression separated by whitespace(ex: 2 + 3): ").split()
if sign == '0':
break
else:
print(operations[sign](int(x), int(y)))
except (ValueError, KeyError, ZeroDivisionError):
print("Something went wrong, check your input")
It's decent, but reviews of working code belong on CodeReview.SE, not here.
Call the result variable result instead of sum, that obviously only is meaningful for addition.
As per AlexanderLekontsev's answer, you don't need a huge big if...else ladder that always computes result and prints the output. A dispatch dictionary to (binary or unary) lambda function is better. You could have all the functions be binary, and default arg2=None, that way you can handle unary functions.
You're assuming the user types in valid floats in response to num_1, num_2. But what if they press return? or type pi or e? or 'help' or :-D etc. You should catch the exception ValueError: could not convert string to floatand display the user's invalid input back to them, "expected a number"(/"operator").
You only need num_2 if operation is a binary not a unary operation, but future stuff like sqrt, log, log10, trigonometrics (sin, cos, tan), hyperbolics and their inverses (arc-fns) are all unary operations. Just something to keep in mind for the future. Don't hardwire your parser to one expected input sequence.
Inputting numbers could get more complicated in future. What if you wanted to support both hexadecimal 7e8 and float/general/exponential notation 7e8? You might need multiple try...except clauses. You might add a HEX mode in future. But then you'll need to generalize from num1 to say arg1, and if arg1 == HEX then enable(/toggle) hex mode, and recurse/loop.
Suggest printing print("Invalid Operation: must be +,-,*,/,..."), this actually tells the user which operations are legal. So: % isn't, neither is ^, neither is log, cos, sqrt etc.
So if you implement the above, you can support things like e^x
Supporting parentheses would require recursion.
Try this:
def calculate(num1, num2, operator):
operator = operator.strip()
if operator.strip() in ['+', '-', '*', '/']:
if operator == '/' and eval(num2) == 0:
return None
try:
result = eval(f'float({num1.strip()}) {operator} float({num2.strip()})')
except:
return ""
return result
num1 = '3'
num2 = '5'
operator = '+'
result = calculate(num1, num2, operator)
if result == '':
print('Wrong expression !')
elif result == None:
print('Dive bye zero !')
else:
print(f'The answe is {result} !')
Your code is alright but we can improvise by using eval()
print(" Basic Calculator ")
i = ""
while i != 'exit':
i = input(" Enter the expression to evaluate or type 'exit' to exit : ")
print(eval(i))
Here is a very clean and short calculator script:
num1 = float(input("Enter a number: "))
op = (input("Enter an operation: "))
num2 = float(input("Enter another number: "))
if op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "^":
print(num1 ** num2)
else:
print("error, you did not enter a supported operation")
Also if you were wondering ** means ^ or to the power of.
Try this:
this calculator will take several inputs, and you can choose to clear the values or to delete it before computing the result.
values_collector = [] #empty list for all values
multi = 1
total = 0
index = 0
print('''For addition press the +,
For Subtraction press the -
For division press the /
For Multiplication press the *''')
entries = int(input('Enter the number of the values you want to compute: '))
signs = input('Enter the sign: ')
while index < entries:
my_input = int(input('Enter your values: '))
values_collector.append(my_input)
index +=1
to_remove = input('Do you want to remove any values, enter Y for yes and N for no ').upper()
if to_remove == 'Y':
values_re=[]
x = 0
no_to_remove = int(input('How many variables do you want to remove: '))
while x < no_to_remove:
my_removed = int(input('Enter your values: '))
values_re.append(my_removed)
x +=1
for y in values_re:
values_collector.remove(y)
my_clear = input("Do you want to clear all the values press Y for yes and N for No ").upper()
if my_clear == 'Y':
values_collector.clear()
print('There is no values to compute because its cleared')
elif my_clear == 'N':
if signs == '+':
for x in range(len(values_collector)):
total +=values_collector[x]
elif signs == '-':
for x in range(len(values_collector)):
total -=values_collector[x]
elif signs == '*':
for x in range(len(values_collector)):
multi *=values_collector[x]
total = multi
elif signs == '/':
for x in range(len(values_collector)):
multi /=values_collector[x]
total = multi
print('The computation of all the values {} is {}'.format(values_collector, total))
enter code here
Ok, what is wrong with my code? I press run and it doesn't give me anything. at get_num it says "too many positional arguments" and after that its just having issues. I'm not sure what I'm doing wrong.
it says "no value for num 1 argument in function to call" and "no value for num 2 argument in function to call" "unused variable answer"
def main(): #control
operation()
get_num(operation)
if operation == "+":
answer = addition()
elif operation == "*":
answer = multiplication()
elif operation == "-":
answer = subtraction()
else:
answer = division()
def operation(): #prompts the user to enter a mathematical symbol & returns that symbol
print("Enter one of the symbols when asked what operation you would like to preform")
operation = input("Would you like to multiply (*), add (+), subtract (-), or divide(/)? ")
return operation
def get_num(): #prompts the user to enter a single integers & returns that value
print("Enter two numbers you would like to calculate")
num1 = float(input("What is the first number you want to calculate? "))
num2 = float(input("What is the second number you want to calculate? "))
return num1
return num2
def addition(num1, num2): #performs addition of the 2 numbers & returns the sum
addition = num1 + num2
return addition
def subtraction(num1, num2): #performs subtraction of the second number from the first & returns the difference
subtraction = num1 - num2
return subtraction
def multiplication(num1, num2): #performs multiplication of the 2 numbers & returns the product
multiplication = num1 * num2
return multiplication
def division(num1, num2): #if the second number is not zero, performs division of the first number (numerator) by the second number (denominator) and returns the quotient; if the second number is zero, doe not perform the division, but displays a message and returns a zero
division = num1 / num2
return division
if num2 == "0":
print("Error, cannot divide by 0")
def show_answer(answer): #displays the answer from the operation
if operation == '*':
print("The answer for your problem is", multiplication)
elif operation == '-':
print("The answer for your problem is", subtraction)
elif operation == '+':
print("The answer for your problem is", addition)
elif operation == '/':
print("The answer for your problem is", division)
else:
print("error")
Hey your program is written in neat manner but you need to pass the variable to the function ..... You can't define global variable like this
First of all you wrote get_num(operation) but then your function has 0 arguments: def get_num():
Area for improvement:
Python is a scripting language, so you must call the main() function at the bottom to kick it off
use raw_input("message") rather than input("mesage") and convert it yourself using operator = str(raw_input("message"))
You are calling get_num(operation) but operation() is a function, not a value. Maybe you should store the return value of get_num(operation) into a variable like operator = get_num(operation)
Here is how I would make some improvements to your code:
def main(): #control
operator = operation()
nums = get_num()
if operator == '+':
answer = addition(nums[0], nums[1])
elif operator == '*':
answer = multiplication(nums[0], nums[1])
elif operator == '-':
answer = subtraction(nums[0], nums[1])
elif operator == '/':
answer = division(nums[0], nums[1])
else:
raise ValueError("'" + operator + "' Operand not recognized")
# Display result
answer = str(answer)
print(str(nums[0]) + operator + str(nums[1]) + " = " + answer)
def operation(): #prompts the user to enter a mathematical symbol & returns that symbol
print("Enter one of the symbols when asked what operation you would like to preform")
operator = raw_input("Would you like to multiply (*), add (+), subtract (-), or divide(/)? ")
# Convert it to a string
return str(operator)
# NOTE - no need to pass the operator
def get_num(): #prompts the user to enter a single integers & returns that value
print("Enter two numbers you would like to calculate")
num1 = float(raw_input("What is the first number you want to calculate? "))
num2 = float(raw_input("What is the second number you want to calculate? "))
# NOTE - Return as an array rather than 2 return statements
return [num1, num2]
def addition(num1, num2): #performs addition of the 2 numbers & returns the sum
addition = num1 + num2
return addition
def subtraction(num1, num2): #performs subtraction of the second number from the first & returns the difference
subtraction = num1 - num2
return subtraction
def multiplication(num1, num2): #performs multiplication of the 2 numbers & returns the product
multiplication = num1 * num2
return multiplication
def division(num1, num2): #if the second number is not zero, performs division of the first number (numerator) by the second number (denominator) and returns the quotient; if the second number is zero, doe not perform the division, but displays a message and returns a zero
# NOTE - Throw an error if denominator is 0
if num2 == 0:
raise ValueError("Divistion by zero")
division = num1 / num2
return division
# Remember to call main() to kick off the program
main()
Here are some of the problems I see with your question/code:
Your code is poorly indented. I can't really try your code because of all of this weird indentions you have.
Your function call must have the same amount of argument like when you defined it func(x, y) must always be declared with 2 variables like func('Hello', 'World')
returnreturns a data but doesn't save itself. You must assign the value to a variable if you have a use for that data.
You don't quite understand local and global scopes of variables
Anyway avoid asking "why is my code not working" questions
Try this code:
def main(): #control
operation = operate()
num1, num2 = get_num()
if operation == "+":
answer = addition(num1, num2)
elif operation == "*":
answer = multiplication(num1, num2)
elif operation == "-":
answer = subtraction(num1, num2)
elif operation == "/":
answer = division(num1, num2)
else:
print ("Invalid Operation")
show_answer(answer)
def operate(): #prompts the user to enter a mathematical symbol & returns that symbol
print("Enter one of the symbols when asked what operation you would like to preform")
operation = input("Would you like to multiply (*), add (+), subtract (-), or divide(/)? ")
return operation
def get_num(): #prompts the user to enter a single integers & returns that value
print("Enter two numbers you would like to calculate")
num1 = float(input("What is the first number you want to calculate? "))
num2 = float(input("What is the second number you want to calculate? "))
return num1, num2
def addition(num1, num2): #performs addition of the 2 numbers & returns the sum
addition = num1 + num2
return addition
def subtraction(num1, num2): #performs subtraction of the second number from the first & returns the difference
subtraction = num1 - num2
return subtraction
def multiplication(num1, num2): #performs multiplication of the 2 numbers & returns the product
multiplication = num1 * num2
return multiplication
def division(num1, num2): #if the second number is not zero, performs division of the first number (numerator) by the second number (denominator) and returns the quotient; if the second number is zero, doe not perform the division, but displays a message and returns a zero
try:
division = num1 / num2
return division
except ZeroDivisionError:
print ("Error, cannot be divided by 0")
def show_answer(answer):
print ("The answer for your problem is", answer)
main()
You can also just change your else-if statement for your divison to check whether the value of num2 is 0:
elif operation == '/':
if num2 == 0:
return ('Error, cannot be divided by 0')
else:
answer = division(num1, num2)