首页 > 解决方案 > 输入为0时执行重载功能

问题描述

我试图做一个程序,用户可以输入华氏温度,它以摄氏度计算,只有在温度合适时才退出循环。

程序正在运行,但最后一点是如果用户输入 0,则创建一个重载函数。如果用户输入 0,程序应该创建一个随机数并将其发送回while循环。我无法让它工作或弄清楚在哪里放置过载。这是现在看起来的代码:

import random
celsius = 0

def fahr_to_cel(temp):
    # function that receives value in fahrenheit and returns value in celsius
    global celsius
    celsius = round((temp - 32) * 5/9, 2)
    return celsius

# welcome message to user
print ("Hello and welcome to your personal sauna.")

while celsius < 82 or celsius > 87:
  try:
    fahr_to_cel(int(input("Please write a desired temperature in fahrenheit: ")))
    if celsius < 82:
      print (str(celsius) + " degrees celsius, that is probably a bit too cold")
    elif celsius > 87:
      print (str(celsius) + " degrees celsius, that is probably a bit too hot")
  except:
    print ("Something went wrong, you might have written letters!")

# output the actual temperature in celsius
print ("Your temperature is now " + str(celsius) + " degrees celsius and perfect for a good sauna!")
input("Press any key to continue...")

标签: pythonoverloading

解决方案


所以你可以清理一些东西。通常最好避免使用全局变量。您的函数不需要知道摄氏度变量,它只需要返回一个值,您可以在主代码中将该返回值分配给摄氏度。

您还可以让您的函数检查温度值是否为 0,如果是,则生成 100 到 200 之间的随机温度,例如。

我在这里也使用了无限循环,中断条件在 else 语句中,因为如果值不小于 82 且不大于 87,那么它就是正确的温度

import random


def fahr_to_cel(temp):
    # function that receives value in fahrenheit and returns value in celsius
    if temp == 0:
        temp = random.randint(100, 200)
    return round((temp - 32) * 5 / 9, 2)


# welcome message to user
print("Hello and welcome to your personal sauna.")
while True:
    try:
        celsius = fahr_to_cel(int(input("Please write a desired temperature in fahrenheit: ")))
        if celsius < 82:
            print(str(celsius) + " degrees celsius, that is probably a bit too cold")
        elif celsius > 87:
            print(str(celsius) + " degrees celsius, that is probably a bit too hot")
        else:
            break
    except:
        print("Something went wrong, you might have written letters!")

# output the actual temperature in celsius
print("Your temperature is now " + str(celsius) + " degrees celsius and perfect for a good sauna!")
input("Press any key to continue...")

推荐阅读