+ 3
How to code a calculator
I keep trying but it isn't working. Please anyone help me https://sololearn.com/compiler-playground/cMJYvPV87vFL/?ref=app
13 Respuestas
+ 9
The error message should be pretty clear - unexpected indent. Python uses indentation to distinguish structeres (e.g. where if starts and ends). Your indents are all messed up.
+ 9
@Ikechika Dickson
You had problems with your indention and some syntax errors and also some incomplete exception handling...
I have edited your code to the bare minimum and simple to understand, please note the indention.
Now its working perfectly. Below is the code.
#======== START OF CODE ========
first_number=int(input("Please enter first number: "))
print(first_number)
second_number=int(input("Please enter second number: "))
print(second_number)
operator = input("Choose an operation (+) or (-):")
if(operator[0]=="+"):
result = first_number + second_number
elif(operator[0]=="-"):
result = first_number - second_number
print(operator[0])
print("Your answer is" , result)
#======== END OF CODE ========
Let me know if you want me to add exception handling
+ 2
1. your indentations are all wrong.
2.you can't concatenate strings and numbers
3.you have to assign the '+' or '-' operation to a variable
4.your conditions do not need to be in parenthesis, and the syntax is wrong for if(+).
print("please enter two numbers")
try:
first_number=int(input())
second_number=int(input())
print(first_number, second_number)
except ValueError:
print('please enter a valid number')
print("choose an operation (+) or (-)")
try:
operation = input()
print(operation)
if(operation == "+"):
result = first_number + second_number
elif(operation == "-"):
result = first_number - second_number
else:
print('please enter + or -')
print(first_number, operation, second_number, "=", result)
except EOFError:
print('please enter a valid operation')
+ 1
@CodeVortex
I have redone the solution to be more complete with exception handling.
https://www.sololearn.com/en/compiler-playground/c2vUxCe0092Y try and play with it there i have also tried to comment most of the lines so you can understand.
#======== START OF CODE ========
try:
#Wait for input from user for the first and second numbers.
try:
first_number=int(input("Please enter first number: "))
print(first_number)#Print the number typed
second_number=int(input("Please enter second number: "))
print(second_number)#Print the number typed
except ValueError: #Incase any of the two numbers are invalid raise error
raise ValueError("Invalid number...") #The actual error raised
#wait for input from user - the operator (+) or (-)
operator = input("Choose an operation (+) or (-):")
print(operator)#print the operator typed
if operator[0]!="-" and operator[0]!="+": #Check only the first character for validity
raise ValueError(f"Invalid operator '{operator}'") #the actual error raised
if(operator[0]=="+"):
result = first_number + second_number
elif(operator[0]=="-"):
result = first_number - second_number
print("Your answer is", result ) #Print the result
except ValueError as e: #Check if we have an error
print(e) #Print the existing error
Incase you have a question, let me know.
+ 1
It seems the issue lies with indentation and some syntax errors in your code. Here's a simplified version that should work:
first_number = int(input("Please enter first number: "))
second_number = int(input("Please enter second number: "))
operator = input("Choose an operation (+) or (-): ")
if operator == "+":
result = first_number + second_number
elif operator == "-":
result = first_number - second_number
print(f"Your answer is {result}")
This version addresses the indentation and simplifies the logic. Let me know if you need further assistance or would like to add exception handling
+ 1
Apart from indentation, as was already pointed out, your code shows lack of experience and understanding (no offense). I strongly advise you to take the Python course here, starting from the Introduction to Python. It really helps.
0
Thanks mashtullah 🙃
0
You too bob_li
0
# Simple Calculator in Python
def calculator():
print("Simple Calculator")
print("Operations: + - * /")
while True:
# take input
num1 = float(input("Enter first number: "))
op = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))
# perform calculation
if op == "+":
result = num1 + num2
elif op == "-":
result = num1 - num2
elif op == "*":
result = num1 * num2
elif op == "/":
if num2 != 0:
result = num1 / num2
else:
print("Error! Division by zero.")
continue
else:
print("Invalid operator! Try again.")
continue
print(f"Result: {result}")
# check if user wants another calculation
choice = input("Do you want to calculate again? (y/n): ")
if choice.lower() != "y":
print("Exiting Calculator. Goodbye!")
0
I have fixed your code bro, you're welcome:)
The code goes here:
print("please enter two numbers")
return_result = True
try:
first_number=int(input())
second_number=int(input())
except ValueError:
print('please enter a valid number')
print("Choose an operation, (+) or (-)")
operation = input()
if operation == "+":
result = first_number + second_number
elif operation == "-":
result = first_number - second_number
else:
print("You can only enter (+) or (-)")
return_result = False
if return_result:
print("Your answer is " + str(result))
0
i tried coding a calculator similar to https://calculadorade-inflacion.com/index.html but i faced alot of error . it was frustrating but still trying o do so
0
This one really helps me a lot .
https://www.peryourhealth.cc
0
To code a calculator, define functions for basic operations (add, subtract, multiply, divide), take user input, and use conditionals to perform the selected operation. For web, use HTML for layout, CSS for styling, and JavaScript for logic. https://www.hhaexchange.com.co