如何将这些输入放入函数中而不声明不同的变量

2024-06-28 22:01:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要优化我的代码,但我不知道该怎么做。我可以把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


Tags: inputheredefintsumaverageenterplease
2条回答

将输入放入循环中:

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

代码:

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
# 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():
    average = sum(inputLs) / len(inputLs)
    print ("Your fahrenheit numbers were: ", end='')
    for i in inputLs:
        print(i, end=' ')
    print ("\nThe sum of fahrinheit is : ", sum(inputLs))
    print ("the average is: ", average)

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

试试这个

相关问题 更多 >