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
解决方案
将输入放在一个循环中:
- 还有其他获得重复输入的选项(例如
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
推荐阅读
- apache - 如果匹配两个条件则重定向
- android - 如何在主要活动中使用按钮 onclicklistener 来回收视图项目
- python - 无法为 pyspark 作业启用 INFO 日志记录
- react-native - 为 WEB 设置反应导航无法编译
- php - 在 Laravel 中自动生成员工编号
- mysql - 与 3M 行表的慢连接
- haskell - 更改脚手架时输入“]”上的错误解析错误
- html - bootstrap 4 轮播全屏和自动裁剪
- r - repeat loop in R to compute the cosine of 2.345 correct to 5 decimal places
- ios - 当视频来自数据库时,Html5 视频标签在 ios 中不起作用