Python calculator/ defining - python

This is meant to be a basic calculator. Can anyone help me to define 'ans' in my code. It says error on line 14. I'm very new to python and don't know how and I'm very stuck. I also need to make sure that whatever the answer to the sum is will be carried over into the next sum the next time I call the function.
def rep(num1,ans):
num2 = int(input("Next number? "))
choice = input("select operation -,+,x,/. ")
if (choice == "+"):
ans= (num1+num2)
elif (choice == "-"):
ans= (num1-num2)
print (ans)
num1 = int(input("First number? "))
rep(num1, ans)
morenum = ("yes")
morenum = input("Do you want to use another number? ")
while (morenum == "yes"):
rep(ans, num1)

You are using ans before you define it: rep(num1, ans)
Initialize ans like this instead:
ans = int(input("First number? "))
morenum = "yes"
while (morenum == "yes"):
morenum = input("Do you want to use another number? ")
rep(ans, num1)
Note that morenum = input("Do you want to use another number? ") needs to be in the loop or it will not be called every time you need it.
There is also the issue that the answer is not being returned from the function and therefore does not update as it should, but that is left as an exercise for the OP.

I see a couple different problems with this code. Nothing that can't be fixed, though!
First of, be mindful of spacing/indentation. Python uses it to know how to 'read' your program and telling what lines of code goes with others. I'm sure some helpful user on here will edit your original q to have proper indentation :-)
def rep(num1,ans):
num2 = int(input("Next number? "))
choice = input("select operation -,+,x,/. ")
if (choice == "+"):
ans = (num1+num2)
elif (choice == "-"):
ans = (num1-num2)
elif (choice == "x"):
ans = (num1*num2)
elif (choice == "/"):
ans = (num1/num2)
print (ans)
num1 = int(input("First number? "))
rep(num1, ans)
This is your first block of code, where you define the rep function with some fixed spacing. The problem is that you're passing ans in as an argument without ever defining it. Just remove it as an argument, and instead have ans get returned by the rep:
def rep(num1):
num2 = int(input("Next number? "))
choice = input("select operation -,+,x,/. ")
if (choice == "+"):
ans= (num1+num2)
elif (choice == "-"):
ans= (num1-num2)
elif (choice == "x"):
ans= (num1*num2)
elif (choice == "/"):
ans= (num1/num2)
return ans
num1 = int(input("First number? "))
rep(num1)
On to the 2nd block:
morenum = ("yes")
morenum = input("Do you want to use another number? ")
while (morenum == "yes"):
rep(num1)
This is where your code gets a little wonky. You initially define the morenum variable, then replace it with an input. Also, this won't work the way you think it will - I think you're under the impression that this will ask the user if they want another number after each time they complete a math operation. To achieve this, use this code instead:
while True:
morenum = input("Do you want to use another number? ")
if morenum == 'yes':
num1 = int(input("First number? "))
rep(num1)
else:
quit()

You are trying to pass a variable ans to the function rep before its ever initialized in this scope.
Try this:
num1 = int(input("First number? "))
ans=0
rep(num1, ans)
Or you could simply call the rep method like this rep(num1, None) or maybe like this rep(num1, 0) and it will work.
Although a better method would be:
def rep(num):
num_two = int(input("Next number? "))
choice = input("select operation -,+,x,/. ")
if choice == "+":
ans = num+num_two
elif choice == "-":
ans= num-num_two
elif choice == "x":
ans= num*num_two
elif choice == "/":
ans= num/num_two
print(ans)
num = int(input("First number? "))
rep(num)

