我是一名小学教师 - 我在ICT中使用python v 2.7。我使用的是第三方公司提供的标准工作方案。到目前为止它一直很棒。我们已经转移到原始输入并遇到障碍,程序如下:
#write input code to declare variables for number of children and number of books
children = raw_input("How many children are there?")
books = raw_input ("How many books does each child need?")
# declare ‘total’ variable from children and books
total = children*books
#print total along with text
print "You will need", total, "books"
错误信息如下:
File "C:\Python34\ss.py", line 6, in <module>
total = children*books
TypeError: can't multiply sequence by non-int of type 'str'
无论我做什么,我都无法获得变量来执行任何类型的数学运算。有什么建议吗?我很乐意让我的孩子写这样的节目。
答案 0 :(得分:0)
此处的问题来自不匹配的类型,因为raw_input
会返回str
类型。即使您输入的内容似乎是一个数字,它也会这样做。所以基本上你试图将2个字符串相乘,这是没有意义的,因此你得到的错误。要正确处理这个问题,首先需要整数:
children = int(raw_input("How many children are there?"))
books = int(raw_input ("How many books does each child need?"))
答案 1 :(得分:0)
原始输入将输入值存储为字符串(请参阅此处:https://docs.python.org/2/library/functions.html#raw_input)
您需要将其转换为整数才能相乘。
分两步完成的一种方法是:
#write input code to declare variables for number of children and number of books
children = raw_input("How many children are there?")
books = raw_input ("How many books does each child need?")
children = int(children)
books = int(books)
total = children*books
#print total along with text
print "You will need", total, "books"
在同一条线上做的另一种方法是:
children = int(raw_input("How many children are there?"))
我会使用第二种,但对于初学者来说,第一种可能更容易掌握。
答案 2 :(得分:0)
您的问题与您将字符串相乘的错误所表明的结果......不会工作
尝试以下方法:
#write input code to declare variables for number of children and number of books
children = int(input("How many children are there?\n"))
books = int(input("How many books does each child need?\n"))
# declare total variable from children and books
total = children * books
#print total along with text
print("You will need", total, "books")
同时确保在评论中取消总计的报价。添加\n
以在每个问题后创建一行。
答案 3 :(得分:0)
raw_input
函数返回一个字符串,将两个字符串相乘并不合理。
你想要的是将字符串转换为整数(因为只有整数值),你可以使用int
函数来执行此操作:total = int(children) * int(books)
Python试图在错误消息中告诉您的内容有点复杂。它来自于可以将一个字符串与一个整数相乘,但不是一个带有另一个字符串的字符串。
>>> "a" * 4
a
这就是为什么它表示你不能将序列乘以&#39;非int&#39;,乘以一个整数是唯一可以做的。
更简单的方法是使用input
函数,它的工作方式与raw_input
完全相同,只是它会自动将字符串转换为正确的格式(即文本保留为字符串,但整数转换为int,浮点转换为浮点数)