在Python中混淆raw_input()的结果

时间:2014-08-19 07:27:52

标签: python

我遇到“operator”变量问题。到目前为止我只试过+。它似乎没有注册,我无法弄清楚为什么。我在repl.it上使用在线python解释器,因为我的计算机出现问题。

编辑:我应该补充一点,我刚开始学习Python(我有一些Java经验,但它是在几年前)。我正在尝试创建一个简单的文本计算器。

    restart=raw_input("to restart calculations enter \'true\'")

    #if restart == "true":
        #stuff

    numone=raw_input("Enter the first number: ")
    operator = raw_input("Enter the operator(+,-,*,/):")
    operator = str(operator)
    numtwo=raw_input("Enter another number: ")
    print("operator: " + operator)

    if operator== '+':
        answer=numone+numtwo
        print(answer)
        print("test")

    if operator == "-":
        answer=numone-numtwo
        print(answer)

    else:
        print("something went wrong")

    #if operator == "*":

2 个答案:

答案 0 :(得分:3)

你的问题是你要连接两个字符串,你应该在int之前投射:{/ p>

answer = int(numone) + int(numtwo)

为什么呢?因为raw_input将输入读取为字符串。

答案 1 :(得分:2)

elif提供给第二个陈述

因为用户提供了'+'

第一个if语句可用,但在下一个语句中fails并转到else,因此对于+,您会two result同时添加错误< / p>

您还需要将operands转换为integer

在转换为整数时还需要检查整数的正确条件,否则会产生错误

numone=raw_input("Enter the first number: ")
operator = raw_input("Enter the operator(+,-,*,/):")
operator = str(operator)
numtwo=raw_input("Enter another number: ")
print("operator: " + operator)

if operator== '+':
    try:        
        answer=int(numone)+int(numtwo)
        print(answer)
        print("test")
    except  ValueError:
        print "one of the operand is not integer"

elif operator == "-":
    try:
       answer=int(numone)-int(numtwo)
       print(answer)
       print("test")
    except  ValueError:
       print "one of the operand is not integer"        

else:
    print("something went wrong")