程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python small instance Celsius Fahrenheit Conversion

編輯:Python

Centigrade <> Fahrenheit Conversion

Today is the official start of self-study Python The first day of , See a topic in the video , Temperature conversion . So the page is paused , I tried to write first . Later, I studied the teacher's program .

I wrote my own program

# Fahrenheit - The conversion of degrees Celsius
print(" Welcome to Fahrenheit - Celsius conversion program ")
print(" Press 1: Fahrenheit → Centigrade ")
print(" Press 2: Centigrade → Fahrenheit ")
temp=input(" Please input the function you want to select :")
guess=int(temp)
if guess==1 :
temp=input(" Please enter the Fahrenheit to convert :")
F=int(temp)
C=(F-32)/1.8
print(" Fahrenheit :"+str(F)+"F = Centigrade :"+str(C)+"℃")
elif guess==2 :
temp=input(" Please enter the degree Celsius to convert :")
C=int(temp)
F=C*1.8+32
print(" Centigrade :"+str(C)+"℃ = Fahrenheit :"+str(F)+"F")
else :
print(" The input does not meet the requirements !")

The idea is simple , It is to judge the function that the user wants to select through the user's input , Then according to different functions , Deal with numbers , The final output .
Verified as follows , choice 1 Function input :80

Verified as follows , choice 2 Function input :80

In fact, my program has to input 1 perhaps 2, If you enter a letter, for example a, It will be converted into guess When integer , Cause the following judgment error , Although it is the wrong format , But did not enter the last :

 print(" The input does not meet the requirements !")

And the final output format has not been uniformly processed

The teacher's program

# Temperature conversion - Teacher version
TempStr = input(" Please enter the temperature value with symbol :")
if TempStr[-1] in ['F','f']:
C = (eval(TempStr[0:-1])-32)/1.8
print(" The temperature after conversion is {:.2f}C".format(C))
elif TempStr[-1] in ['C','c']:
F = 1.8*eval(TempStr[0:-1])+32
print(" The temperature after conversion is {:.2f}F".format(F))
else:
print(" Input format error !")

This program actually requires users to unify their input formats
If you enter Celsius , Then we should use C ending
If you enter Fahrenheit , Then we should use F ending

[-1] The subscript indicates the last element
format() The function matches the previous {:.2f} It means to keep two decimal places for output
Verified as follows

attach :format() Function learning

Python2.6 Start , Added a function to format strings str.format(), It enhances string formatting .
The basic grammar is through {} and : To replace the old % .
format Function can take any number of arguments , Positions can be out of order .


And then there is Dictionary method and list index method , Not to mention


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved