amateurprogrammer
amateurprogrammer

Reputation: 7

ving trouble with multiplication in python

i was recently practicing with python when i came across a slight issue with multiplication every time i run this:

nights = raw_input('How many nights do you intend to stay?:')    
if len(nights) > 0 and nights.isdigit():         
    cost = 3000 * nights  
    print cost  
else:  
    print "Error, enter a number"

i get this answer once i input, for example 5:

How many nights do you intend to stay?:5
55555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555 (basically very many fives)

anyone with any idea on how to solve it. thanks.

Upvotes: 0

Views: 39

Answers (1)

Vikas Ojha
Vikas Ojha

Reputation: 6950

In Python, raw_input returns a string object, and thats why you already have to check for isdigit. So, you will need to typecast nights to int first.

Change your code to following -

cost = 3000 * int(nights)

You are still not getting an error and a valid result because Python supports string multiplication, i.e.,

>>> s = 'a'
>>> s * 10
'aaaaaaaaaa'

Upvotes: 2

Related Questions