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



我目前仍在学习Python的基础知识。我看到其他人把摄氏度转换成华氏度,大约有10行。而我的代码超过40行。我不完全理解"return"的意义,所以我选择了一个简单的项目来理解它。但当我意识到我的代码对于如此简单的东西来说是超长的。感觉我应该做很多困难的项目,因为我在做一些简单的事情时使用了大量的行。

对不起,我是新来的,我渴望通过做项目来学习。任何困难的初学者项目的建议都会有所帮助。谢谢

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()
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
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子句

最新更新