Shebang / Interpreter Directive
At the very first line of your Python 3 script file which could be named cels_to_fahr.py, enter a shebang (#!) followed by the interpreter directive:
#!/usr/bin/env python3
Input
Leave a space below the shebang/interpreter directive. Then add the following:
celsius = float(input('Enter Celsius Temperature: '))
When the script executes, the user is prompted for a numerical value; a temperature in Celsius. That numerical value is actually converted to a string object by input(), then float() converts the string object to a float object—a decimal value to be applied to the temperature conversion formula. That value is stored in a new celsius variable. If a user entered something erroneous, like a text string, an error message would be returned. (note: code for exception handling, including error messages, could be added.)
Temperature Conversion Formula
Next, add a formula for converting Celsius to Fahrenheit. This is where the value stored in the celsius variable will be converted to Fahrenheit. The converted value will then be stored in a new fahrenheit variable.
fahrenheit = ((celsius * 9) / 5) + 32
Print Result
Finally, the value of fahrenheit is printed. To display the conversion from Celsius to Fahrenheit degrees.
print('Same as', fahrenheit, 'degrees Fahrenheit')
The Python script could be saved as cels_to_fahr.py (see Figure 1).
#!/usr/bin/env python3celsius = float(input('Enter Celsius Temperature: '))
fahrenheit = ((celsius * 9) / 5) + 32
print('Same as', fahrenheit, 'degrees Fahrenheit')
In a Unix terminal emulator, navigate to the directory where the script is stored, then run the script by entering:
python3 cels_to_fahr.py
Alternative Print Line
The print line can be revised to clarify your result (see Figure 2).
print(str(celsius) + '°C' + ' converts to ' + str(fahrenheit) + '°F')
Your Turn
Now use the example to create your own script which converts Fahrenheit to Celsius. Or a script which solves some mathematical problem.