Well, to be honest, I don't know why you are having ans as a parameter in your code. If I were you, I'd just do it like this:
def rep():
goes+=1
firstnum = int(raw_input("first number?") #I am guessing you're using python 2.7
secondnum = int(raw_input("second number?")
operation = raw_input("operation")
if operation=="+":
sum = firstnum+secondnum
return sum
elif operation=="-":
diff = firstnum-secondnum
return diff
elif operation=="*":
product = firstnum*secondnum
return product
elif operation=="/":
quo = float(firstnum)/float(secondnum) #to make sure there's no rounding
return quo
else:
raise ValueError("Improper entry!")
This new function can be called directly like this:
result = rep()

Related

how to make a calculator with a loop until I choose to break

I'm trying to build a calculator with a loop until I choose to break it or end it.
Can you please suggest?
Thank you in advance,
Max
new_operation = input("press enter to make a new operation or type the word exit to finish")
num1 = int(input("Enter a number: "))
op = input("Enter the operator: ")
num2 = int(input("Enter a second number: "))
while new_operation != ("no"):
if op == ("+"):
print (num1 + num2)
elif op == ("-"):
print (num1 - num2)
elif op == ("*"):
print (num1 * num2)
elif op == ("/"):\
print (num1 / num2)
else:
print ("Invalid operation")
new_operation = input("make a new operation")
Your code looks good, but need some tweak to make it "do while" loop kind of implementation.
while True:
num1 = int(input("Enter a number: "))
op = input("Enter the operator: ")
num2 = int(input("Enter a second number: "))
if op == ("+"):
print (num1 + num2)
elif op == ("-"):
print (num1 - num2)
elif op == ("*"):
print (num1 * num2)
elif op == ("/"):\
print (num1 / num2)
else:
print ("Invalid operation")
new_operation = input("press enter to make a new operation or type the word exit to finish")
if(new_operation == ("no")):
break
Some suggestions:
Check your indentation, as commented above. Python is sensitive to that.
Make sure your inputs and outputs are more consistent and useful. Your prompt says I should type exit, but your code requires them to type no...
Your looping structure is a bit broken. This is to be expected for somebody new to coding. One of my favorites for this case is:
print('Welcome to the calculator!')
do_run = True
while do_run:
...
do_run = input('Would you like to continue [y/n]: ')[0].lower() == 'y'

I am Facing a problem i Python where a user says "yes" or "no" the loop still executes anyhow. Why is it so?

I am making a python calculator program that asks a user after completing one calculation whether they want to continue or not. If the user says Yes the loop should run or else it should stop. I am Facing a problem where a user says yes or no the loop still executes anyhow. Why is it so ???
print("This is a Calculator In Python. !!!")
print("I Can Do Addition, Subtraction, Multiplication and Division.!!")
def addition():
print("Please Don't Enter Float Values Here.")
num1 = int(input("Enter First Number.!!"))
num2 = int(input("Enter Second Number. !!"))
result = num1 + num2
return result
def subtraction():
print("Please Don't Enter Float Values Here.")
num1 = int(input("Enter First Number.!!"))
num2 = int(input("Enter Second Number.!!"))
result = num1 - num2
return result
def multiplication():
print("You Can Enter Float Values Here.")
num1 = float(input("Enter First Number.!!"))
num2 = float(input("Enter Second Number.!!"))
result = num1 * num2
return result
def division():
print("You Can Enter Float Values Here.")
num1 = float(input("Enter First Number.!!"))
num2 = float(input("Enter Second Number.!!"))
result = num1 / num2
return result
print("""1. a for Addition
2. s for subtraction
3. m for multiplication
4. d for Division""")
select = "Yes"
while select:
choice = str(input("You Choose The Operation."))
if choice == "a":
print(addition())
elif choice == "s":
print(subtraction())
elif choice == "m":
print(multiplication())
elif choice == "d":
print(division())
else:
print("Invalid Input")
select=str(input('Continue Yes or No '))
print("Thank you..!")
You've defined your loop as while select, which means as long as select is considered to not be None, it will continue looping
In your loop, you assign the user input to select, which means as long as the user inputs anything, it will always keep looping.
To fix this, you should have the while loop check if select is "yes":
while select.lower().strip() == "yes":
choice = input("You Choose The Operation. ")
if choice == "a":
print(addition())
elif choice == "s":
print(subtraction())
elif choice == "m":
print(multiplication())
elif choice == "d":
print(division())
else:
print("Invalid Input")
select = input("Continue Yes or No ")
print("Thank you..!")
Also, input() returns a string so you don't need to wrap it in a str() call.

Unable to get desired outcome of a while True loop

Until this semester I didn't even know a while True was a thing. I have to write a while True loop to loop until the user enters 'n' to break. My problem is restarting the loop if the user enters anything other than 'y' or 'n'. Currently, I can loop with any character besides 'n'. I need a way to catch the if say 'q' was entered, "please enter 'y' or 'n'" and prompt the user again. I have considered doing another while loop within the loop but I feel like there is a more optimal way to achieve this.
def main():
userinput = "y"
display_title()
while True:
userinput.lower() == "y"
choice = ""
display_menu()
choice = str(input("Select a conversion (a/b): "))
while choice == "a" or "b":
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
elif choice != "a" or "b":
print("Please enter a valid option a or b")
choice = str(input("Select a conversion (a/b): "))
userinput = input("Would you like to perform another conversion? (y/n): ")
if userinput == "n":
print()
print("Thanks, Bye!")
break
You don't need another while loop. You could just need to put the input check to the beginning of the loop and add a check for any other character than 'y' and 'n', e.g.:
def main():
userinput = "y"
display_title()
while True:
if userinput == "n":
print()
print("Thanks, Bye!")
break
elif userinput != "y":
userinput = input("Please select yes (y) or no (n)").lower()
continue
### If you get this far, userinput must equal 'y'
choice = ""
display_menu()
choice = str(input("Select a conversion (a/b): "))
while choice == "a" or "b":
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
elif choice != "a" or "b":
print("Please enter a valid option a or b")
choice = str(input("Select a conversion (a/b): "))
userinput = input("Would you like to perform another conversion? (y/n): ").lower()
continue
Be aware, the way you implemented the inner loop asking for the conversion type doesn't allow you to exit the xcript if you suddenly decide abort the procedure e.g. a Keyboard interrupt.
[Edit]
I've not looked at your inner loop. As someone else has suggested,
while choice == "a" or "b"
will always evaluate to True. Why? beacuse internally python will split this expression:
(choice == "a") or "b"
It doesn't matter if choice == "a", as "b" is a non-empty string and thus evaluates to True.
If you were to rewrite yout inner loop as follws:
while choice: # Will evaluate to True as long as choice isn't an empty string.
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
else:
print("Please enter a valid option a or b")
choice = input("Select a conversion (a/b): ")
you'll be able to give the user an option to exit the inner loop by inputing nothing and you'll remove an uneccessary double-check if the choice equals a or b.
Tip: If you want to check if one variable matches one of some different options in a while statement, you could use the following:
while var in [opt1, opt2 ...]:
...

EOFError: EOF when reading a line in a calculator script

I'm trying to program a simple Python calculator but always when I run the code the Atom editor has a problem with reading this line:
while True:
user_input = input(":")
Under this line of code I entered the methods for Python and told it what it should do:
if userinput == "quit":
break
elif userinput == "add":
num1 = float(input("Enter a number"))
num2 = float(input("Enter another number"))
result = str(num1 + num2)
print("The answer is:" + result)
So now when I run this code the Atom editor says that it has a problem with reading this code and it won't ask me for an input as it should.
I think I didn't miss out any code.
This is most likely either mixed tabs and spaces or a missing parenthesis somewhere in your code. also the code has a few mistakes including indentation errors:
while True:
user_input = input(":")
if user_input == "quit":
break
elif user_input == "add":
num1 = float(input("Enter a number"))
num2 = float(input("Enter another number"))
result = str(num1 + num2)
print("The answer is:", result)

My program not showing question or taking inputs in Python

I made this simple Python Maths Quiz Program for some reason sometimes when it is supposed to ask a question it doesn't display the question or allow any input and just says it is incorrect. The problem doesn't happen every time I run the program just sometimes.
import random
def RandomNum():
import random
ran= random.randint(1,10)
return (ran)
def RanOperation():
import random
operation = ['+','-','x']
RanOp = random.choice(operation)
return (RanOp)
stop = False
while stop == False:
Name= input("Hello, what is your name?").title()
print("Hello,", Name, "Welcome to ARITHMETIC QUIZ")
score=0
for i in range(1, 11):
print(str(i)+".")
num1 = RandomNum()
num2 = RandomNum()
operation = RanOperation()
if operation == "+":
ans = num1+num2
elif operation == "-":
if num1 > num2:
ans = num1-num2
elif num2>num1:
ans = num2-num1
elif operation == "x":
ans = num1*num2
if num1 > num2:
num1 = str(num1)
num2 = str(num2)
Answer = int(input((num1+operation+num2+"=")))
elif num2 > num1:
num1 = str(num1)
num2 = str(num2)
Answer = int(input((num2+operation+num1+"=")))
if Answer == ans:
print("Correct!")
score += 1
elif Answer != ans:
print("The correct answer is", ans)
print("Sorry this is incorrect!")
length = int(len(Name))
print("You got", score, "correct out of 10,", Name)
File1 = open('Class_Scores.txt','a')
File1.write("\n %-20s %10d" %(Name , score))
File1.close()
Ask = input("Do you want to continue? Y/N").upper()
if Ask == "N":
stop = True
elif Ask == "Y":
stop = False
Your input() line only runs in two situations:
if num1 > num2:
and
elif num2 > num1:
What happens when num1 and num2 are the same? You won't enter the if block, because num1 > num2 is False; And you won't enter the elif block, because num2 > num1 is also False.
That means the input() won't run at all;
Your code's problem is that you do not always call the input:
if num1 > num2:
num1 = str(num1)
num2 = str(num2)
Answer = int(input((num1+operation+num2+"=")))
elif num2 > num1:
num1 = str(num1)
num2 = str(num2)
Answer = int(input((num2+operation+num1+"=")))
if num1 == num no input is done and the one from before is used (again).
You can solve it by changing one of them to >= or use an additional else: ....
You can shorten/improve your code a lot if you
do not import random multiple times
use a dictionary to decide which function to call (reduces if .. elif .. else
use input validation to avoid crashing on bad input
use string.format() or even better f-strings instead of python 2.7 % formatting
use with open(...) for file operations
structure the code with some more functions
import random
def RanOperation():
return random.choice(['+','-','x'])
def plus():
# get both numbers with one random call
a,b = random.choices(range(1,11),k=2)
return (a,b,a+b)
def minus():
# only operation where a > b matters to not get negative results
# sorting (low to high) and choosing b,a ensures a is at least b or more
# the other operations are cummutative so its better to leave then unsorted
# to train 8x4 as as well as 4x8
b,a = sorted(random.choices(range(1,11),k=2) ) # a > b
return (a,b,a-b)
def mult():
a,b = random.choices(range(1,11),k=2)
return (a,b,a*b)
def get_answer(a,operation,b):
while True:
try:
k = int(input( "{} {} {} = ".format(a,operation,b)))
return k
except Exception:
print("Input a valid number.")
Usage:
# call which function for what ops?
# using mapper["+"]() --> calls the plus() function - this reduces if/else's
mapper = {"-": minus, "+":plus, "x":mult}
while True:
Name= input("Hello, what is your name?").title()
print("Hello,", Name, "Welcome to ARITHMETIC QUIZ")
score=0
for i in range(10):
print(str(i+1)+".")
operation = RanOperation()
a,b,ans = mapper[operation]()
answer = get_answer(a,operation,b)
if answer == ans:
print("Correct!")
score += 1
else:
print("The correct answer is {:>10d}".format(ans))
print("Sorry this is incorrect!")
length = int(len(Name))
print("You got", score, "correct out of 10,", Name)
with open('Class_Scores.txt','a') as File1:
File1.write("\n -{:20s} {:10d}".format(Name , score))
Ask = input("Do you want to continue? Y/N").upper()
if Ask == "N":
break
Output:
Hello, what is your name?Enya
Hello, Enya Welcome to ARITHMETIC QUIZ
1.
10 - 5 = 5
Correct!
2.
8 - 6 = 9
The correct answer is 2
Sorry this is incorrect!
3.
10 - 2 = 8
Correct!
# ...snipp 4-9...
10.
4 - 4 = 0
Correct!
You got 9 correct out of 10, Enya
Do you want to continue? Y/Nn

Categories