I'm a primary teacher - I'm using python v 2.7 in ICT. I'm using a standard scheme of work provided by 3rd party company. It's been great so far. We've moved onto raw input and hit a snag, Program as follows:
#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"
Error message as follows:
File "C:\Python34\ss.py", line 6, in <module>
total = children*books
TypeError: can't multiply sequence by non-int of type 'str'
No matter what I do, I can't get the variables to perform any kind of mathematical operation. Any advice out there? I'd love to get my kids writing a program like this.
The
raw_inputfunction returns a string, multiplying two strings together doesn't make sense.What you want is to convert the strings to integers (since there will only ever be integer values), you can use the
intfunction to do this:total = int(children) * int(books)What Python is trying to tell you in the error message, is a little more complex. It comes from the fact that you can multiply a string with an integer but just not a string with another string.
Which is why it says that you can't multiply the sequence by a 'non-int', multiplying by an integer is the only one you can do.
An easier way to do all of this is to use the
inputfunction instead, which works in exactly the same way asraw_inputexcept it automatically converts the string into the correct format (i.e text is left as a string but integers are converted to int and floating points to float)