0

I was just testing a little python maths and I could not multiply numbers! I am really confused because I thought this simple code would work:

test = raw_input("answer")
new = test * 5
print new

Instead, it just gave whatever I wrote five times next to each other. E.g I write 8 and it prints 88888! Can somebody explain this?

Jamie
  • 1,530
  • 1
  • 19
  • 35

1 Answers1

3

You need to cast to int, raw_input returns a string:

test = int(raw_input("answer"))

You can see the type is str without casting:

In [5]: test = raw_input("answer ")
answer 8    
In [6]: type(test)
Out[6]: str
In [7]: test = int(raw_input("answer "))
answer 8    
In [8]: type(test)
Out[8]: int

When you multiply the string python will return the string repeated test times.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • 1
    Yeah, just: `test = int(raw_input("answer"))` (first line) or `new = int(test) * 5` (second line). I like the former better in terms of readability. – pawelswiecki Feb 22 '15 at 15:09