首页 > 解决方案 > 如何将摄氏度转换为华氏温度,然后计算寒冷和温暖的天数,温度取自用户输入

问题描述

我编写了一个程序来从用户那里获取摄氏度输入并将它们转换为华氏温度。我已经完成了大部分程序。

我只是不知道如何让它输出寒冷天和温暖天的出现次数,这取决于用户输入。

# This program will convert 10 entries from Celsius to Farenheit.
print('Lets convert the temperature from the past 10 day from celsius to farenheit')

# Create the open list and loop to prompt the user for all the temperatures in Farenheit.
temps = list()
celsius = int(input("Enter the temperature of everyday of the past 10 days in celsius: "))
while len(temps) != 10:
    temps.append(celsius)
    celsius = int(input("Enter the temperature of everyday of the past 10 days in celsius: "))
print("Okay, the temperature, in celsius of the past 10 days has been: ", temps)

# Using a for-loop, convert each entry by the user into Celsius and print the result.
for far in range(len(temps)):
    temps[far] = (temps[far] * 1.8) + 32
print("The temperatures for everyday of the past week, converted into farenheit, is: ", temps)

def cold():
    if temps[far] < 50:
        print(len(temps[far]))
if cold:
    print(len(temps))

def warm():
    if temps[far] is (>= 50 or < 85):
        print(len(temps[far]))
if warm:
    print(len(temps))

标签: pythonpython-3.x

解决方案


你声明了函数,现在你必须在里面编写逻辑,这将帮助你计算温暖和寒冷天的值。看看下面的代码

def cold(temps):
    counter = 0
    for far in range(len(temps)):
        if temps[far] < 50:
            counter += 1
    return counter

def warm(temps):
    counter = 0
    for far in range(len(temps)):
        if temps[far] >= 50 and temps[far] < 85:
            counter += 1
    return counter
    
# This program will convert 10 entries from celsius to farenheit
print('Lets convert the temperature from the past 10 day from celsius to farenheit')
# Create the open list and loop to prompt the user for all the temperatures in farenheit
temps = list()
celsius = int(input("Enter the temperature of everyday of the past 10 days in celsius: "))
while len(temps) != 10:
    temps.append(celsius)
    celsius = int(input("Enter the temperature of everyday of the past 10 days in celsius: "))
print ("Okay, the temperature, in celsius of the past 10 days has been: ", temps)
# Using a for loop, convert each entry by the user into celsius and print the result
for far in range(len(temps)):
    temps[far] = (temps[far] * 1.8) + 32
print ("The temperatures for everyday of the past week, converted into farenheit, is: ", temps)

print("Cold days: " + str(cold(temps)))
print("Warm days: " + str(warm(temps)))

编辑:

在使用冷和暖功能时,您可以使用 Lamba 功能,如下所示:

print("Cold days: " + str(sum(value < 50 for value in temps)))
print("Warm days: " + str(sum(85 > value >= 50 for value in temps)))

代替

print("Cold days: " + str(cold(temps)))
print("Warm days: " + str(warm(temps)))

现在您可以删除cold()warm()功能。


推荐阅读