Saturday, October 10, 2015

Learning Python

Python is one hell of a programming language. The flexibility with if statements, for example, is amazing. There's so many ways to do things.  More than this, but just to demonstrate the flexibility of being able to say:

if (this or that) or (not this and not that) or (that and not this)
    doSomething()
else:
    doSomethingElseEntirely()


.. is just plain liberating, from a programming point of view. To do that in bash, you'd probably have to do something like:

this = "true" 
that = "true" 
if [[ this == true && that == true]]
then
     do_STUFF()
elif
     [[that == true]] && [[this != true]]
else
     do_MORE_STUFF()
fi 

But than again, BASH will evaluate anything and everything as true, and there's also a /bin/true and /bin/false floating around, so that is not the most reliable code.. So we ought to use arithmetical operations:

#!/bin/bash

false=0
true=1

((false)) && echo false
((true)) && echo true
((!false)) && echo not false
((!true)) && echo not true


Python, however, is much more forgiving when it comes to boolean stuff (but not forgiving at all regarding indentation...) It also makes great use of parameter expansion. How many different ways can you calculate leap years? At least two that I know of. (Some kid in my class was asking for help with this one, so here ya go..)

########################
#!/usr/bin/env python  #
# Leap Year Calculator #
########################

# Declaring error messages here is a lot prettier than everywhere
erNocomp = ("Sorry... that doesn't compute!")
mathIsBroken = ("Something is terribly wrong here! Bailing!")

# Python does not seem to understand unset variables outside of functions so #declare them here:
year = ""
##########
# exit cleanly. got sick of programs crashing upon completion
def exit_0():
    while True:
        try:
            x = input("Press Ctrl + c to quit ")
        except KeyboardInterrupt:
                break
                exit(0)  
  
#

print("""
######################
# Is it a leap year? #
######################

"""
)
# Another library we can use to save some code
import calendar
# 1 will always equal 1; 1 will always return true.

# This is the standard way to validate input. Here we're just saying "till the  

# end of time, or until y = an integer, keep asking for input"
 while 1:
    try:

        y = int(input("Please enter a year...: "))
        break
    except ValueError:("That's not a year!")
    print (erNocomp)
    

#
# This is how to calculate leap years manually, because that was the assignment:

# I feel this is pretty straightforward...
#
# def isLEAP(year):
      return (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)
#
#   if
isLEAP(year):
#       print ("%s is a leapyear." % y)
#   elif not isLEAP(year):
#       print ("Nope")
#
# but its better to trust the calender library that's already meticulously #written.. this is another thing about python that I totally love-- all these #built in functions like isLeap(year) or toRoman(int) to calculate roman numerals

#
# I can pull it off using the math and the library in one if statement,
 

# for the sake of ultimate reliability.
#
######## Note how to combine variables and strings in output:

isOrIs = ("Python or math says %s is a leap year!" % y)
isntAndIsnt = ("Python and math says %s is not a leap year!" % y)
## Prepare for Transdimensional Scenarios
isAndIsnt = ("Python says it's a leapyear, math says not. What universe is this?")
isntAndIs = ("Python says it's not a leapyear, math says it is. What's going on here?")
#########
# Here I'm asking "does the math check out, and does calendar also say it's so?
#

if calendar.isleap(y) or
isLEAP(year):
    print(isOrIs)
    if
calendar.isleap(y) and not isLEAP(year):
        print (isAndIsnt)
    elif not
calendar.isleap(y) and isLEAP(year):
        print (IsntAndIs)
elif not
calendar.isleap(y) and not isLEAP(year):
    print (isntAndIsnt)
else:
    print(mathIsBroken) # just in case the universe ends or whatever
    exit(1)

#
# figured i needed a clean exit func at some point
#
exit_0()

# not a whole lot different than doing
# exit(0)
# just catches the traceback errors


Fun stuff, right? I've decided to post all my python homework scripts on Github, (after the due date, of course!) on the off chance someone learns something from them, but also for own record... Github is very reliable for backing up code and discs tend to fail as per Murphy's law...

That's all for today, folks. BTW does anyone have a CSS script or API for proper python colour coding? That'd be great.

No comments:

Post a Comment