[英]Python calling functions from a if statement
I want to sum up the numbers taken by raw_input(">")
but instead of giving me the sum when I run the code on the python shell, it gives me the numbers paired.我想总结由
raw_input(">")
获取的数字,但是当我在 python shell 上运行代码时,它没有给我总和,而是给了我配对的数字。 That would be: if I give 4 to answer
and 5 to answer2
on the input, it will return 45 instead of 9. Please help me.这将是:如果我给4
answer
和5 answer2
输入,它会返回45,而不是9,请帮助我。
from sys import argv
def sum(num1, num2):
result =(num1 + num2)
return result
print ' I wanna know your two results'
answer = raw_input(">")
answer2 = raw_input(">")
real_answer = sum(answer, answer2)
print real_answer
You need to convert to integers first:您需要先转换为整数:
answer = int(raw_input(">"))
answer2 = int(raw_input(">"))
or keep them the same and do this:或保持它们相同并执行以下操作:
real_answer = sum(map(int, (answer, answer2)))
or或者
real_answer = sum(int(answer), int(answer2))
With only two numbers, though, you don't need sum()
:但是,只有两个数字,您不需要
sum()
:
real_answer = int(answer) + int(answer2)
It's because the answers are being read as strings, and for strings the addition operator concatenates them.这是因为答案是作为字符串读取的,对于字符串,加法运算符将它们连接起来。 You can fix it by changing the input lines to:
您可以通过将输入行更改为:
answer = int(raw_input(">"))
answer2 = int(raw_input(">"))
This converts the strings to integers before assigning them to answer
and answer2
.这会将字符串转换为整数,然后再将它们分配给
answer
和answer2
。
If you want to support floating point numbers (eg 1.2
), change the int
to float
.如果您想支持浮点数(例如
1.2
),请将int
更改为float
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.