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
Related
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'
Hello I'm trying to add two natural numbers and I wanted the program to continue and have an option to break.
This is my code:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum," is Odd")
You can do this using a while loop. So for example:
while True:
play = input("Do you want to play (type no to stop)?")
if play == 'no':
break
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum," is Odd")
Put all of this code in a loop and add option to continue/ break before taking input from the user.
while(True):
option = int(input("Enter 0 to break. Else, continue")
if option == 0:
break
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum," is Odd")
print('entry "quit" when you want toe terminate the program')
# infinite loop
while 1:
# input validation
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
except ValueError:
print('Please entry a number')
print()
# continue would restart the while loop
continue
if(num1 == 'quit' or num2 == 'quit'):
# break will terminate the while loop
break
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum," is Odd")
You can always nest these statements in a while loop and break on some condition.
def process_results():
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum,"is Odd")
def get_choice():
print("Enter R to run program or Q to quit:")
choice = input()
return choice
def main():
while(True):
choice = get_choice()
if choice == 'R' or choice == 'r':
process_results()
elif choice == 'Q' or choice == 'q':
print("This program has quit")
else:
print("You must enter R to run program or Q to quit")
main()
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
while True:
print ("Options")
print ("Write 'Quit' if you want to exit")
print ("Write '+'if you want to make an addition")
print ("Write '-' if you want to make a sottration")
print ("Write '*' if you want to make a moltiplication")
print ("Write '/' if you wantto make a division")
user_input == input(":")
if user_input == ("+")
num1 = float(input("Enter a number...")
num2 = float(input("Enter the second number...")
result = str(num1+num2)
print("The result is"+ result)
elif user_input == ("-")
num1 = float(input("Enter a number...")
num2 = float(input("Enter the second number...")
result = str(num1-num2)
print("The result is"+ result)
elif user_input == ("*")
num1 = float(input("Enter a number...")
num2 = float(input("Enter the second number...")
result = str(num1*num2)
print("The result is"+ result)
elif user_input == ("/")
num1 = float(input("Enter a number...")
num2 = float(input("Enter the second number...")
print ("The result is"+ result)
This is the code I have created in python 2.7, but it does not work. I think there's an indentation error. Can you help me?
Fix your indentation and add a colon after each if-statement as the following and change user_input == input(':') to user_input = input(':'):
while True:
print ("Options")
print ("Write 'Quit' if you want to exit")
print ("Write '+'if you want to make an addition")
print ("Write '-' if you want to make a sottration")
print ("Write '*' if you want to make a moltiplication")
print ("Write '/' if you wantto make a division")
user_input = input(":") # fix this line
if user_input == ("+"):
num1 = float(input("Enter a number..."))
num2 = float(input("Enter the second number..."))
result = str(num1+num2)
print("The result is"+ result)
elif user_input == ("-"):
num1 = float(input("Enter a number..."))
num2 = float(input("Enter the second number..."))
result = str(num1-num2)
print("The result is"+ result)
elif user_input == ("*"):
num1 = float(input("Enter a number..."))
num2 = float(input("Enter the second number..."))
result = str(num1*num2)
print("The result is"+ result)
elif user_input == ("/"):
num1 = float(input("Enter a number..."))
num2 = float(input("Enter the second number..."))
result = str(num1/num2)
print ("The result is"+ result)
EDIT:
Below is a better version of your code that fixes few errors, like reading string input, avoid dividing by zero exception and removing float() type casting because in python 2.7 input() already does that for you.
while True:
print("Options")
print("Write 'Quit' if you want to exit")
print("Write '+'if you want to make an addition")
print("Write '-' if you want to make a sottration")
print("Write '*' if you want to make a moltiplication")
print("Write '/' if you wantto make a division")
user_input = raw_input(":")
if user_input == '+':
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
print('The result is {}'.format(num1+num2))
elif user_input == '-':
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
print('The result is {}'.format(num1-num2))
elif user_input == '*':
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
print('The result is {}'.format(num1*num2))
elif user_input == '/':
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
if num2 == 0:
print("Can't divide by zero.")
else:
print("The result is {}".format(num1/num2))
Also as suggested by other users here is an improved version:
while True:
print("Options")
print("Write 'Quit' if you want to exit")
print("Write '+'if you want to make an addition")
print("Write '-' if you want to make a sottration")
print("Write '*' if you want to make a moltiplication")
print("Write '/' if you wantto make a division")
user_input = raw_input(":")
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
if user_input == "+":
result = str(num1+num2)
elif user_input == "-":
result = str(num1-num2)
elif user_input == "*":
result = str(num1*num2)
elif user_input == "/":
if num2 == 0:
result = "Can't divide by zero"
else:
result = str(num1/num2)
print("The result is", result)
I have managed to create a small calculator in Python, but I am trying to shorten the code unsucsessfully. Can anyone help please?
elif queencommand == "/calc addition" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) + int(num2))
input(Answer)
elif queencommand == "/calc subtraction" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) - int(num2))
input(Answer)
elif queencommand == "/calc multiplication" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) * int(num2))
input(Answer)
elif queencommand == "/calc division" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) / int(num2))
input(Answer)
I am not able to do two operations at once either.
Use functions from the operator module or simple functions you define yourself to the calculation work, then map the operation name from the queencommand string to those functions:
import operator
ops = {
'addition': operator.add,
'subtraction': operator.sub,
'multiplication': operator.mul,
'division': operator.truediv
}
if queencommand.startswith("/calc"):
operation = queencommand.partition(' ')[-1]
if operation in ops:
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = ops[operation](int(num1), int(num2))
operator.add could be replaced by lambda a, b: a + b, etc. if you don't want to use a module for those operations.
Here is a fully fledged calculator. See if it helps:
def multiplication():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 * num2
print(ans)
def addition():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 + num2
print(ans)
def subtraction():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 - num2
print(ans)
def division():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 / num2
print(ans)
def Help():
print("""Welcome to Calculator P1!!!
Type "x" for multiplication.
Type "+" for addition.
Type "-" for subtraction.
Type "/" for division.""")
while True:
print("Type 'help' for introduction or instructions")
choice = input("Operator: ")
if choice == "x" or choice == "muliplication":
multiplication()
elif choice == "+" or choice == "addition":
addition()
elif choice == "-" or choice == "subtraction":
subtraction()
elif choice == "/" or choice == "division":
division()
elif choice == "help":
Help()
answer = input('Run again? (y/n): ')
if answer == 'n':
break
elif answer == 'y':
continue
else:
print("""Unrecognized Input.
<<<<RESTARTING PROGRAM>>>>""")
continue