我正在学习Python(2.7)并测试我迄今为止学到的东西,我写了一个温度转换器,将摄氏温度转换为华氏温度,我想知道我的代码是否可以写得更好,以便更快或更加Pythonic。有人能告诉我是否有if __name__ == '__main__': main()
(出于好奇)的实际名称?学习Python,有没有更好的方式来写这个?
from sys import argv, exit # import argv and exit functions
def to_f(c): # Convert celsius to ferinheight
temp = (c * 9/5) + 32
return temp
def to_c(f): # Convert ferinheight to celsius
temp = (f - 32) * 5/9
return temp
def main():
args = argv[1:] # Creates an argument list omitting the omitting the [0] element
if len(argv) < 2: exit(1) # If less than two arguments
if args[0] == '-f': # If the first argument is -f
print args[1], 'ferinheight is', str(to_c(int(args[1]))), 'celsius'
elif args[0] == '-c': # If the first argument is -c
print args[1], 'celsius is', str(to_f(int(args[1]))), 'ferinheight'
else: exit(1)
if __name__ == '__main__':
main()
你先生刚刚赢得了你自己的答案,谢谢!感谢Fahrenheit拼写修正,我在拼写和Chrome,Google,Komodo Edit和截止日期之后(Chrome高级拼写检查器扩展)都会告诉我这是拼错的,但他们都不知道我想要的是什么词拼写。 – 2010-07-11 20:21:12
你能解释一下'sys.exit(convert(sys.argv [1:]))'的作用吗?它会在它退出之前这样做,因为没有别的东西可以执行了? – 2010-07-11 20:28:45
convert()需要一个参数列表,我使用sys.argv [1:]提供。 convert()然后返回一个状态码,将其传递给sys.exit,该状态码用该状态码退出进程。 – 2010-07-11 20:34:38