Looping main function while resetting variables - python

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

Related

Python calculator script with functions and lists

I am trying to create a simple python calculator with inputs as lists and functions defining the operations that can be performed.
I am having trouble getting my functions to return the value after they have returned.
The program is supposed to get numbers in the form of a list and then pass them into the while loop in the main part of the program. The user can perform as many operations as they want before the program quits.
Please let me know what my error is or if I need to add anything.
def display_menu():
print("Please Choose an option")
print("1. Add (+)")
print("2. Subtract (-)")
print("3. Multiply (*)")
print("4. Divide (/)")
print("q to quit")
def addition():
numlist = input("please enter at least 2 numbers to be operated on.").split()
numlist = [float(num) for num in numlist]
num1 = numlist[0]
del numlist[0]
for num in numlist:
num1 = num1 + num
return num1
def subtraction():
numlist = input("please enter at least 2 numbers to be operated on.").split()
numlist = [float(num) for num in numlist]
num1 = numlist[0]
del numlist[0]
for num in numlist:
num1 = num1 - num
return num1
def multiply():
numlist = input("please enter at least 2 numbers to be operated on.").split()
numlist = [float(num) for num in numlist]
num1 = numlist[0]
del numlist[0]
for num in numlist:
num1 = num1 * num
return num1
def division():
numlist = input("please enter at least 2 numbers to be operated on.").split()
numlist = [float(num) for num in numlist]
num1 = numlist[0]
del numlist[0]
for num in numlist:
num1 = num1 * num
return num1
displ_menu()
operator = input("Please enter an operator: ")
while operator != "q":
if operator == "+":
addition()
elif operator == "-":
subtraction()
elif operator == "*":
multiply()
else:
division()
displ_menu()
operator = input("please enter an operator")
print("Closing calculator")

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

Basic calculator will only add values [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 3 years ago.
I'm new to python and am trying to make a basic calculator that takes two numbers and performs the operation specified by the user, but regardless of the operation I enter, the numbers always add.
num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = input("Type Add, Subtract, Multiply, or Divide" )
if operation == "Add" or "add":
add = num1 + num2
print(add)
elif operation == "Subtract" or "subtract":
sub = num1 - num2
print(sub)
elif operation == "Multiply" or "multiply":
mult = num1 * num2
print(mult)
elif operation == "Divide" or "divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")
With what I have, if num1 = 10 and num2 = 5 and I enter "multiply" the result I get is 15, not 50.
if operation == "Add" or "add"
These are two conditions:
if operation == "Add" which does what you expect.
if "add" - Always evaluates to True because it's a constant string.
So you could just as well have written:
if True. You need to replace it with:
if operation == "Add" or operation == "add"
Anyway, I would like to suggest a few things.
Lowercase then check only once
You should lowercase your input string instead of double checking "Add" or "add":
num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = input("Type Add, Subtract, Multiply, or Divide" ).lower() # Notice the `lower` here
if operation == "add":
add = num1 + num2
print(add)
elif operation == "subtract":
sub = num1 - num2
print(sub)
elif operation "multiply":
mult = num1 * num2
print(mult)
elif operation "divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")
Use the built-in operator module
The operator module contains exactly the methods that you seek for. You could use it for convenience (haven't tested, should work):
import operator
keywords = {"add": "add", "subtract": "sub", "multiply": "mul", "divide": "truediv"}
num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = input("Type Add, Subtract, Multiply, or Divide" )
op_func = keywords.get(operation.lower(), "add") # defaults to add
print(getattr(operator, op_func)(num1, num2))
def fun(operation, num1,num2):
operation = operation.lower()
if operation == "add":
add = num1 + num2
print(add)
elif operation == "subtract":
sub = num1 - num2
print(sub)
elif operation == "multiply":
mult = num1 * num2
print(mult)
elif operation == "divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")
fun('multiply', 10,5)
Why:
if operation == "add" or "Add": this is always True
We can use if operation == "add" or operation == "Add":
You have to do like this:
num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = str(input("Type Add, Subtract, Multiply, or Divide" ))
if operation == "Add" or operation =="add":
add = num1 + num2
print(add)
elif operation == "Subtract" or operation =="subtract":
sub = num1 - num2
print(sub)
elif operation == "Multiply" or operation =="multiply":
mult = num1 * num2
print(mult)
elif operation == "Divide" or operation =="divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")
Because of or operation with string, all your conditions will be true.
That's why it will only go to first condition no matter what you give in the input.

Random numbers and uppercase result instead of a number ->

I'm working on this calculator but the output that I keep getting is function ops at 0x03B0B858 instead of it being a number, and i'm not really sure what i'm doing wrong....
The calculator asks three questions, first number, operator, and the second number. if you type in letters or anything other than numbers when asked the first number and the second number, it will tell you that what you typed in was invalid and asks you to enter a valid number again, the problem is that I'm trying to do that with the operator as well which is defined inside the function ops() but it doesn't matter what I typed in the operator the result will always be random letters and numbers.... This is the code below, you can copy past it and try it and see what I mean by all of this..
try:
num1 = float(input('Enter the first number: '))
except ValueError:
print('Invalid number')
num1 = float(input('Enter first number again: '))
op = input('Enter operator: ')
try:
num2 = float(input('Enter the second number: '))
except ValueError:
print('Invalid number')
num2 = float(input('Enter second number again: '))
def ops():
if op != '+' or '-' or '/' or '*':
op = input('Invalid Operator, please enter operator: ')
elif op == '+':
return num1 + num2
elif op == '-':
return num1 - num2
elif op == '*':
return num1 * num2
elif op == '/':
return num1 / num2
print(ops)
First:
- to run the function 'ops' you should call print(ops()) , do not forget the parentheses
- try putting the code inside the function, otherwise, your function won't recognize the variable 'op'
- you cannot check the content of the variable 'op' like that
op != '+' or '-' or '/' or '*'
this will be evaluated as a single boolean 'OR',
your code should go like that instead:
if op not in ['+' , '-' , '/' , '*']:
do smthg...
Edit 2:
Complete solution:
def ops():
try:
num1 = float(input('Enter the first number: '))
except ValueError:
print('Invalid number')
num1 = float(input('Enter first number again: '))
op = input('Enter operator:')
try:
num2 = float(input('Enter the second number: '))
except ValueError:
print('Invalid number')
num2 = float(input('Enter second number again: '))
if op not in ['+' , '-' , '/' , '*']:
op = input('Invalid Operator, please enter operator: ')
if op == '+':
return num1 + num2
elif op == '-':
return num1 - num2
elif op == '*':
return num1 * num2
elif op == '/':
return num1 / num2
print(ops())

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