Python Calculator Code - python

I'm fairly new to python and have tried to develop a calculator. I have created it so that it keeps asking you questions until you press 9 and exits. I have made an error while doing this and it keeps asking me to enter first number and keeps looping that
loop = 1
oper = 0
while loop == 1:
num1 = input("Enter the first number: ")
print num1
oper = input("+, -, *, /,9: ")
print oper
num2 = input("Enter the second number: ")
print num2
if oper == "+":
result = int(num1) + int(num2)
elif oper == "-":
result = int(num1) - int(num2)
elif oper == "*":
result = int(num1) * int(num2)
elif oper == "/":
result = int(num1) / int(num2)
elif oper == "9":
loop = 0
print "The result of " + str(num1) + str(oper) + str(num2) + " is " + str(result)
input("\nPress 9 to exit.")

The issue seems to be that you haven't indented. Python cares about how much you indent, and thus only indented lines will be considered part of the while loop. Here only the first line (num1 = input...) is being considered part of the while loop. The simplest way to fix this would be to add four spaces before each line that is supposed to be in the loop (as well as an additional four spaces before each line in an if statement).
See http://www.diveintopython.net/getting_to_know_python/indenting_code.html for more help.

It's because you never do anything to break in the first place. Try changing your oper to include 9:
oper = raw_input("+, -, /, *, or 9 (to exit)": )
Then include an elif statement and change loop to 0 to exit the while loop:
elif oper == "9":
loop = 0
Also, deal with your indention:
loop = 1
while loop == 1:
num1 = input("Enter the first number: ")
print num1
oper = input("+, -, *, /,9: ")
print oper
num2 = input("Enter the second number: ")
print num2
if oper == "+":
result = int(num1) + int(num2)
elif oper == "-":
result = int(num1) - int(num2)
elif oper == "*":
result = int(num1) * int(num2)
elif oper == "/":
result = int(num1) / int(num2)
elif oper == "9":
loop = 0
print "The result of " + str(num1) + str(oper) + str(num2) + " is " + str(result)

You had problem with indentation and here's a better way to exit using break for the while loop:
loop = 1
oper = 0
while loop == 1:
x = input("Press 9 to exit otherwise anything to continue:")#much better way
if x == "9":
break
num1 = input("Enter the first number: ")
print (num1)
oper = input("+, -, *, /: ")
print (oper)
num2 = input("Enter the second number: ")
print (num2)
if oper == "+":
result = int(num1) + int(num2)
elif oper == "-":
result = int(num1) - int(num2)
elif oper == "*":
result = int(num1) * int(num2)
elif oper == "/":
result = int(num1) / int(num2):
else:
print("Invalid operator!") #if user inputs something else other than those
print ("The result of " + str(num1) + str(oper) + str(num2) + " is " + str(result))

Related

How to make a calculator function that uses the operator as an input?

I started learning Python yesterday; this is the first calculator I've made. I noticed that the last lines of code that print the equation's result are repeated.
Can I write a function that takes the operator as input and then prints the result with just one line of code?
I imagine it would be something like this:
def result(operator):
print((str(num1)) + " " + str(operator) + " " + str(num2) + " = " + str(num1 insert operator to compute equation num2))
num1 = float(input("Enter first number: "))
op = None
while op not in ("-", "+", "*", "/"):
op = input("Enter operator (-, +, *, /): ")
num2 = float(input("Enter second number: "))
if op == "-":
print((str(num1)) + " " + str(op) + " " + str(num2) + " = " + str(num1 - num2))
elif op == "+":
print((str(num1)) + " " + str(op) + " " + str(num2) + " = " + str(num1 + num2))
elif op == "*":
print((str(num1)) + " " + str(op) + " " + str(num2) + " = " + str(num1 * num2))
elif op == "/":
print((str(num1)) + " " + str(op) + " " + str(num2) + " = " + str(num1 / num2))
You might try using a dictionary to map strings (operators) to function objects:
from operator import add, sub, mul, floordiv
operations = {
"+": add,
"-": sub,
"*": mul,
"/": floordiv
}
a = float(input("Enter first number: "))
while (op := input("Enter operator: ")) not in operations: pass
# 'operation' is one of the four functions - the one 'op' mapped to.
operation = operations[op]
b = float(input("Enter second number: "))
# perform whatever operation 'op' mapped to.
result = operation(a, b)
print(f"{a} {op} {b} = {result}")
In this case, add, sub, mul and floordiv are the function objects, each of which take two parameters, and return a number.
I would use this method to keep it simple yet powerful.
first generate an expression using fstring
execute eval with the expression: The eval() function evaluates the specified expression, if the expression is a legal Python statement, it will be executed.
first = float(input("Enter the first number: "))
second = float(input("Enter second number: "))
operator = str(input("Enter operator: "))
# add checks for the operator
allowed_ops = ["+", "-", "*", "/"]
if operator not in allowed_ops:
raise Exception(f"Operator {operator} not allowed. Allowed operators are '{', '.join(allowed_ops)}'.")
# execute the expression
result = eval(f"{first} {operator} {second}")
print(result)
print('''
1. +
2. -
3. *
4. /
5. exit
''')
while True:
op = input("please choice the operation? ")
num1 = float(input("please insert first number? "))
num2 = float(input("please insert second number? "))
if op == "+":
result = (num1 + num2)
print("result is:", result)
elif op == "-":
result = (num1 - num2)
print("result is:", result)
elif op == "*":
result = (num1 * num2)
print("result is:", result)
elif op == "/":
result = (num1 / num2)
print("result is:", result)
elif op == "exit":
break
number1 = int(input("pick a number "))
number2 = int (input("pick another number "))
def addition(number1,number2):
sum = (number1 + number2)
return sum
sum = addition(number1,number2)
print(sum)
def multiplication(number1,number2):
product = (number1 * number2)
return product
product = multiplication(number1,number2)
print(product)
def devision(number1,number2):
quotient = (number1 / number2)
return quotient
quotient = devision(number1,number2)
print(quotient)
def subtraction(number1,number2):
remander = (number1 - number2)
return remander
remander = subtraction(number1,number2)
print(remander)

