«

»

Dec 10 2012

Print this Post

Multiple operations using a single input

Last time we talked about the basics of Python 3 programing language. Using the basic principles we learned about variables, we will create a unit conversion program for weight.

The first step is to find all the conversion factors from a reference material. In ancient times, most mathematicians and computer scientists used unit conversion tables. But with the advancement in computer science and electronics, you can use search it online. (Google it!) Make sure you get the background information (such as these conversion factors) from an accurate source. Even with a well written program, the output will be quite useless if you use erroneous data.

It is important to use meaningful variable names.


Write down the necessary steps required for taking an user input, processing (conversions) and printing a meaningful output. There have been disasters in the scientific community as a result of inadequate communication. For example, if a group of scientists calculate the distance in km and the other group in miles, it would be a nightmare if they don’t communicate to each other about the differences in calculations. Since we will be converting a kilogram input in to outputs with several different units, we will make a print statement for each conversion with information about the conversion.

Study the following code and try identify the key elements using the comments as aids. You will see that there are more to the code than what just mention above.

#
# This program will prompt the user for a weight in kg and format the input and output
# The program will convert the value into different units
# It will print a statement on the terminal (Python GUI/CMD)
# To run type, YourFileName.py on the terminal
#
kg = float (input("Please enter a value in kilograms: "))
#
# Conversion factors
#
mton_factor = 0.001
lbs_factor = 2.20462
oz_factor = 35.274
g_factor = 1000
mg_factor = 1000000
#
# Conversion
#
ton = kg * mton_factor
lbs = kg * lbs_factor
oz = kg * oz_factor
g = kg * g_factor
mg = kg * mg_factor
#
# Print statements: prompt, format specifier to 2 decimals
# Results from the factors were passed to the print statements
#
print ("\nYou entered %.2f" % kg, "in kilograms...")
print ("It is %.2f" % ton, "in metric tons !")
print ("It is %.2f" % lbs, "in pounds !")
print ("It is %.2f" % oz, "in ounces !")
print ("It is %.2f" % g, "in grams !")
print ("It is %.2f" % mg, "in milligrams !")
#
# End of Program
#

Do not pick out of a hat

If you are a Computer Science student and/or a Professional, it is important to use meaningful variable names. For example, kg is a meaningful variable name for the user input of this program because we take a value in kilograms (kg). However, if you were to take the temperature in degree Celsius, kg as a variable name would be very unprofessional. Instead, you could use, temp, temperature, celsius, deg, deg_cel, degCelsius, etc. It is also the norm not to pick variable names that would start with a capital letter. Other conditions of the language itself should be considered as well. (Rules for creating variable names will varies depend on the programming language.)

What is a float () ?

In programming languages (C#, Java, Python, etc) float() function is a built in command to force a value into a floating point number. The line 7 of the above program cast the user input into a floating point number. If you were to perform a mathematical calculation using just an input without casting it into a floating point number, the Python program will take it as a string and crash the program with a string math error.

The the best possible way to avoid this undesirable outcome is to try to process the input as a floating point number. However, this will not prevent the program from crashing in an event the user enter a non numeric value. In a later tutorial we will learn how to handle known and unknown errors without crashing the program.

Avoiding magic numbers

Magic numbers are values that are poorly documented that often appear on a program several times. Often these values are consents or values that rarely change throughout the program. In our program above, Conversion factors section (lines 11 to 15) is creating variables for conversion units. These units then can be used in the program over and over the same way the variable, kg is used for user input. Another advantage of creating this type of variables in a single section of your program is if you were to change a factor for the whole program, you have to only do it at this section.

From Microsoft to Google and millions of other software development companies encourage all their engineers and programmers to avoid magic numbers. This is because if a large scale program such as Microsoft Excel to have an error in the code, it would be a nightmare to change all the consistent values over thousands of lines of code. By creating variables, even a large scale software can be modified in a reasonable amount of time. In software engineering it is always prone to have errors even if a program is written by “experts”.

Complex print statements

An armature programmer may choose to use simple print() statements to deliver the output of a program. When a program manipulates and creates several different outputs, it is better to display the results with a meaningful message attached to it. The only way to accomplish this would be to use complex print statements with several different elements. In our program, the following print statements;

#
# NOTICE: PULLED OUT OF THE ORIGINAL CODE ABOVE
#         Missing code lines above and this is NOT a program!
#
print ("\nYou entered %.2f" % kg, "in kilograms...")
print ("It is %.2f" % ton, "in metric tons !")
print ("It is %.2f" % lbs, "in pounds !")
print ("It is %.2f" % oz, "in ounces !")
print ("It is %.2f" % g, "in grams !")
print ("It is %.2f" % mg, "in milligrams !")
#
# END of code pull
#

This will generate the following output in the terminal (CMD).

The key elements in the six print statements can be broken down into several elements. The text statement, the format specifier(s) and the calling of the variable. The text statement is always written between quotes (“…”) in Python 3. When a text statement is followed by a variable call, there are two ways to code it depend on the situation. If the variable call is immediately followed after the text statement, then there will be a comma (,) right after the end of the print quotes. For example, print("It is", ton, "in metric tons !"). However No comma right after the text statement will be entered, if a format specifier is used. Instead, the format specifier is called in before/after (depends) the variable call immediately after the end of text statement; print ("It is %.2f" % ton, "in metric tons !"). But in both scenarios you must use a comma right after the variable is called in for printing (ton,). The %.2f is the format condition given to rounding of decimal places. The ” % ” is the beginning of the format specifier and the dot ( . ) indicate the condition (in this case the decimals) with “2f” it forces the values to be rounded up to exactly two decimal places. To call in this format specifier, a ” % ” is typed in immediately before the variable call.

Another format specifier we used is \n. In here, print ("\nYou entered %.2f" % kg, "in kilograms...") \n does the same operation as a blank print statement, print(). Both \n and blank print() will create a new blank line between the format specifier and the next print statement. However, a good programmer always use the shortest code for a blank line.

What else did you notice? Hay, the format specifiers are within the print text statements itself! In Python 3, the format specifiers will be always defined (or predefined) within a print text statement. The formatting is required for styling. Therefore it is a built in feature to automatically identify format specifiers within a print text statement. The statement print("I am from... Calgary, Alberta, Canada") can be printed on three separate lines and tabs by modifying the code to; print("I am from...\n\tCalgary,\n\tAlberta,\n\tCanada") instead of using three separate statements.

That’s it for today! Happy coding in this holiday season. May the algorithms be with you!

Permanent link to this article: http://sanuja.com/blog/multiple-operations-using-a-single-input