为了账号安全,请及时绑定邮箱和手机立即绑定

我是否让我的代码对我自己来说太复杂了?

我是否让我的代码对我自己来说太复杂了?

Go
慕勒3428872 2023-02-22 15:05:36
我目前仍在学习 Python 的基础知识。我看到其他人将摄氏度转换为华氏度,这就像 10 行。虽然我的代码超过 40 行。我没有完全理解'返回'的意义是什么,所以我选择了一个简单的项目来理解它。但是当我意识到我的代码对于如此简单的事情来说太长了。感觉我应该做很多困难的项目,因为我在简单的事情上使用了很多行。对不起,我是新手,我很想通过做项目来学习。困难的初学者项目的任何建议都会有所帮助。谢谢!import timedegree_sign = u'\N{DEGREE SIGN}'def fahrenheit():    degree = int(input('\nHow many degrees is it currently in Fahrenheit?: '))    a = round((degree - 32) * 5/9)        return adef celsius():    degree = int(input('\nHow many dgrees is it currently in Celsius?: '))    a = round((degree * 9/5) + 32)        return aprint("Welcome to my first weather conversion!\n")weather = input('Do you want to convert to Fahrenheit or Celsius (c/f)? \n').lower()if weather == "c":    time.sleep(0.5)    print(f'It is currently {fahrenheit()}{degree_sign}C.')elif weather == "f":    time.sleep(0.5)    print(f'\nIt is currently {celsius()}{degree_sign}F.')else:    while True:        print("\nI'm sorry I don't understand.\n")        weather = input('Do you want to convert to Fahrenheit or Celsius (c/f)? \n').lower()        if weather != "c" and weather != "f":            continue        elif weather == "c":            time.sleep(0.5)            print(f'\nIt is currently {fahrenheit()}{degree_sign}C')            break        elif weather == "f":            time.sleep(0.5)            print(f'\nIt is currently {celsius()}{degree_sign}F.')            break
查看完整描述

1 回答

?
杨__羊羊

TA贡献1943条经验 获得超7个赞

import time


degree_sign = u'\N{DEGREE SIGN}'


def fahrenheit():

    degree = int(input('\nHow many degrees is it currently in Fahrenheit?: '))

    a = round((degree - 32) * 5/9)

    

    return a


def celsius():

    degree = int(input('\nHow many dgrees is it currently in Celsius?: '))

    a = round((degree * 9/5) + 32)

    

    return a


print("Welcome to my first weather conversion!\n")


weather = input('Do you want to convert to Fahrenheit or Celsius (c/f)? \n').lower()

d = {"c": f"{fahrenheit()}{degree_sign}C",

     "f": f"{celsius()}{degree_sign}F"}


if weather == "c":

    time.sleep(0.5)

    print(f'It is currently {fahrenheit()}{degree_sign}C.')


elif weather == "f":

    time.sleep(0.5)

    print(f'\nIt is currently {celsius()}{degree_sign}F.')


else:

    while True:

        print("\nI'm sorry I don't understand.\n")

        weather = input('Do you want to convert to Fahrenheit or Celsius (c/f)? \n').lower()

        try:

            time.sleep(0.5)

            print("It is currently ", d[weather])

        except:

            continue

同样可以修改其他if-else子句


查看完整回答
反对 回复 2023-02-22
  • 1 回答
  • 0 关注
  • 98 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信