How to parse user input as a number - python

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!

Related

Restart Python script at specific point

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 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.

How to input operator in python?

#Faulty calculator
I want to make a calculator that give the wrong answer of my given question and
give all correct answer of other question
operator = input("Enter operator")
number1 = int(input("Enter your number 1"))
number2 = int(input("Enter your number 2"))
if operator == * and number1 == (45) and number2 == (3):
print(number1operatornumber2: 555)
elif operator == + and number1 == 56 and number2 == 9:
print(number1operatornumber2: 77)
elif operator == / and number1 == (56) and number2 == 6:
print(number1operatornumber2: 4)
else :
print(number1 opertor number2: number1operatornumber2)
In my program comming like this
enter image description here
If you want to take operators as inputs, then you must check every single operator. Here's an edited version of your code that works a little bit.
operator = input("Enter operator: ")
number1 = int(input("Enter your number 1"))
number2 = int(input("Enter your number 2: "))
if operator == '*' and number1 == (45) and number2 == (3):
print(f'{number1 * number2} : 555')
elif operator == '+' and number1 == 56 and number2 == 9:
print(f'{number1 + number2} : 77')
elif operator == '/' and number1 == (56) and number2 == 6:
print(f'{number1 / number2} : 4')
#else :
# print(number1 opertor number2: number1operatornumber2)
Notice the last one. Here you don't know what the operator could be. Hence, you can't apply any operation on it.
operator = input("Enter operator")
number1 = int(input("Enter your number 1"))
number2 = int(input("Enter your number 2"))
if (operator == '*' and number1 == 45 and number2 == 3):
print(number1,operator,number2, 555)
elif (operator == '+' and number1 == 56 and number2 == 9):
print(number1, operator, number2, 77)
elif(operator == '/' and number1 == 56 and number2 == 6):
print(number1, operator, number2, 4)
else :
print(number1, operator, number2, number1,operator,number2)
Update the code by correcting the syntax errors as above. Variables should be seperated by , in the print statement and use quotes to compare operators

IF statements and Input

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

Python Error on while True loop

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

Categories