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语句之前完美运行,但不输出任何内容 并显示此'>>>'。
答案 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)
raw_input()
的输入,这是一个字符串,对整数。它们从不匹配,您的if
块永远不会进入。num1
和num2
作为字符串,而不是整数。请改用input()
。请改为尝试:
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