![](/img/trans.png)
[英]Need to find min, max, range, and average in a list of user inputs but I can't use the built in functions to find them
[英]How do i use user input floats and find the average, min, max and range in Python
我知道如何用整數來做到這一點,但我對如何從用戶那里獲取浮點數並找到平均值、最小值、最大值和范圍感到困惑。 我不斷收到一條錯誤消息:TypeError: 'float' object is not iterable。
到目前為止,這是我的最小代碼,我知道它不起作用,但只是尋找有關如何獲取浮點用戶數並找到平均值、最小值、最大值和范圍的建議。 謝謝!
import statistics
def main ():
userNum= float(input("Give me 5 numbers "))
average = statistics.mean(userNum)
print("The average of the numbers given is: ", average)
print(max(userNum))
print(min(userNum))
main()
您不能直接將輸入轉換為浮點數。 首先,您需要拆分用戶輸入。 如果它是這樣的:
"3.4, 5.6, 8.7, 6.4, 9.8"
然后像這樣嘗試:
import statistics
def main():
userNum = float(input("Give me 5 numbers "))
userNum = [float(x) for x in userNum.split(", ")]
average = statistics.mean(userNum)
print("The average of the numbers given is: ", average)
print(max(userNum))
print(min(userNum))
main()
首先,您需要在調用main()
函數時取消縮進,我的意思是代碼的最后一行。
這是我沒有statistics
模塊的解決方案,因為我不太熟悉它。
def main():
tries = 0
while True:
tries += 1
print(f'try number {tries}')
user_num = float(input('Enter five floating points: '))
if tries == 1:
sum1 = user_num
elif tries == 2:
sum2 = user_num
elif tries == 3:
sum3 = user_num
elif tries == 4:
sum4 = user_num
elif tries == 5:
sum5 = user_num
sums = sum1 + sum2 + sum3 + sum4 + sum5
print(f'sum is {sums}')
average = sums / tries
print(f'The average of the numbers given is: {average}')
all_numbers = [sum1, sum2, sum3, sum4, sum5]
all_numbers.sort()
print(f'sorted: {all_numbers}')
print(f'the minimum number is {all_numbers[-1]}')
print(f'the maximum number is {all_numbers[0]}')
break
main()
我希望你喜歡它。
玩得開心 :)
更新:這是我找到的解決方案。 也許它太簡單了,但它對我有用。
def main ():
import statistics
userNum= input("Enter 5 floating point values seperated by a space")
x=[float(x) for x in userNum.split(" ")] #converts string to floating point
values
average = statistics.mean(x) #find the average value entered
print("The average of the numbers given is: ", average) #print the average
number entered
print (min(x), "The min number given") #print the min number entered
print (max(x), "The max number given") #print the max number entered
diff= max(x) - min(x) #calculate the range
print (diff, "This is the range of numbers given") #print the range
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.