it is keep on printing [duplicate]

This question already has answers here:
What does "while True" mean in Python?
(18 answers)
Closed 2 years ago.
when i run this code it keeps on giving me the answer
here is my code
num1 = float(raw_input("enter a number: ")) # type: float
operation = str(raw_input("enter a operation: "))
num2 = float(raw_input("enter a number: ")) # type: float
while True:
if operation == "+":
print num1 + num2
elif operation == "-":
print num1 - num2
elif operation == "*":
print num1 * num2
elif operation == "/":
print (num1 / num2)
else:
print("Error Error")
What you might want is to put the input taking code into the while loop:
while True:
num1 = float(raw_input("enter a number: ")) # type: float
operation = str(raw_input("enter a operation: "))
num2 = float(raw_input("enter a number: ")) # type: float
if operation == "+":
print (num1 + num2)
elif operation == "-":
print (num1 - num2)
elif operation == "*":
print (num1 * num2)
elif operation == "/":
print (num1 / num2)
else:
print("Error Error")
`while True:` means Infinite Loop.
You can take input inside while loop or you can change the condition of while loop.
remove the while True: and it will only print out the answer once. while loops continue running as long as the argument is true and True is always true :P
What you probably want is for the application to keep calculating input from the user.
Try this
def calculate():
num1 = float(raw_input("enter a number: ")) # type: float
operation = str(raw_input("enter a operation: "))
num2 = float(raw_input("enter a number: ")) # type: float
if operation == "+":
print (num1 + num2)
elif operation == "-":
print (num1 - num2)
elif operation == "*":
print (num1 * num2)
elif operation == "/":
print (num1 / num2)
else:
print("Error Error")
while True:
calculate()

How do i write the users input in a file in python? [duplicate]

This question already has answers here:
Correct way to write line to file?
(17 answers)
Closed 2 years ago.
f = open("calculator.txt", "a+")
a = True
while a == True:
operation = input("Please input an operation (+, -, *, /): ")
num1 = float(input("Please input number 1: "))
num2 = float(input("Please input number 2: "))
if operation == "+":
result = num1 + num2
elif operation == "-":
print(num1 - num2)
elif operation == "*":
print(num1 * num2)
elif operation == "/":
print(num1 / num2)
answer = input("Run again? (Yes/No): ")
if answer == "Yes":
continue
else:
print("Goodbye ")
exit()
How do i go about writing the results of the calculations in a file? Say the user inputs 5 + 5 and the program returns 10, how would I save "10" in a text file? If possible the entire equation "5+5 = 10"
You can use str.format to format result string and then use print() with file= parameter to write to file. For example:
with open('operations.txt', 'a') as f_out:
while True:
operation = input("Please input an operation (+, -, *, /): ")
num1 = float(input("Please input number 1: "))
num2 = float(input("Please input number 2: "))
if operation == "+":
result = num1 + num2
elif operation == "-":
result = num1 - num2
elif operation == "*":
result = num1 * num2
elif operation == "/":
result = num1 / num2
result_string = '{} {} {} = {}'.format(num1, operation, num2, result)
# print result string to screen:
print(result_string)
# save result string to file
print(result_string, file=f_out)
answer = input("Run again? (Yes/No): ")
if answer == "Yes":
continue
else:
print("Goodbye ")
break
Prints:
Please input an operation (+, -, *, /): +
Please input number 1: 1
Please input number 2: 2
1.0 + 2.0 = 3.0
Run again? (Yes/No): Yes
Please input an operation (+, -, *, /): /
Please input number 1: 2
Please input number 2: 4
2.0 / 4.0 = 0.5
Run again? (Yes/No): no
Goodbye
And saves operations.txt:
1.0 + 2.0 = 3.0
2.0 / 4.0 = 0.5
You could do it like this:
f.write(f'{num1} {operation} {num2} = {result}') # for example, '5 + 5 = 10'
if answer == "Yes":
continue
else:
print("Goodbye ")
you can change your program like this:
f = open("calculator.txt", "a+")
a = True
while a:
operation = input("Please input an operation (+, -, *, /): ")
num1 = float(input("Please input number 1: "))
num2 = float(input("Please input number 2: "))
if operation == "+":
result = num1 + num2
elif operation == "-":
result = num1 - num2
elif operation == "*":
result = num1 * num2
elif operation == "/":
result = num1 / num2
print(result)
f.write(f"{num1}{operation}{num2} = {result}\n") #this will save the whole equation
answer = input("Run again? (Yes/No): ")
if answer == "Yes":
continue
else:
print("Goodbye ")
a = False
Just do like this:
with open("calculator.txt", "a+") as myfile:
myfile.write("\n" + result)
Inside if block
You can open the file and write into it like this:
f = open("calculator.txt", "a+")
f.write(f"{num1} {operation} {num2} = {result}")

