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()
Related
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 == '+':
result = number_1 + number_2
print(number_1, "+", number_2, "=", result)
elif operation == '-':
result = number_1 - number_2
print(number_1, "-", number_2, "=", result)
elif operation == '*':
result = number_1 * number_2
print(number_1, "*", number_2, "=", result)
elif operation == '/':
result = number_1 / number_2
print(number_1, "/", number_2, "=", result)
else:
print('You have not typed a valid operator, please run the program again.')
return result
def cont():
calc_again = input("Do you want to continue?")
if calc_again.upper() == 'Y':
Tempresult = result
cntr = 0
while cntr == 0:
num3 = int(input("Enter next number: "))
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
if operation == '+':
result1 = Tempresult + num3
print(result1)
else:
print('hi')
else:
print('See you later.')
calculate()
cont()
Your program is throwing error because result is local variable of calculate() . In order to access it in cont() , you have to make it global .
def calculate():
#global variable
global result
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 == '+':
result = number_1 + number_2
print(number_1, "+", number_2, "=", result)
elif operation == '-':
result = number_1 - number_2
print(number_1, "-", number_2, "=", result)
elif operation == '*':
result = number_1 * number_2
print(number_1, "*", number_2, "=", result)
elif operation == '/':
result = number_1 / number_2
print(number_1, "/", number_2, "=", result)
else:
print('You have not typed a valid operator, please run the program again.')
return result
def cont():
global result
calc_again = input("Do you want to continue?")
if calc_again.upper() == 'Y':
Tempresult = result
cntr = 0
while cntr == 0:
num3 = int(input("Enter next number: "))
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')
if operation == '+':
result1 = Tempresult + num3
print(result1)
else:
print('hi')
else:
print('See you later.')
#variable declaration
result=None
calculate()
cont()
The result variable is local. Define the result variable globally. And, use global result inside the function implementation, to instruct the function not to create a new variable result, rather update the global variable.
Here is a hint.
result = 0 # default value
def function(n1, n2, operation):
global result
if operation == '+':
result = n1 + n2
return result
else:
return 0
Digressing a bit from the question, give a thought about the following code (python3+):
def function(n1, n2, operation):
if operation == '+':
print(f'{n1} + {n2} = {n1+n2}')
return n1 + n2
else:
return 0
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}")
Just started learning Python in my computing fundamentals class. We have to build a program that creates practice sets for mathematics. The user inputs two numbers, an operator, then a solution, and the program tells them if they are correct/incorrect. After that, the program is supposed to loop back around so the user can continue practicing. The program is supposed to loop for a total of 5 practice sets. I have the loop, but when it's executed it repeats the inputs initially entered by the user instead of resetting, so the user cannot make any more inputs. What am I missing?
I tried a while True: loop on my global variables but that just causes the main function to loop without completing the program. The assignment very clearly dictates that the use of a while loop is needed, as my professor included slight hints to help us.
num1 = int(input("Enter First Input: "))
num2 = int(input("Enter Second Input: "))
op = str(input("Enter Operator: "))
UserSolution = int(input("Enter Solution: "))
res1 = num1+num2
res2 = num1-num2
res3 = num1*num2
res4 = num1/num2
timesCorrect = 0
timesIncorrect = 0
def main ():
counter = 0
while counter < 4:
print(num1)
print(num2)
print(op)
print(UserSolution)
counter = counter + 1
The function is indeed looping like I want it to, but it isn't resetting the variables like I want it to.
You need to move your input statements to within the loop, for example:
timesCorrect = 0
timesIncorrect = 0
def main ():
counter = 0
while counter < 4:
num1 = int(input("Enter First Input: "))
num2 = int(input("Enter Second Input: "))
op = str(input("Enter Operator: "))
UserSolution = int(input("Enter Solution: "))
res1 = num1 + num2
res2 = num1 - num2
res3 = num1 * num2
res4 = num1 / num2
print(num1)
print(num2)
print(op)
print(UserSolution)
counter = counter + 1
Also, if you want it to loop five times, you need to change the counter comparison to < 5, or <= 4, instead of < 4.
Probably going to be a little beyond the scope of your assignment, but here's an untested suggestion:
# Mix it up a little by hiding the user's suggested solution with getpass()
from getpass import getpass
### Set iterator variable to avoid hard-coding the script
max_iterations = 5
def evaluate_expression(first_input, second_input, operator):
"""
Function to handle arithmetic
"""
my_solution = 0
if operator == '+':
my_solution = first_input + second_input
elif operator == '-':
my_solution = first_input - second_input
elif operator == '/':
# Can't divide by zero, so we have to handle that.
if second_input != 0:
my_solution = first_input / second_input
else:
my_solution = 0
elif operator == '*':
my_solution = first_input * second_input
return my_solution
def main():
### Counters
correct_guesses = 0
incorrect_guesses = 0
try_counter = 1
while try_counter <= max_iterations:
num1 = int(input("Enter First Input: "))
num2 = int(input("Enter Second Input: "))
op = str(input("Enter Operator: "))
UserSolution = int(getpass("Enter Solution: ")) # Hide the input
### We van evaluate the expression and return the result to a variable using eval()
# temp_solution = eval(f'{num1} {op} {num2}')
## Traditional evaluation method
#if op == '+':
# my_solution = num1 + num2
#elif op == '-':
# my_solution = num1 - num2
#elif op == '/':
# my_solution = num1 / num2
#elif op == '*':
# my_solution = num1 * num2
# Call our expression and evaluate the results
if evaluate_expression(num1, num2, op) == UserSolution:
print('You\'re correct!')
correct_guesses += 1
else:
print('Incorrect answer!')
incorrect_guesses += 1
try_counter += 1
print(f'Number of correct guesses: {correct_guesses]\nNumber of incorrect guesses: {incorrect_guesses}')
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.')
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))