Python’添加’功能问题:为什么这不起作用?
发布时间:2020-12-20 11:27:06 所属栏目:Python 来源:网络整理
导读:我刚刚开始学习 Python,我是一个绝对的新手. 我开始学习函数了,我写了这个简单的脚本: def add(a,b): return a + bprint "The first number you want to add?"a = raw_input("First no: ")print "What's the second number you want to add?"b = raw_input(
我刚刚开始学习
Python,我是一个绝对的新手.
我开始学习函数了,我写了这个简单的脚本: def add(a,b): return a + b print "The first number you want to add?" a = raw_input("First no: ") print "What's the second number you want to add?" b = raw_input("Second no: ") result = add(a,b) print "The result is: %r." % result 脚本运行正常,但结果不是总和.即:如果我为’a’输入5,为’b’输入6,结果将不是’11’,而是56.如下: The first number you want to add? First no: 5 What's the second number you want to add? Second no: 6 The result is: '56'. 任何帮助,将不胜感激. 解决方法
raw_input返回string,需要将其转换为int
def add(a,b): return a + b print "The first number you want to add?" a = int(raw_input("First no: ")) print "What's the second number you want to add?" b = int(raw_input("Second no: ")) result = add(a,b) print "The result is: %r." % result 输出: The first number you want to add? First no: 5 What's the second number you want to add? Second no: 6 The result is: 11. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |