number1 = float
number2 = float
number1 = raw_input("Please input the first number: ")
number2 = raw_input("Please input the second number: ")
if number1 > number2:
print number1 + ' is bigger than ' + number2
elif number2 < number1:
print number2 + ' is bigger than ' + number1
else:
print 'You did not follow the instructions properly. Goodbye!'
print "\n"
raw_input("Please press enter to exit.")
答案 0 :(得分:5)
这些行:
number1 = float
number2 = float
不要将输入变为浮点数。相反,他们只是将变量分配给内置float
。
这就是你应该做的事情:
number1 = float(raw_input("Please input the first number: "))
number2 = float(raw_input("Please input the second number: "))
此外,在if语句中,您不能将字符串和浮点数一起添加(尝试这样做会引发TypeError
)。有两种方法可以解决这个问题。第一个是str.format
:
print '{} is bigger than {}'.format(number1, number2)
第二种是用逗号分隔值:
print number1, 'is bigger than', number2
最后,你的逻辑有点偏。第二个if语句应该是这样的:
elif number1 < number2:
否则,它与第一个if语句的作用相同。
以下是您脚本的固定版本:
number1 = float(raw_input("Please input the first number: "))
number2 = float(raw_input("Please input the second number: "))
if number1 > number2:
print '{} is bigger than {}'.format(number1, number2)
elif number1 < number2:
print '{} is bigger than {}'.format(number2, number1)
else:
print 'You did not follow the instructions properly. Goodbye!'
print "\n"
raw_input("Please press enter to exit.")
答案 1 :(得分:2)
您正在比较字符串,这意味着它们将按字典顺序进行比较。
将raw_input
的返回值转换为float:
number1 = float(raw_input("Please input the first number: "))
number2 = float(raw_input("Please input the second number: "))
行:
number1 = float
number2 = float
仅存储对float()
构造函数的引用。 Python没有类型声明,而那些行 not 意味着这两个名称只应该包含浮点值。
然后,您需要在打印时将浮点数转回字符串;您可以使用print
接受多个值来完成此操作的事实:
if number1 > number2:
print number1, 'is bigger than', number2
elif number2 < number1:
print number2, 'is bigger than', number1
或者,您可以将raw_input()
结果存储为字符串,并在比较时仅将值转为float()
:
number1 = raw_input("Please input the first number: ")
number2 = raw_input("Please input the second number: ")
if float(number1) > float(number2):
print number1 + ' is bigger than ' + number2
elif float(number2) < float(number1):
print number2 + ' is bigger than ' + number1