简体   繁体   中英

How could I get and average form python using strings?

I am trying to work out an average using this code:

average = print(please, please2,please3/3)
print(average)

but this error shows up

Traceback (most recent call last):
  File "C:\Users\Philip\Desktop\Python Stuff\Python Task.py", line 31, in <module>
    average = print(please, please2,please3/3)
TypeError: unsupported operand type(s) for /: 'str' and 'int'

And I don't know what that means, and no matter what I try, I can't get an average using the strings please, please2, please3 .

You are trying to divide a string by an integer here:

please3/3

where please3 is a string value in your code:

>>> '10'/3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'

You'd have to convert your values to a number first, I picked int() here:

>>> please3 = '10'
>>> please3 / 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'
>>> int(please3) / 3
3.3333333333333335

All this doesn't give you an average, because for an average you need to sum your 3 values first:

(int(please) + int(please2) + int(please3)) / 3

It'd better if you made this conversion from strings to integers as early as possible, perhaps you are reading this information from a file, at which point you'd also convert the strings there .

Your problem is that the language Python using a computing concept called typing.

Imagine you had 3 apples, 5 oranges and 4 forks. If I told you to add them together and give me how many fruit you had, in your head you'd have to look at each object, decide whether or not it was fruit, and then "convert" it, to evaluate whether or not you should add them to your total. Some are convertible (like oranges and apples) and some are not convertible with lots of work (like forks).

In this case, even though you read those variables as '10', '5' and '3', the compiler doesn't know they're integers (abbreviated as 'int') and treats them as 'strings' (abbreviated as 'str'). You need to 'typecast' them to integers first, and then the compiler knows how to do a '/'.

In this case, you can do it by using the Python function 'int'.

(int(please) + int(please2) + int(please3)) / 3

(You don't need to convert the 3 at the end, as it's already recognized as an int.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM