Learning Diary: Python
The first in an ongoing series on learning a new coding language.
Swift Playgrounds on the iPad is an easy way to play around with the Apple's newest coding language. The app includes three Learn To Code modules that give you activities to learn syntax as well as basic coding concepts. Swift is fairly easy to pick up and use, although I haven’t built much beyond a program that plays around with math and random numbers. I recommend it, although I need to set it aside and spend some time learning Python for work.
I did code in college some, but I couldn’t really tell you much of what I built. I remember some sorting algorithms, SQL queries, and being incensed at trying to draw a calculator in Java. I don’t think I ever saved anything I made, nor making anything worth saving. My real introduction to coding was when I moved from desktop support to be a Windows Server admin. Powershell was an easy language to learn and has been my go-to language for the last five years. The last two have been focused on PowerCLI. Which is just VMware's extensive module for automation using Powershell.
A friend and I have done some intro courses for people at work, and I always say that the benefit to Powershell is that if you’re ever stuck you can Google your way out of it. If you wanted to do it, so has someone else. I have made some pretty complex stuff, and I’ve made some pretty stupid mistakes. One in particular when trying to do some clever RegEx that failed spectacularly. I’m no expert, but I feel that I am at least a competent coder. I owe most of that to Powershell, and some patient colleagues and bosses. I'm no expert, but I at least feel confident that I can make almost anything in Powershell if you asked me.
Microsoft has done quite a bit of work to make the language available on many different platforms. However, the embrace of Open Source tools at work has meant that newer automation tools require Python. VMware has support for automation in Python, so I can start using it do the same kinds of tasks I am already building in PowerCLI. I'll likely return to Swift at some point when I'm comfortably working in Python every day at work.
I have been playing around with different ways to learn Python. I used Code Academy, just to get a grasp on the syntax. But I started trying to use the language as soon as I could. The first thing I build was a script to import a list of IPs, and then ping them and check if they have DNS entries. It was a bit of a slog. In Powershell, this is a five or ten line script, but in Python, this was around thirty lines. Still easily manageable, mind you, but a bit of a culture shock. I haven’t really done much in the intervening months as I got busy building out patching automation in Power-CLI. But here is that first Python script:
import csv
import socket
import os
import sys
def returnListOfDNSNames( ):
ipArray = []
dnsCheck = []
pingCheck = []
finalArray = ['IP Address', 'DNS Address','Ping Result']
ipFile = 'filepath/IPList.csv'
checkedFile = 'filepath/CheckedIPs.csv'
reader = csv.reader(open(ipFile, 'rU'), dialect='excel')
for row in reader:
ipArray.append(row[0])
for ipAddy in ipArray:
try:
dnsCheck.append(socket.gethostbyaddr(str(ipAddy)))
except:
dnsCheck.append("Not Found")
for ipAddy in ipArray:
response = os.system("ping -c 1 -i 0.5 "+ipAddy)
if response == 0:
pingCheck.append("Up")
else:
pingCheck.append("Down")
i = 0
for ipAddy in ipArray:
thisentry = ([ipArray[i], dnsCheck[i], pingCheck[i]])
finalArray.append(thisentry)
i+=1
with open(checkedFile, 'w') as fout:
writer = csv.writer(fout)
writer.writerows(finalArray)
returnListOfDNSNames()
I picked it back up in earnest a few weeks ago. Doing a quick refresher on syntax, I decided I would just build a little tip calculator in Pythonista on the iPad. It isn’t even close to fancy, but it does work. It even checks to make sure the input is a number.
totalAmount = raw_input('What is the check Total?')
try:
checkAmount = float(totalAmount)
except:
print("As a number, please.")
raise
fifteenPercent = str(checkAmount * .15)
eighteenPercent = str(checkAmount * .18)
twentyPercent = str(checkAmount * .20)
outputString = "Total check amount: " + totalAmount + "\nSuggested tips: \n15%: " + fifteenPercent + "\n18%: " + eighteenPercent + "\n20%: " + twentyPercent + "\nTip your server, you goddamned savage!"
print(outputString)
That’s the code above. There’s still something I want to play around with and improve. The code takes in a string input and converts it to float. It will stop the script and throw an error if it doesn’t get a number. Then that number is multiplied by the percentages and the tips are compiled together in an output string that is formatted via new lines. I need to figure out how to force it to output to two decimals and add the dollar signs to the string outputs. But I was satisfied that it works, and I built it in about a half hour.
My wife suggested I should make one that helps you figure out what to tip to make it a round number. So I removed two of the percentage options and opted for a more detailed breakdown of tipping twenty percent. The script still takes in your check total. I copy and pasted this portion right from the first script. That input is then multiplied for the twenty percent. To get the rounded amount I convert the tip and total added together. I convert that to an integer and add one. I then subtract the tip and check amount added together from that rounded total and add that to the tip to give the amount you need to write in the tip area. Again, everything is combined together in a string, with a friendlier message per her other suggestion.
totalAmount = raw_input('What is the check Total?')
try:
checkAmount = float(totalAmount)
except:
print("As a number, please.")
raise
tipAmount = round((checkAmount * .2),2)
checkTotal = round((tipAmount + checkAmount),2)
roundedTotal = int(checkTotal) + 1
tipTotal = round(((roundedTotal-checkTotal)+tipAmount),2)
outputString = "Tip Cheat Sheet: \nYour bill is: " + str(totalAmount) + "\nYour tip should be at least: " + str(tipAmount) + "\nTo get your check to the nearest dollar, your tip should be: " + str(tipTotal) + "\nMaking your total check: " + str(roundedTotal)
print(outputString)
Again, the script could still use some polishing. This also needs the dollar signs and the enforced two decimal points. I did learn the round feature that holds the floats to two places. However, it still doesn’t show them with two if the number has less than two decimal places. I will probably come back and redo these as I get a little more experience.
I’ll sprinkle these entries in as I make more things in Python as I go. Like the book entries, these are mostly a way for me to cement what I learn. Writing about things and explaining my understanding helps make connections to better retain information. Not to mention that I will have an archive of my progress.
So that’s it, and I really recommend Pythonista for a place to code in iOS. It was easy to use, and I was able to write the scripts laying on the couch. I have been mostly relying on my iPad as my at home computer these days, though no one needs to do any more writing about that. Ever.
Rants and Reviews. Mostly just BS and Affiliate Links.
Follow on Mastodon