compare list with input - python

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()

Related

How do I write a calculator in python? [duplicate]

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...:)

Error message when trying to execute exit() in VS Code

def calculate():
while True:
operator = input("What operator do you wanna use(*,/,+,-)? ")
possible_op = "+-*/"
if operator not in possible_op:
continue
try:
number_1 = float(input("What is your first number? "))
number_2 = float(input("What is your second number? "))
except ValueError:
continue
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)
try:
print("Do you wanna calculate again? ")
answer = input("(Y/N) ").lower()
possible_answers = ["y", "n"]
if answer == "y":
return calculate()
elif answer == "n":
exit()
except input != possible_answers:
print("Wrong Input")
continue
calculate()
When I tried to open my script in Microsoft VS Code, I got this error message:
Traceback (most recent call last):
File "e:\Python\Projects\VsCode\calculator\calculator_school.py", line 31, in calculate
exit()
File "D:\Schule\Phyton\lib\_sitebuiltins.py", line 26, in __call__
raise SystemExit(code)
SystemExit: None
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "e:\Python\Projects\VsCode\calculator\calculator_school.py", line 36, in <module>
calculate()
File "e:\Python\Projects\VsCode\calculator\calculator_school.py", line 32, in calculate
except input != possible_answers:
TypeError: catching classes that do not inherit from BaseException is not allowed
When I open it in my file explorer, the script closes itself in Cmd as it should. But in VS Code it just won't. Why is that?
You can stop the script even with a break in this case.
you're inside a single loop.
You can exit without using try except statement. Try this:
def calculate():
while True:
operator = input("What operator do you wanna use(*,/,+,-)? ")
possible_op = "+-*/"
if operator not in possible_op:
continue
try:
number_1 = float(input("What is your first number? "))
number_2 = float(input("What is your second number? "))
except ValueError:
continue
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)
while True:
print("Do you wanna calculate again? ")
answer = input("(Y/N) ").lower()
if answer == "y":
return calculate()
elif answer == "n":
quit()
else:
print("Wrong Input")
continue
calculate()

Python: How to easily make specific string characters the only possible input

I'm a beginner to coding, and I'm still doing my "first" calculator, and I was wondering how to make only 5 characters ("-" "+" "/" "x" "^") into the only possible input the user can answer, or it will result in a message saying "Invalid", sorry for my limited knowledge about this, it's also my first post here, thanks in advance! This is what I did so far -
try:
number_1 = float(input("Insert number 1 here: "))
sign = str(input("+ - / x ^: "))
number_2 = float(input("Insert number 2 here: "))
except ValueError:
print("Invalid")
exit()
if sign != "-" "+" "/" "x" "^":
print("Invalid")
exit()
elif sign == "-":
print(number_1 - number_2)
elif sign == "+":
print(number_2 + number_1)
elif sign == "/":
if number_2 == 0:
print("Invalid")
exit()
print(number_1 / number_2)
elif sign == "x":
print(number_1 * number_2)
elif sign == "^":
print(number_1 ** number_2)
else:
print("Invalid")
You can use the power of functions! Make a function that repeatedly asks for user input until they give you something valid!
def ask_float(title):
while True:
try:
return float(input(title))
except ValueError:
print("Invalid choice. Try again!")
def ask_sign():
while True:
sign = input("+ - / x ^: ").strip()
if sign in ("+", "-", "/", "x", "^"):
return sign
print("Invalid choice. Try again!")
Now in your code you can do:
number_1 = ask_number("Insert number 1 here: ")
sign = ask_sign()
number_2 = ask_number("Insert number 2 here: ")

How to make a calculator in Python 3

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))

Basic Calculator in Python [closed]

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...:)

Categories

Resources