Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unsupported operand type(s) for /: 'str' and 'int' [duplicate]

Tags:

python

I am new to Python and am learning some basics. I would like to know why I am getting this error. The code is:

Hours = raw_input ("How many Hours you worked for today : ")
minutes = (Hours * 60)
Percentage = (minutes * 100) / 60
print "Today you worked : ", "percentage"
like image 884
user975194 Avatar asked Oct 02 '11 07:10

user975194


3 Answers

You have to convert your Hours variable to a number, since raw_input() gives you a string:

Hours = int(raw_input("How many hours you worked for today: "))

The reason why this is failing so late is because * is defined for string and int: it "multiplies" the string by the int argument. So if you type 7 at the prompt, you'll get:

Hours = '7'
minutes = '777777....77777'        # 7 repeated 60 times
Percentage = '77777....77777' / 60 # 7 repeated 60*100 = 6000 times

So when it tries to do / on a string and a number it finally fails.

like image 180
NullUserException Avatar answered Sep 18 '22 13:09

NullUserException


Hours is read as a string. First convert it to an integer:

Hours = int(raw_input("..."))

Note that Hours*60 works because that concatenates Hours with itself 60 times. But that certainly is not what you want so you have to convert to int at the first opportunity.

like image 22
David Heffernan Avatar answered Sep 22 '22 13:09

David Heffernan


Your value Hours is a string. To convert to an integer,

Hours = int(raw_input("How many hours you worked for today : "))

Values in Python have a specific type, and although a string may contain only digits, you still can't treat it as a number without telling Python to convert it. This is unlike some other languages such as Javascript, Perl, and PHP, where the language automatically converts the type when needed.

like image 31
Greg Hewgill Avatar answered Sep 21 '22 13:09

Greg Hewgill