todd2323
todd2323

Reputation: 67

getting incorrect answer. what is wrong with this code?

x=raw_input('what is your favorite number? ')
n=x*10
print n

If I plug in 5, I don't get 50. I get 5555555

I have tried declaring float(n) and tooling around with it. nothing helped. I realize this is minor league, but I am just starting to teach myself python. Thanks, Todd

Upvotes: 1

Views: 77

Answers (3)

Tarun Ande
Tarun Ande

Reputation: 31

This is because the default data type of raw_input() is string. You have to cast the string input to an integer for achieving the desired result.

Upvotes: 1

Joseph Farah
Joseph Farah

Reputation: 2534

You are taking in your number as raw_input, meaning, it is returned to the program as a string. When you multiply a string by an integer and print the result, it just prints the string x times, in your case 10 because you attempted to multiply by 10. To prove this, change, the 10 to 20 and watch what happens.

There are two ways to fix this. The first would be to use input() instead of raw_input(), so that it returns a number as a result.

x=input("Please enter a number here.\n")

The second way would be to reassign x to the integer equivalent of the string, using the function int().

x=int(x) # Will turn "10", which is what you have, into 10

This should solve your problem.

Best of luck, and happy coding!

Upvotes: 1

pwilmot
pwilmot

Reputation: 596

When you read a value in from user input like this it is as a string. So x actually equals the string '5' but what you actually want is the number 5.

int(x) * 10

Upvotes: 0

Related Questions