我正在學習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