开发者

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

开发者 https://www.devze.com 2023-04-09 17:53 出处:网络
This question already has answers here: How can I read inputs as numbers? (10 answers) Closed 6 years ago.
This question already has answers here: How can I read inputs as numbers? (10 answers) Closed 6 years ago.

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"


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.


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.


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.


raw_input() returns a string. Convert it to a number before proceeding (since multiplying a string by an integer is a valid operation).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号