1.6. Python programs#
We have used the console for a while now and you may start to notice that it has some shortcomings. For example, if you want to change the value of a variable, any other commands that use that variable will need to be entered again. This is where programs are useful. A program is a file or a collection of files that contain Python commands that can be run.
We are going to use Spyder to write our programs. In Spyder create a new file:
Click on File > New file…. This will create a new file with the file name untitled0.py (Python programs have the file extension .py).
Click on File > Save as…, navigate to the folder where you want to save the program (e.g., Documents/Programming_skills/) and give it the filename 1_Python_basics.py.
We are going to write a simple program that converts an angle expressed in degrees to radians. In your 1_Python_basics.py
file enter the following code (you can leave the text at the top of the file).
pi = 3.1415927;
angle_in_degrees = 45;
angle_in_radians = angle_in_degrees * pi / 180;
The first three lines should be familiar to you as we have declared the two variables pi
and angle_in_degrees
which are used to calculate the value of angle_in_radians
. Run the program by clicking on the play button or by pressing the F5 key. Not a lot happens apart from the text runfile(...)
appearing in the console. We need to output the value of the angle in radians so add the following command to your program.
print(angle_in_radians)
Running your program now outputs the following to the console.
0.785398175
1.6.1. Exercise#
Create a new Python file called 1_Python_basics_exercises.py
and save it to your OneDrive folder. Use it to answer the remaining exercises in this chapter.
Write a program similar to Exercise 1.2 except that it converts a temperature from degrees Fahrenheit to degrees Centigrade and outputs the result to the console.
Use your program to convert the following to degrees Centigrade:
100 \(^\circ\)F
0 \(^\circ\)F