'none' prints for no apparent reason

print("Entre nummber 1: ")
num1 = float(input('> '))
print("Entre opperation: ")
op = input('> ')
print("Entre nummber 2: ")
num2 = float(input('> '))
result = print("Your Result is:")
if op == "+":
print(num1 + num2)
print(result)
print("Done")
elif op == '-':
print(num1 - num2)
print(result)
print("Done")
elif op == '/':
print(num1 / num2)
print(result)
print("Done")
elif op == '*':
print(num1 * num2)
print(result)
print("Done")
elif op == '**':
print(num1 ** num2)
print(result)
print("Done")
else:
print("Entre a valid opperation")
I tried to make a calculator. It works fine but when at the end a 'none' pops up for no apparent reason .
I don't know why. Any help is appreciated.
This is the problem:
result = print("Your Result is:")
print("Your Result is:") prints this string "Your Result is:" and returns None and now result is equal None. then print(result) prints None
result = print("Your Result is:")
print return nothing None
value of result is None
print(result) #this is none
You should store it in a variable like
result = num1 + num2
print(result) #with calculated value
# remove result = print("Your result is :")
# Add this result = num1 'operation +/-/*/** etc' num2 after your if condittions.
# for example :
if op == "+":
result = num1 + num2
print("Your result is :",result)
if op == "-" :
result = num1 - num2
print("Your result is :",result)
# It will work fine.

What does getting a string index out of range error mean?

I am making a calculator in python 3, and I made a function to check for letters in the input. When it runs the letter check though, it gives me an error of string index out of range. Here is the code:
while True:
num = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
op = input("What operation would you like to use(+,-,*,/,**): ")
num1 = input("What is the first number you want to use: ")
length1 = len(num1)
lc1 = 0
def letterCheck1():
global num1
global length1
global lc1
while lc1 <= length1:
if num1[lc1] in num:
num1 = input("No letters, just numbers: ")
else:
lc1 = lc1 + 1
while True:
letterCheck1()
if len(num1) == 0:
num1 = input("Actually enter something: ")
continue
else:
break
num2 = input ("What is the second number you want to use: ")
length2 = len(num2)
lc2 = 0
def letterCheck2():
global num2
global length2
global lc2
while lc2 <= length2:
if num2[lc2] in num:
num2 = input("No letters, just numbers: ")
else:
lc2 = lc2 + 1
while True:
while True:
if op == "/" and num2 == "0":
num2 = input("It is impossible to divide a number by 0. Try again: ")
continue
else:
break
letterCheck2()
if len(num2) == 0:
num2 = input("Enter more than 0 numbers please: ")
continue
else:
break
if op == "+":
print (float(num1) + float(num2))
elif op == "-":
print (float(num1) - float(num2))
elif op == "*":
print (float(num1) * float(num2))
elif op == "/":
print (float(num1) / float(num2))
elif op == "**":
print (float(num1) ** float(num2))
again = input("Would you like to do another problem? 1(Yes), 2(No): ")
while True:
if again != "1" or again != "2":
again = input("Please enter 1(Yes), or 2(No): ")
continue
else:
break
if again == "1":
continue
elif again == "2":
leave = input("You are about to exit, do you want to continue? 1(Yes), 2(No): ")
while True:
if leave != ("1" or "2"):
leave = input("Please enter 1(Yes), or 2(No): ")
continue
else:
break
if leave == '1':
continue
elif leave == '2':
break
Indexing from 0 to len(num1) - 1. Fix this
while lc1 < length1
and this
while lc2 < length2
Here is a much cleaner way to do it:
def get_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
# not a float, try again
pass
# division is the only operation that requires more than a one-liner
def op_div(a, b):
if b == 0:
print("Dividing by 0 makes the universe explode. Don't do that!")
return None
else:
return a / b
# dispatch table - look up a string to get the corresponding function
ops = {
'*': lambda a,b: a * b,
'/': op_div,
'+': lambda a,b: a + b,
'-': lambda a,b: a - b,
'**': lambda a,b: a ** b
}
def main():
while True:
op = input("What operation would you like to use? [+, -, *, /, **, q to quit] ").strip().lower()
if op == "q":
print("Goodbye!")
break
elif op not in ops:
print("I don't know that operation")
else:
a = get_float("Enter the first number: ")
b = get_float("Enter the second number: ")
res = ops[op](a, b)
print("{} {} {} = {}".format(a, op, b, res))
if __name__=="__main__":
main()

Categories

Resources