So i Tried using this chunk of code to create a calculator in python, since I have just started learning. Thing is, it always says I enter an invalid option, passing through all my if-else statements, even when I do enter a valid option. What did I do wrong ?
#!/usr/bin/env python
def add():
return float(input ("Enter a number: ")) + float(input ("Enter another number: "))
def subt():
return float(input ("Enter a number: ")) - float(input ("Enter another number: "))
def mult():
return float(input ("Enter a number: ")) * float(input ("Enter another number: "))
def power():
return float(input ("Enter a number: ")) ** float(input ("Enter another number: "))
def division():
return float (input ("Enter a number: ")) / float (input ("Enter another number: "))
s = input("Add, Subtract, Multiply, Divide or Power two Numbers: ")
if s == "add":
print(add ())
elif s == "subtract":
print(subt ())
elif s == "multiply":
print(mult ())
elif s == "power":
print(power ())
elif s == "division":
print(division ())
else:
print ("Enter a valid option")
If sounds like you're using Python2. In that case, use raw_input
instead of input
, otherwise it tries to locate a variable/function by the users string input and place the object-name in s
. Where as raw_input
takes a user input as a string and places the string s
.
This is the short answer of the difference between the two.
#!/usr/bin/env python
def add():
return float(input ("Enter a number: ")) + float(input ("Enter another number: "))
def subt():
return float(input ("Enter a number: ")) - float(input ("Enter another number: "))
def mult():
return float(input ("Enter a number: ")) * float(input ("Enter another number: "))
def power():
return float(input ("Enter a number: ")) ** float(input ("Enter another number: "))
def division():
return float (input ("Enter a number: ")) / float (input ("Enter another number: "))
s = raw_input("Add, Subtract, Multiply, Divide or Power two Numbers: ")
if s == "add":
print(add())
elif s == "subtract":
print(subt())
elif s == "multiply":
print(mult())
elif s == "power":
print(power())
elif s == "division":
print(division())
else:
print("Enter a valid option")
There's a lot of differences in Python2 and Python3, specifying which one you're using helps a lot. It either says it at the top of your terminal when you enter the python interpreter or if you execute python --version
.