为什么这段代码不输出结果呢?

时间:2016-06-24 15:37:27

标签: python

print "HEllo !!"
print "Today, I will calculate something for you !!"
print "Enter your first number"
num1 = raw_input()
print "enter your second number"
num2 = raw_input()
print "type 1 for ADDITION"
print "type 2 for SUBTRACTION"
print "type 3 for MULTIPLICATION"
print "type 4 for DIVISION"
press=raw_input()
if press == 1:
   result = num1 + num2
   print result
if press == 2 :
   result = num1 - num2
   print result
if press == 3:
   result = num1 * num2
   print result
if press == 4:
   result = num1/num2
   print result 

它在if语句之前完美运行,但不输出任何内容 并显示此'>>>'。

3 个答案:

答案 0 :(得分:2)

这里的问题是你得到一个字符串输入,然后直接将它与一个整数值进行比较。由于str不是int所有if语句都评估为False。要么直接与字符串进行比较,要么将输入转换为int

因此,您可以执行以下操作之一:

press=raw_input()
if press == '1':
   result = num1 + num2
   print result
if press == '2' :
   result = num1 - num2
   print result
if press == '3':
   result = num1 * num2
   print result
if press == '4':
   result = num1/num2
   print result 

press=int(raw_input())
if press == 1:
   result = num1 + num2
   print result
if press == 2 :
   result = num1 - num2
   print result
if press == 3:
   result = num1 * num2
   print result
if press == 4:
   result = num1/num2
   print result 

比较字符串应该是首选方法。

答案 1 :(得分:1)

raw_input returns a str object,因此press == 1永远不会成立:

>>> a = raw_input()
1
>>> type(a)
<type 'str'>
>>> a == 1
False
>>> a == '1'
True

您需要使用引号括住数字或使用int(press)将输入转换为整数(但如果用户输入非数字字符串,请注意ValueError异常)

答案 2 :(得分:1)

  1. 您正在检查来自raw_input()的输入,这是一个字符串,对整数。它们从不匹配,您的if块永远不会进入。
  2. 您接受num1num2作为字符串,而不是整数。请改用input()
  3. 请改为尝试:

    print "HEllo !!"
    print "Today, I will calculate something for you !!"
    print "Enter your first number"
    num1 = input()
    print "enter your second number"
    num2 = input()
    print "type 1 for ADDITION"
    print "type 2 for SUBTRACTION"
    print "type 3 for MULTIPLICATION"
    print "type 4 for DIVISION"
    press=raw_input()
    if press == "1":
       result = num1 + num2
       print result
    if press == "2":
       result = num1 - num2
       print result
    if press == "3":
       result = num1 * num2
       print result
    if press == "4":
       result = num1/num2
       print result