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 .
# 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
# 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
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