I am just practising basic python and attempting to build a calculator with only addition, subtraction, and multiplication functions. When I run the code and input 1, 2, or 3, I get no output.
Here is my code:
question1 = input("Enter 1 to add, 2 to substract, or 3 to multiply: ")
if question1 == 1:
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = float(num1) + float(num2)
print(result)
elif question1 == 2:
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = float(num1) + float(num2)
print(result)
elif question1 == 3:
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = float(num1) + float(num2)
print(result))
When you get some input with input() in Python3, you get a string.
Test it with following:
foo = input()
print(type(foo))
The result will be <class 'str'>(it means foo's type is string) regardless of your input. If you want to use that input as a integer, you will have to change the type to int(integer).
You should use int(input()) to get a integer like the following:
question1 = int(input("Enter 1 to add, 2 to substract, or 3 to multiply: "))
You have to change the number inputs in each of the if-else blocks too:
if question1 == 1:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 + num2
print(result)
Or, you can just change it when you want to calculate:
result = int(num1) + int(num2)
You need to convert your input to the integer. Try this code:
question1 = int(input("Enter 1 to add, 2 to substract, or 3 to multiply: "))
if question1 == 1:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 + num2
print(result)
elif question1 == 2:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 - num2
print(result)
elif question1 == 3:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 * num2
print(result)
You are well on your way! As mentioned in the comments, all your statements are False because input() just by itself returns string type which will never be equal to an integer.
You just have to change the all the input() of your code to convert it as an int to be stored. Below is an example:
question1 = int(input("Enter 1 to add, 2 to substract, or 3 to multiply: "))
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 made a simple program where it asks for the user to type in 2 numbers, and the program will add the numbers. For some reason my program gives me an error and I am not sure why. The code is below.
choice = input("Enter Choice")
choice2 = input("Enter Choice")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1"+",num2,"=", add(num1,num2))
The error states Syntax Error - Invalid Syntax.
Any help would be appreciated.
You miss a ","
choice = input("Enter Choice")
choice2 = input("Enter Choice")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1,num2))
'add' is not defined. Try below:
choice = input("Enter Choice") choice2 = input("Enter Choice")
num1 = int(input("Enter first number: ")) num2 = int(input("Enter
second number: "))
if choice == '1': print(num1, "+", num2, "=", num1+num2)
total = 0
print ("Enter first number")
num1 = input()
print ("Enter 1)Add 2)Minus 3)Multiply 4)Divide")
choice = input()
while True:
print("Wrong Answer Pick Again")
print("Enter 1)Add 2)Minus 3)Multiply 4)Divide")
choice = input()
if choice => 1 and choice =< 4:
break
if choice == 1:
print ('Enter second number')
num2 = input()
total = num1 + num2
elif choice == 2:
print ('Enter second number')
num2 = input()
total = num1 - num2
elif choice == 3:
print ('Enter second number')
num2 = input()
total = num1 * num2
elif choice == 4:
print ('Enter second number')
num2 = input()
total = num1 / num2
print("Total")
print (total)
I`m getting a syntax error on the "if choice => 1 and choice =<4:" can some one please help. I have tried so many different things and nothing have worked.
This script should work for you :
total = 0
print ("Enter 1)Add 2)Minus 3)Multiply 4)Divide")
choice = int(input())
for _ in range(int(input("total test cases"))):
if choice >= 1 and choice <= 4:
if choice == 1:
print ("Enter first number")
num1 = int(input())
print ('Enter second number')
num2 = int(input())
total = num1 + num2
print("Total is: ",total)
choice=int(input("enter choice again"))
elif choice == 2:
print ("Enter first number")
num1 = int(input())
print ('Enter second number')
num2 = int(input())
total = num1 - num2
print("Total is: ",total)
choice=int(input("enter choice again"))
elif choice == 3:
print ("Enter first number")
num1 = int(input())
print ('Enter second number')
num2 = int(input())
total = num1 * num2
print("Total is: ",total)
choice=int(input("enter choice again"))
elif choice == 4:
print ("Enter first number")
num1 = int(input())
print ('Enter second number')
num2 = int(input())
total = num1 / num2
print("Total is: ",total)
choice=int(input("enter choice again"))
else:
print("wrong number entered")
choice=int(input("enter again"))
Note:If you find this answer helpful you can mark this answer correct
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
I am making a calculator program in my Python, following a tutorial. Here is my code:
print ("This is a calculator program, press Enter to continue")
a = input()
while a == "":
print("Enter 1 for option 1 which adds")
print("Enter 2 for option 2 which subtracts")
print("Enter 3 for option 3 which multiply")
print("Enter 4 for option 4 which divides")
print("Enter 5 for option 5 which quits",)
Option = input("Enter an option number:")
int(Option)
if Option == 1:
Number1 = input("Enter number 1")
Number2 = input("Enter number 2")
int(Number1,Number2)
print(Result = Number1 + Number2)
if Option == 2:
Number1 = input("Enter number 1")
Number2 = input("Enter number 2")
int(Number1,Number2)
print(Result = Number1 - Number2)
if Option == 3:
Number1 = input("Enter number 1")
Number2 = input("Enter number 2")
int(Number1,Number2)
print(Result = Number1 * Number2)
if Option == 4:
Number1 = input("Enter number 1")
Number2 = input("Enter number 2")
int(Number1,Number2)
print(Result = Number1 / Number2)
if Option == 5:
break
It is very basic, it gets up to the point of printing all the option numbers and then asks me to pick one. So I enter "1" as a string, parsing it to an integer 1. However it doesn't go straight to option 1 and instead loops again which is fine I will sort that out later. But again it doesn't go to any option when I enter 1-5. I think I typed in the wrong code to parse it or something?
input() converts the input to a string, so if you need to read an int, you have to cast it.
In the if condition, you could cast the input() result (a string) to int:
Number1 = int(input("Enter number 1"))
then create a variable, let's say result and assign it the sum of the numbers:
result = Number1 + Number2
and finally print the result
print "Result = " + str(result)
The final code should look like this:
print ("This is a calculator program, press Enter to continue")
a = input()
while a == "":
print
print("Enter 1 for option 1 which adds")
print("Enter 2 for option 2 which subtracts")
print("Enter 3 for option 3 which multiply")
print("Enter 4 for option 4 which divides")
print("Enter 5 for option 5 which quits",)
Option = input("Enter an option number:")
if Option == 1:
Number1 = int(input("Enter number 1"))
Number2 = int(input("Enter number 2"))
result = Number1 + Number2
print "Result = " + str(result) # To print you have to cast to `str`
elif Option == 2:
...
elif Option == 3:
...
elif Option == 4:
...
else:
break
Notes:
You could use an if-elif-else as the structure, so if Option == 1, the following conditions won't be checked.
I would also recommend you to follow Python naming convention. Your variable Number1 should be called number1 and so on.
Result of input function is a string, you need to convert it to int, using int type .
>>> foo = "3"
>>> foo
'3'
>>> int(foo)
3
Your misconception might come from that python is a dynamically typed language. But remember that despite variables themselves are untyped, variable values have types.
>>> type(foo)
<class 'str'>
>>> type(int(foo))
<class 'int'>
Your code should look more like this:
print("This is a calculator program. Press Enter to continue.")
while True:
_ = input()
print("Enter 1 for option 1 which adds")
print("Enter 2 for option 2 which subtracts")
print("Enter 3 for option 3 which multiply")
print("Enter 4 for option 4 which divides")
print("Enter 5 for option 5 which quits")
option = int(input("Enter an option number: "))
if option == 5:
break
else:
number1 = int(input("Enter number 1: "))
number2 = int(input("Enter number 2: "))
if option == 1:
result = number1 + number2
elif option == 2:
result = number1 - number2
elif option == 3:
result = number1 * number2
elif option == 4:
result = number1 / number2
print(result)
Salient points:
You aren't doing anything with a. So I got rid of it, and put a call to input that stores its result in _, which is the standard name for a variable whose value you don't care about.
You must explicitly convert option to an int. Python will not implicitly convert for you, and so '1' != 1.
You cannot convert to an int in-place - writing int(number1) does nothing. You must write number1 = int(number1) or similar.
You cannot convert multiple strings to an int in a single statement of the form int(number1, number2). What you're actually doing here is calling int(x, base), where you convert x into an int, interpreted as being in base base.
I refactored your if statements to be more concise
Variable names are typically lowercase in Python.
You cannot assign to a variable inside a print statement.
that code posted contains several errors, below is the corrected code:
print ("This is a calculator program, press Enter to continue")
a = input()
while a == "":
print("Enter 1 for option 1 which adds")
print("Enter 2 for option 2 which subtracts")
print("Enter 3 for option 3 which multiply")
print("Enter 4 for option 4 which divides")
print("Enter 5 for option 5 which quits",)
Option = int(input("Enter an option number:"))
if Option == 1:
Number1 = int(input("Enter number 1"))
Number2 = int(input("Enter number 2"))
# int(Number1,Number2)
Result = Number1 + Number2
if Option == 2:
Number1 = int(input("Enter number 1"))
Number2 = int(input("Enter number 2"))
# int(Number1,Number2)
Result = Number1 - Number2
if Option == 3:
Number1 = int(input("Enter number 1"))
Number2 = int(input("Enter number 2"))
# int(Number1,Number2)
Result = Number1 * Number2
if Option == 4:
Number1 = int(input("Enter number 1"))
Number2 = int(input("Enter number 2"))
# int(Number1,Number2)
Result = Number1 / Number2
print(Result)
if Option == 5:
break
I corrected your code.
_ = input("This is a calculator program, press Enter to continue")
print ("""Enter 1 for option 1 which adds
Enter 2 for option 2 which subtracts
Enter 3 for option 3 which multiplies
Enter 4 for option 4 which divides
Enter 5 for option 5 which quits""")
while True:
Option = input("Enter an option number: ")
if Option == '1':
Number1 = int(input("Enter number 1: "))
Number2 = int(input("Enter number 2: "))
print("The Result is {0}".format(Number1 + Number2))
elif Option == '2':
Number1 = int(input("Enter number 1: "))
Number2 = int(input("Enter number 2: "))
print("The Result is {0}".format(Number1 - Number2))
elif Option == '3':
Number1 = int(input("Enter number 1: "))
Number2 = int(input("Enter number 2: "))
print("The Result is {0}".format(Number1 * Number2))
elif Option == '4':
Number1 = int(input("Enter number 1: "))
Number2 = int(input("Enter number 2: "))
print("The Result is {0}".format(Number1 / Number2))
else:
break
Notes:
Triple quote syntax is good for long multiline strings.
The pythonic way of formatting a printed string is the str.format method.
Good luck learning!