How I Spent My Holidays with Python 3.6

Starting the new year right by getting up to speed with Python 3

The holidays can be great where you can take time off, recharge, spend time with the family, watch football, and eat lots of food. However, in-between activities, there’s usually some downtime and rather than do something mind-numbing, I decided to get up to speed with Python 3.

I’ve developed in mostly Python 2 in the past and rather than jump directly into Python 3.7, I decided to take a little step back and start with 3.6 although 3.7 has some interesting new features such as the dataclass() module to declare data classes.

The list below isn’t exhaustive by any means but describes the steps and functions I had to (re)learn.

Print function

The print() function is clearly the most widely known change and has been discussed in depth by many other articles.

Integer division

When dividing integers, the result no longer stays an integer and can dynamically convert to a float.

F-string

Introduced in Python 3.6 are f-strings, an improved way to format strings. Instead of using % and str.format(), you can add an “f” in front of the quote. This will be the preferred method going forward so get used to them!

List comprehension

These aren’t really new in Python 3 but I had to relearn this and do this in a more “Pythonic” way rather than wrapping everything in map, lambda, and filter functions.

Zip and tuples

I didn’t use this much in the past but wanted to understand how to retrieve items from multiple lists in a more elegant way using zip() and tuples rather than traditional for loop iteration.

REPL command line application

One of the standard type of applications that is built when learning a language such as C# is to build a command line application with a menu to execute various functions. I wanted to replicate this with Python.

The result

Below is a REPL command line application that demonstrates the various topics above.

class ConvertFunctions():
def f2c(self, ftemps):
return [(ftemp-32) * 5/9 for ftemp in ftemps]
def m2cm(self, lmeters):
return [meters*100 for meters in lmeters]
def main():
convert = ConvertFunctions()
while True:
op = input("Please select the conversion you wish to perform\n"
"1: Fahrenheit to Celsius\n"
"2: Meters to centimetres\n"
"q: Exit\n")
if op == "1":
strtemps = input("Please enter your fahrenheit temperature(s): ")
ftemps = [float(ftemp) for ftemp in strtemps.split()]
ctemps = convert.f2c(ftemps)
for (ftemp, ctemp) in zip(ftemps, ctemps):
print(f"F:{ftemp:.2f} = C:{ctemp:.2f}")
elif op == "2":
strm = input("Please enter the meters: ")
meters = [int(meter) for meter in strm.split()]
cms = convert.m2cm(meters)
for (m, cm) in zip(meters, cms):
print(f"{m}m = {cm}cm")
elif op.lower() in {'q', 'quit', 'e', 'exit'}:
return
if __name__ == "__main__":
main()
Tags:

Leave a Reply