Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm new to Python. I tried to make a basic calculator, but i can't really find the problem. It returns with 0 exit code, but nothing appears, no input no nothing. Any help with this will greatly be appreciated. Thank You.
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def div(num1, num2):
return num1/num2
def multi(num1,num2):
return num1*num2
def main():
operation = input("What do you want to do?(+, -, *, or /):")
if (operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("Your input is invalid. Please enter a valid input.")
else:
num1 = float(input("Enter value for num1: "))
num2 = float(input("Enter value for num2: "))
if (operation == "+"):
print(add(num1, num2))
elif (operation == "-"):
print(subtract(num1, num2))
elif (operation == "*"):
print(multi(num1,num2))
elif (operation == "/"):
print(div(num1,num2))
main()
Based on the code above, you are never actually running main(). Right now, you have said that the definition of main is to prompt the user, check if the input was correct, and then do the math. The main() at the end causes the program to repeat after doing all this (not sure if you want the loop or not).
If you don't want the loop, and just want to run the calculator once, just remove the indent of the last main(), because right now the indentation means it is inside of def main(). Just move it to the left to be at the same indentation level as the def main(): and your program should run fine.
I think you are missing:
if __name__ == "__main__":
main()
Your call to main() inside main itself won't execute and that's probably why you aren't getting any input.
Other than that your code should work as expected (make sure you don't divide by zero ;) ).
Edit: to make my answer more obvious, you should have done:
def main():
operation = input("What do you want to do?(+, -, *, or /):")
if (operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("Your input is invalid. Please enter a valid input.")
else:
num1 = float(input("Enter value for num1: "))
num2 = float(input("Enter value for num2: "))
if (operation == "+"):
print(add(num1, num2))
elif (operation == "-"):
print(subtract(num1, num2))
elif (operation == "*"):
print(multi(num1,num2))
elif (operation == "/"):
print(div(num1,num2))
if __name__ == "__main__":
main()
num1=float(input("enter the first number :"))
op = input("sellect the operation :")
num2 = float(input("enter the second number :"))
if op== "+" :
print(num1+num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1*num2)
elif op == "/":
print(num1 / num2)
else:
print("please enter a real operation ")
#this one is more simple
Basic Calculator:
Method 1:
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4): ")
num1 = float(input("Enter first number (Should be in numeric form): "))
num2 = float(input("Enter second number (Should be in numeric form): "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
Method 2:
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4): ")
num1 = float(input("Enter first number (Should be in numeric form): "))
num2 = float(input("Enter second number (Should be in numeric form): "))
if choice == '1':
print(num1,"+",num2,"=", num1+num2)
elif choice == '2':
print(num1,"-",num2,"=", num1-num2)
elif choice == '3':
print(num1,"*",num2,"=", num1*num2)
elif choice == '4':
print(num1,"/",num2,"=", num1/num2)
else:
print("Invalid input")
Happy Learning...:)
def calculate():
operator = input("What operator do you wanna use(*,/,+,-)? ")
possible_op = ["*", "+", "-", "/"]
if not operator == possible_op:
calculate()
number_1 = float(input("What is your first number? "))
if number_1 != float:
calculate()
number_2 = float(input("What is your second number? "))
if number_2 != float:
calculate()
if operator == "+":
print(number_1 + number_2)
elif operator == "-":
print(number_1 - number_2)
elif operator == "*":
print(number_1 * number_2)
elif operator == "/":
print(number_1 / number_2)
else:
print("Wrong Input")
calculate()
again()
def again():
print("Do you wanna calculate again? ")
answer = input("(Y/N) ").lower()
if answer == "y":
calculate()
elif answer == "n":
exit
else:
print("Wrong Input")
again()
calculate()
Does anyone have an idea why my code always asks the operator questions again and again even if there was a right operator? Do i have to change the name of the list and the input getting compared or
There are quite a few things wrong in this code, but you've managed to use what you know and are in the right tracks so rather than giving you a solution I'll just review it for now.
Mostly, I'd recommend to keep your calculate function simple and handle the looping (rather than recursion) somewhere else.
def calculate():
operator = input("What operator do you wanna use(*,/,+,-)? ")
possible_op = ["*", "+", "-", "/"]
if not operator == possible_op: # this will never be true because operator is a string, use `not in`
calculate() # you probably don't want to run calculate again, maybe return early
number_1 = float(input("What is your first number? "))
if number_1 != float: # number_1 is a float it's not the `float` type so always True
calculate() # return
number_2 = float(input("What is your second number? "))
if number_2 != float: # same as number_1 above
calculate() # return
if operator == "+": # this block is good, simple and to the point
print(number_1 + number_2)
elif operator == "-":
print(number_1 - number_2)
elif operator == "*":
print(number_1 * number_2)
elif operator == "/":
print(number_1 / number_2)
else:
print("Wrong Input") # here you also want to retry
calculate() # but not by recursing
again() # and definitely not call again
def again():
print("Do you wanna calculate again? ")
answer = input("(Y/N) ").lower()
if answer == "y":
calculate()
elif answer == "n":
exit # what is this exit ?
else:
print("Wrong Input")
again() # also don't recurse this, loop if you want
calculate()
I need to create a calculator in Python that can perform all of these tasks. I have gotten this far with my code to do addition, subtraction, multiplication, and division. Can someone show me what to add to my code to add log, power, Pythagorean theorem, and factorial to my calculator? These are all the requirements for my calculator below.
Each mathematic operation needs to be its own function/method:
Addition - Takes up to 5 arguments,
Subtraction - - Takes 3 arguments,
Multiplication - Takes 4 arguments,
Division - Takes 2 arguments,
Log - Takes 1 argument,
Raise a number to a power ex. X squared,
Solve Pythagorean theorem,
Factorial
def calculate():
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
else:
print('You have not typed a valid operator, please run the program again.')
# Add again() function to calculate() function
again()
def again():
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
calculate()
elif calc_again.upper() == 'N':
print('See you later.')
else:
again()
calculate()
It's just the ideas of your requested functions. I added some of them to your calculator. You can also change the hints that you want to show to the user.
PS: Better to use while for the calculator loop.
import math
def calculate():
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
! for factorial
log for logarithm(number, base)
hypot for Pythagorean
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
elif operation == '!':
print(math.factorial(number_1))
print(math.factorial(number_2))
elif operation == 'log':
print(math.log(number_1, number_2))
elif operation == 'hypot':
print(math.hypot(number_1, number_2))
else:
print('You have not typed a valid operator, please run the program again.')
# Add again() function to calculate() function
again()
def again():
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
calculate()
elif calc_again.upper() == 'N':
print('See you later.')
else:
again()
calculate()
I updated the answer based on the comment; you want to take a variable number of inputs from a user like n numbers. I used add() for your situation to answer your exact issue and removed additional codes.
def add(numbers_list):
return sum(numbers_list)
if __name__ == "__main__":
while(True):
number_of_inputs = int(input('Number of inputs? '))
numbers = [float(input(f'Please enter a number({i + 1}): ')) for i in range(number_of_inputs)]
print(add(numbers))
I'm making a calculator program, it has a square root feature, but first, you need to type 's' in order to access it, I wanna make it so that the user can type "S" or "s" and have the computer still recognize it and bring up the square root option but if I add the s.upper() and the s variable it works but not as intended the code is:
import math
def calculator():
while True:
s = "s"
intro = input('Hello! Please type * for multiplication, / for division, + for addition, - for subtraction, ** for exponents, and "s" for square root \n')
if intro not in ["*", "/", "+", "-", "**", s.upper(), s]:
print ("that wasnt an option!")
continue
if intro != s:
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
if intro != s.upper():
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
if intro == "*":
print(num1 * num2)
break
elif intro == "/":
print(num1/num2)
break
elif intro == "+":
print(num1 + num2)
break
elif intro == "-":
print(num1 - num2)
break
elif intro == "**":
print(num1 ** num2)
break
elif intro == s.upper():
num_sqr = int(input("What number do you wanna find the square root of \n"))
print(math.sqrt(num_sqr))
break
elif intro == s:
num_sqr = int(input("What number do you wanna find the square root of \n"))
print(math.sqrt(num_sqr))
break
calculator()
whenever a user types s it ignores variables num1 and num2 so it can just do run the num_sqr variable so the output is:
s (or S)
Whats your first number
2
Whats your second number
4
What number do you wanna find the square root of
24
4.898979485566356
Rather than:
s (or S)
What number do you wanna find the square root of
24
4.898979485566356
Why is it doing this and how can I fix it?
Go ahead and call the .capitalize() string method over your intro string; it'll insure the correct formatting for the string letters without messing up the formatting on the operators.
import math
def calculator():
while True:
intro = input('Hello! Please type * for multiplication, / for division, + for addition, - for subtraction, ** for exponents, and "s" for square root \n')
intro = intro.capitalize()
if intro not in ["*", "/", "+", "-", "**", "S"]:
print ("that wasnt an option!")
continue
if intro != "S":
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
if intro == "*":
print(num1 * num2)
break
elif intro == "/":
print(num1/num2)
break
elif intro == "+":
print(num1 + num2)
break
elif intro == "-":
print(num1 - num2)
break
elif intro == "**":
print(num1 ** num2)
break
else:
num_sqr = int(input("What number do you wanna find the square root of \n"))
print(math.sqrt(num_sqr))
break
calculator()
Also just for fun, since this is evaluating string expressions, Python actually provides us with a handy function for applying computations over string objects using the eval() function. So we could also do this:
def calculator():
while True:
intro = input('Hello! Please type * for multiplication, / for division, + for addition, - for subtraction, ** for exponents, and "s" for square root \n')
intro = intro.capitalize()
if intro not in ["*", "/", "+", "-", "**", "S"]:
print ("that wasnt an option!")
continue
if intro != "S":
num1 = input("Whats your first number \n")
num2 = input("Whats your second number \n")
print(
eval(num1+intro+num2)
)
break
else:
num_sqr = int(input("What number do you wanna find the square root of \n"))
print(math.sqrt(num_sqr))
break
Instead of checking if the command is s and then waiting till the end to execute the square root command, you can run the "s" or "S" command before asking the first or second number.
This code will do`
import math
def calculator():
while True:
s = "s"
intro = input('Hello! Please type * for multiplication, / for division, + for addition, - for subtraction, ** for exponents, and "s" for square root \n')
if intro not in ["*", "/", "+", "-", "**", s.upper(), s]:
print ("that wasnt an option!")
continue
if intro == s:
num_sqr = int(input("What number do you wanna find the square root of \n"))
print(math.sqrt(num_sqr))
break
if intro == s.upper():
num_sqr = int(input("What number do you wanna find the square root of \n"))
print(math.sqrt(num_sqr))
break
if intro != s:
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
if intro != s.upper():
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
if intro == "*":
print(num1 * num2)
break
elif intro == "/":
print(num1/num2)
break
elif intro == "+":
print(num1 + num2)
break
elif intro == "-":
print(num1 - num2)
break
elif intro == "**":
print(num1 ** num2)
break
calculator()
The problem with the code is that you did not actually format the input. You just have to upper() your input, and check all the condition with "S". This will also shorten your code.
import math
def calculator():
while True:
intro = input(
'Hello! Please type * for multiplication, / for division, + for addition, - for subtraction, ** for exponents, and "s" for square root \n').upper()
if intro not in ["*", "/", "+", "-", "**", "S"]:
print("that wasnt an option!")
calculator()
if intro != "S":
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
if intro == "*":
print(num1 * num2)
break
elif intro == "/":
print(num1/num2)
break
elif intro == "+":
print(num1 + num2)
break
elif intro == "-":
print(num1 - num2)
break
elif intro == "**":
print(num1 ** num2)
break
elif intro == "S":
num_sqr = int(
input("What number do you wanna find the square root of \n"))
print(math.sqrt(num_sqr))
break
calculator()
You made two if statements with two different conditions and even if you enter "s" or "S" one of the if statements is going to evaluate to True all the time.
# ONE OF THIS IF STATEMENT IS GOING TO BE TRUE ALL TIME WHEN ENTER "S" or "s"
if intro != s:
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
if intro != s.upper():
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
You can easily solve this by evaluating both conditions in only one if statement
if intro != s and intro != s.upper(): #<-- if not "s" or "S"
num1 = int(input("Whats your first number \n"))
num2 = int(input("Whats your second number \n"))
Try changing this:
intro = input('Hello! Please type * for multiplication, / for division, + for addition, - for subtraction, ** for exponents, and "s" for square root \n')
into this:
intro = input('Hello! Please type * for multiplication, / for division, + for addition, - for subtraction, ** for exponents, and "s" for square root \n').lower()
Here I m making a small calculator. accepting two numbers and one operator this will be easy while I'm using function but in this I'm using the while condition statement but there is a error it will not breaking while every operation it will ask to user that it will want to any operation again in 'Y' for yes and 'N' for no but There is an error it will not changing the value of n. Below is my program:
n = 1
def again(number):
print('value of n in again fucntion', n)
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
number = 1
return number
elif calc_again.upper() == 'N':
number = 0
print('value of n after say no', number)
return number
else:
again(n)
while n > 0:
print('while n value', n)
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
again(n)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
again(n)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
again(n)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
again(n)
else:
print('You have not typed a valid operator, please run the program again.')
Can anybody please help me for solving this. Thanks in advance.
You use the local variable number in again, but use n outside. You have to assign the return value of again to n.
def again():
while True:
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
number = 1
return number
elif calc_again.upper() == 'N':
number = 0
print('value of n after say no', number)
return number
n = 1
while n > 0:
print('while n value', n)
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
else:
print('You have not typed a valid operator, please run the program again.')
n = again()
If you want to break your loop, then simply use break where you want the loop to stop.
Edit:
Your loop can be like:
while n > 0:
print('while n value', n)
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
if again(n) == 0:break
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
if again(n) == 0:break
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
if again(n) == 0:break
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
if again(n) == 0:break
else:
print('You have not typed a valid operator, please run the program again.')
There is no need to store a value n
Change the while loop to while True:
Change the again function to return a Boolean.
use the following syntax when calling the again function.
if not again():
break
There is no need to store a value n
Change the while loop to while True:
Change the again function to return a Boolean.
use the following syntax when calling the again function.
if not again():
break
The final code will be something like this.
def again():
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
return True
elif calc_again.upper() == 'N':
return False
else:
return again()
while True:
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)
elif operation == '-':
print('{} - {} = '.format(number_1, number_2))
print(number_1 - number_2)
elif operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
elif operation == '/':
print('{} / {} = '.format(number_1, number_2))
print(number_1 / number_2)
else:
print('You have not typed a valid operator, please run the program again.')
break
if not again():
break
You can simplify your code as follow, and to avoid unnecessary recursion in the code:
operations = {
"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"/": lambda x, y: x / y,
"*": lambda x, y: x * y
}
continue_calculation = ""
while True:
calc_again = input('''Do you want to calculate again?Please type Y for YES or N for NO.''')
if calc_again == "n" or calc_again == "N":
break
operation = input('''Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
number_1 = int(input('Please enter the first number: '))
number_2 = int(input('Please enter the second number: '))
try:
print(operations[operation](number_1, number_2))
except:
print('You have not typed a valid operator, please run the program again.')