首页 > 解决方案 > 检查数字并转换华氏度

问题描述

有人能告诉我将两个功能连接在一起的主要规则是什么吗?我有两个功能:一个检查输入是否为数字,另一个将摄氏度转换为华氏度。我如何将它们结合起来?我目前的水平只是想了解如何将它们结合起来,但是任何关于如何使它更 Pythonic 的建议也值得赞赏。谢谢你的建议!

第一的:

def is_number():
    user_input = input ('>>> Please enter a temperature in Celsius: ')
    if (user_input.isdigit()):
        return user_input
    else:
        print ('It is not a number!')
        return is_number()
is_number()

第二:

t = input('>>> Please enter a temperature in Celsius: ')
def Celsius_to_Fahrenheit(t):
    fahrenheit = (t * 1.8) + 32
    print('>>> ' + str(t) + 'C' + ' converted to Fahrenheit is: ' +     str(fahrenheit) + 'F')
Celsius_to_Fahrenheit(float(t))

(可能的重复不是重复的,因为即使那里的问题也不是很清楚,也没有回答我的问题)

标签: python-3.xvalidationconverters

解决方案


这两个函数可以相互独立运行,因此最简单的方法是将代码简单地组合成一个函数:

def Celsius_to_Fahrenheit(t):
    while not t.isdigit():
        print ('It is not a number!')
        t = input ('>>> Please enter a temperature in Celsius: ')
    t = float(t)
    fahrenheit = (t * 1.8) + 32
    print('>>> ' + str(t) + 'C' + ' converted to Fahrenheit is: ' + str(fahrenheit) + 'F')    

t = input ('>>> Please enter a temperature in Celsius: ')
Celsius_to_Fahrenheit(t)

推荐阅读