Over the past few posts, we have introduced Python through the use of descriptive statistics and the corresponding libraries such as NumPy/SciPy, Pandas, etc. We will take a hiatus from the data science aspects of Python and focus on the core language itself. Python is fast becoming the go-to language for many computer science programs in North America. This is because of the simplicity of the language and its ability to perform complex tasks in fewer lines of code. These tasks include the descriptive statistics programs highlighted in the series. In this post, we look at a standard Python program and explain each line of code. Here is a past program performing temperature conversions:
response = "Yes" while response == "Yes" or response == "yes" or response == "YES" or response == "Y" or response == "y": fahrenheit = float(input("Enter temperature in Fahrenheit: ")) celsius = 5.0/9.0 * (fahrenheit - 32.0) N = format(celsius, '.2f') print("The equivalent in Celsius is", n) response = input("Do you want to continue?")
This program requires users to enter a value in Fahrenheit and convert the value to Celsius. This is a standard conversion program found in many introductory computer science courses. The first line, which is a variable declaration (response = “Yes”), asks users to type in various versions of the word “yes” to continue or end the program if another character is pressed. The conversion factor is encapsulated in a while loop, which will be explained in the next post. As long as the condition is true, the program will continue to run until the condition is false. The float(input(“Enter temperature in Fahrenheit: “)) gets the temperature in Fahrenheit as a floating-point variable. Then, the program uses this formula, (5.0/9.0) * (fahrenheit- 32.0), to convert to Celsius. When Python finishes converting the Fahrenheit temperature, the program outputs the said temperature into Celsius. The reader is invited to go to this repository and download the program. An interesting modification would be to add the reverse conversion from Celsius to Fahrenheit. Another modification would be to build a user interface with Tkinter and do the Fahrenheit-to-Celsius conversion. Tkinter is the main GUI library for Python. An alternate GUI library is PyQt5, based on the Qt widget library. Qt is written in C++ and can be downloaded for free. To install PyQt5, call pip and enter this line in your command prompt: pip install PyQt5. In many of the examples seen in this series, pip is used to install the main data science/analytics libraries used in Python code and is a convenient way to install modules not included in core Python. In the next post, we will return to this program and focus on the while loop plus look at a program which uses decision statements. Here’s a quick hint: There are no case statements in Python. Find out why in the next post.