python - 输入为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...")
解决方案
所以你可以清理一些东西。通常最好避免使用全局变量。您的函数不需要知道摄氏度变量,它只需要返回一个值,您可以在主代码中将该返回值分配给摄氏度。
您还可以让您的函数检查温度值是否为 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...")
推荐阅读
- nuxt.js - Contentful API 结合 nuxt 和 vite 引发运行时错误
- visual-studio-code - PHP 智能感知,无需编写
我最近从 Atom 切换到 VScode,并且正在寻找我无法找到的功能。
在 Atom 中,如果我开始
fore
在 php 文件中编写(开始一个 foreach 循环),它建议使用 foreach,然后按 Enter 输出:<?php foreach ($variable as $key => $value): ?>
- google-api - 无法使用 Google Drive API 创建管理器权限
- python - 确定文件是否已从 windows 写入 linux
- python - 使用 iloc 创建新 col 和设置值时出错
- reactive-programming - 哪个更适合这种情况。zipWith 还是 .map?
- firefox - GeckoDriver 即使在 Chrome 中启动与 Firefox 浏览器的连接时也不会忽略网页的 JS 错误,Edge 工作正常
- php - 如何在单个帖子页面(wordpress)中添加“function”和“add_action”php?
- android - 转换 SQL 查询以从中删除窗口函数
- javascript - 如何将表达式树 (AST) 转换为 DOM 树 (XML)