Ok so I am very new to Python and I recently took on the challenge of creating a very simple calculator.
It works completely fine but I want to add a option to restart and go back to the main menu area rather than restarting the program entirely. How could this be done?
here is the code that i have so far
from math import sqrt
import time
print("Welcome to Calculator")
print(" #1 Add \n #2 Subtract \n #3 Multiply \n #4 Divide \n #5 Square Root")
option = input("Select one #: ")
if option == "1":
print("Addition:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) + float(num2)
print("The answer is: ", result)
elif option == "2":
print("Subtraction:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) - float(num2)
print("The answer is: ", result)
elif option == "3":
print("Multiplication:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) * float(num2)
print("The answer is: ", result)
elif option == "4":
print("Division:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) / float(num2)
print("The answer is: ", result)
elif option == "5":
print("Square Root:")
num1 = input("Enter Number: ")
result = sqrt(float(num1))
print("The answer is: ", result)
I tried the adding While True to the program but I was not able to figure out how that works.
Wrapping your whole code in a while True loop would work but you need to write an if statement at the end in order to exit the infinite loop. Here's the working code:
from math import sqrt
import time
while True:
print("Welcome to Calculator")
print(" #1 Add \n #2 Subtract \n #3 Multiply \n #4 Divide \n #5 Square Root")
option = input("Select one #: ")
if option == "1":
print("Addition:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) + float(num2)
print("The answer is: ", result)
elif option == "2":
print("Subtraction:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) - float(num2)
print("The answer is: ", result)
elif option == "3":
print("Multiplication:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) * float(num2)
print("The answer is: ", result)
elif option == "4":
print("Division:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) / float(num2)
print("The answer is: ", result)
elif option == "5":
print("Square Root:")
num1 = input("Enter Number: ")
result = sqrt(float(num1))
print("The answer is: ", result)
restart = input("Do you want to restart the program? (yes/no) ")
if restart.lower() != "yes":
break
You can add while loop like this:
while True:
option = input("Select one #: ")
if option == "1":
print("Addition:")
...
elif option == "5":
print("Square Root:")
num1 = input("Enter Number: ")
result = sqrt(float(num1))
print("The answer is: ", result)
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'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)
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
I recently started learning Python. I have never coded before, but it seemed like a challenge. The first thing I have made is this calculator. However, I can't seem to get it to work.
while True:
print("Typ 'plus' to add two numbers")
print("Typ 'min' to subtract two numbers")
print("Typ 'multiplication' multiply two numbers")
print("Typ 'division' to divide two numbers")
print("Typ 'end' to abort the program")
user_input = input(": ")
if user_input == "end"
break
elif user_input == "plus":
num1 = float(input("Give a number: "))
num2 = float(input("Give another number: "))
result = str(num1 + num2)
print("The anwser is: " + str(result))
elif user_input == "min":
num1 = float(input("Give a number: "))
num2 = float(input("Give another number: "))
result = str(num1 - num2)
print("The anwser is: " + str(result))
elif user_input == "maal":
num1 = float(input("Give a number:"))
num2 = float(input("Give another number: "))
result = str(num1 * num2)
print("The anwser is: " + str(result))
elif user_input == "deel":
num1 = float(input("Give a number: "))
num2 = float(input("Give another number: "))
result = str(num1 + num2)
print("The anwser is: " + str(result))
else:
print ("I don't understand!")
I know it will probably something stupid, I am still very much learning. Just trying to pickup a new skill instead of bothering my friends who do know how to code.
You missed a colon after an this if statement
if user_input == "end"
break
Should Be:
if user_input == "end":
break