为什么if语句中的print语句没有运行?

时间:2017-10-15 13:40:01

标签: python-2.7

我在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)

输出:      它只是退出代码而没有错误。

1 个答案:

答案 0 :(得分:1)

代码实际上存在几个问题:

  1. 根本不调用main函数。你无论如何都不需要它,所以我已将它删除了。
  2. 在某些环境中,raw_input的返回值可能包含回车符。使用strip()从输入中删除任何空格。
  3. raw_input返回字符串。你不能用字符串做计算。您需要先将输入转换为数字。
  4. 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)