我在python中编写这个计算器,我想知道为什么任何if语句中的print语句都没有运行。这是代码:
firstnum = raw_input("What is your first number?")
type(firstnum)
op = raw_input("What is your operation?")
type(op)
secondnum = raw_input("What is your second number?")
type(secondnum)
def main():
if op == "*":
answer = firstnum * secondnum
print(answer)
if op == "/":
answer = firstnum / secondnum
print(answer)
if op == "-":
answer = firstnum - secondnum
print(answer)
输出: 它只是退出代码而没有错误。
答案 0 :(得分:1)
代码实际上存在几个问题:
raw_input
的返回值可能包含回车符。使用strip()
从输入中删除任何空格。raw_input
返回字符串。你不能用字符串做计算。您需要先将输入转换为数字。firstnum = float(raw_input("What is your first number?").strip())
op = raw_input("What is your operation?").strip()
secondnum = float(raw_input("What is your second number?").strip())
if op == "*":
answer = firstnum * secondnum
print(answer)
if op == "/":
answer = firstnum / secondnum
print(answer)
if op == "-":
answer = firstnum - secondnum
print(answer)