首页 > 解决方案 > 如何在不声明不同变量的情况下将这些输入放入函数中

问题描述

我需要优化我的代码,但我不知道该怎么做。我可以将fahr_inputs所有功能整合到一个功能中,但无法使其正常工作

# fahr to cel conversion
def toCelsius (fahr):
    cel = (fahr - 32) * 5/9
    return float(cel)

#dispaly the input and average of fahrenheit and celsius
def displayFahr():
    sum = fahr_input1 + fahr_input2 + fahr_input3 + fahr_input4 + fahr_input5
    average = sum / 5
    print ("Your fahrenheit numbers were: ",fahr_input1, fahr_input2, fahr_input3, fahr_input4, fahr_input5)
    print ("The sum of fahrinheit is : ", sum)
    print ("the average is: ", average)

fahr_input1 = int(input("Please enter a Fahrenheit temperature here: "))
fahr_input2 = int(input("Please enter a Fahrenheit temperature here: "))
fahr_input3 = int(input("Please enter a Fahrenheit temperature here: "))
fahr_input4 = int(input("Please enter a Fahrenheit temperature here: "))
fahr_input5 = int(input("Please enter a Fahrenheit temperature here: "))

displayFahr()




我正在尝试这个,但它不起作用。

def fahr_input ():
    i = 0
    while i < 5:
        input1 = int(input("Please enter a Fahrenheit temperature here: "))
        i + 1
    return input1

标签: python

解决方案


将输入放在一个循环中:

  • 还有其他获得重复输入的选项(例如while-loop),但如果您想要 5 个温度,一个for-loop就足够了。
  • 一个函数应该做一件事,所以有一个单独的函数来计算摄氏度是完美的。
  • temps直接在里面收集list comprehension

代码:

def to_celsius(fahr):
    return float((fahr - 32) * 5/9)

def fahr_input():
    return [int(input('Please enter a Fahrenheit temperature here: ')) for _ in range(5)]

def display_temps():
    temps = fahr_input()
    total = sum(temps)
    average = total / len(temps)

    print('\nYour fahrenheit numbers were', ', '.join(str(x) for x in temps), '°F')
    print(f'The sum of fahrenheit is: {total}°F')
    print(f'the average is: {average:0.0F}°F')
    print(f'You average temp in celsius is: {to_celsius(average):0.02f}°C')

输出disply_fahr()

Please enter a Fahrenheit temperature here:  33
Please enter a Fahrenheit temperature here:  44
Please enter a Fahrenheit temperature here:  55
Please enter a Fahrenheit temperature here:  66
Please enter a Fahrenheit temperature here:  77

Your fahrenheit numbers were 33, 44, 55, 66, 77 °F
The sum of fahrenheit is: 275°F
the average is: 55°F
You average temp in celsius is: 12.78°C

推荐阅读