簡體   English   中英

我如何使用字符串獲取和平均形成python?

[英]How could I get and average form python using strings?

我正在嘗試使用以下代碼得出平均值:

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

但是這個錯誤出現了

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'

而且我不知道這意味着什么,無論我嘗試什么,都無法平均使用字符串please, please2, please3

您嘗試在此處將字符串除以整數:

please3/3

其中please3是代碼中的字符串值:

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

您必須先將值轉換為數字,我在這里選擇了int()

>>> 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

所有這些都不能給您一個平均值,因為對於平均值,您需要首先對三個值求和

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

它會更好,如果你盡早作出從字符串到整數這個轉換,也許你正在閱讀從文件信息,此時你也想轉換成字符串存在

您的問題是Python語言使用一種稱為鍵入的計算概念。

假設您有3個蘋果,5個橙子和4個叉子。 如果我告訴您將它們加在一起並給我您有多少水果,則您必須在腦海中查看每個對象,確定是否為水果,然后“轉換”以評估是否為水果。您應該將它們添加到總計中。 有些是可兌換的(例如桔子和蘋果),而有些則不能通過大量工作兌換(例如叉子)。

在這種情況下,即使您將這些變量讀為“ 10”,“ 5”和“ 3”,編譯器也不知道它們是整數(縮寫為“ int”)並將它們視為“字符串”(縮寫為'STR')。 您需要先將它們“類型轉換”為整數,然后編譯器才知道如何執行“ /”。

在這種情況下,您可以使用Python函數'int'來實現。

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

(您無需在末尾轉換3,因為它已被識別為int。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM