Python Programming Fundamentals

Life is Short, Use Python

A programming language is really a set of tools that allow us to program at a much higher level than the 0’s and 1’s that exist at the lowest levels of the computer.

Photo by Hitesh Choudhary on Unsplash

Python has many libraries available that make it easy to write some very interesting programs like in Computer Graphics and Graphical User Interfaces. IDE like Wing have debugger support that will understand how Python Program works. You can download from http://wingware.com.

Guess & check pattern or idiom is making a guess as correct solution and storing the guess in a variable. Then you use one or more if statements to check that guess to see if it was correct or not.

Python has elif to solve stair step pattern.

Short Circuit Logic: stoppage of execution of boolean operations if the truth value of expression has been determined already.

In Python, real numbers or floats are represented using eight bytes. Integers, float, bool and strings are immutable in Python. List are not. A list is really a list of references. Unlike strings, individual references within a list can be made to point to new objects using indexed assignment. Every value in python is a object. include integers, float, strings.

In Object Oriented Programming (OOP), type is a class and value is an object. Types in python called classes. Methods are called hooks, syntactic sugar, operators.

Lazy evaluation in python 3: range function returns a generator which generates list of integers as needed.

Instead of returning list of int in python2.

# python3:list(range(4)) -> [0 ,1,2,3]range(4) -> range(0,4)type(range(n)) is <class ‘range’># python2:range(n) is <type ‘list’>range([start,]stop[,increment]) e.g range(10,110,10)

Reading & Writing to a File:

there is a ‘\n’ newline character at the end of each line read from the file.

If you have non-string items to write to a file, they must be converted to strings using the str function. A while loop is used to read records from a file that are composed of multiple lines.

Loop and a half problem: The idea is that you must attempt to read a line from the file before you know whether you are at the end of file or not.

file=open(“name.txt”,”r”)numEntries=0lastName=file.readline().rstrip()while lastName!=” “:numEntrie=numEntries+1lastName=file.readline().rstrip()Other patterns:numEntries=0eof=Falsewhile not eof:lastName=file.readline().rstrip()if lastName!=” “:numEntrie=numEntrie+1else:eof=True

A module is a file containing Python code. The turtle module includes code that helps us draw figures in the sand.

Photo by Anna Wangler on Unsplash

for module import *

e.g from turtle import *

Working with XML Files:

XML stands for eXtensible Markup Language. Computer Scientists devised the XML format so data could be stored in a consistent format.

Being able to write code to extract data from an XML file is a very practical skill.

XML parser:

from xml.dom import minidom

Once you have imported the XML parser you create an Document object by telling minidom to parse the XML file.

xmldoc = minidom.parse(“ flowerandbg.xml”)

Extracting file from XML File

graphicsCommands=xmldoc.getElementsByTagName(“GraphicCommands”)

get just first one:

graphicsCommand = xmldoc. getElementsByTagName(“GraphicsCommands” )[0]

Dictionary: The difference between a list and a dictionary are in the values used to index into them. Within a dictionary there is no ordering of the index values. An index value, called a key when working with dictionaries, can be nearly any value. A dictionary is a list of key, value pairs. Each key is mapped to a value. Keys must be unique, values do not have to be unique in the dictionary.

lst=[]dct={}lst.append(“hello”)lst.append(“world”)dct[“x”]=”299"dct[“y”]=”-45.0"for i in range(len(lst)):print(i,lst[i])for key in dct.keys():print(key,dct[key])

Reading an XML File and Building Parallel lists:

technique of using multiple lists to hold data that are related to each other is called parallel lists.

Scope (LEGB rule) Mark Lutz describes the rules of scope in Python with what he calls the LEGB rule. Memorizing the acronym LEGB will help you memorize the scope rules of Python.

The LEGB rule refers to Local Scope, Enclosing Scope, Global Scope, and Built-in Scope.

The one gotcha with scope is that local scope trumps the enclosing scope, which trumps the global scope, which trumps the built-in scope. Hence the LEGB rule.

The Run-Time Stack

The run-time stack is a data structure that is used by Python to execute programs. Stack is first in/first out data structure.

The run-time stack is a stack of activation records. An activation record is an area of memory that holds a copy of each variable that is defined in the local scope of a function while it is executing.

Each activation record holds a copy of the local variables and parameters that were passed to the function.

To view the activation records on the run-time stack you have to debug your program and set a breakpoint during its execution.

Recursive Functions

Recursives are like inductive proofs. A function is recursive if it calls itself. Recursion works in Python and other languages because of the run-time stack

def factorial(n):if n==0:return 1return n*factorial(n-1)print(factorial(5))

Main Function in Python

Python programmers sometimes write a main function and sometimes do not. However, it is safer to write a main function and most experienced Python programmers will stick to the convention of writing one.

def main():# the if statement that calls main goes last.if __name__=”__main__”:main()

Keyword Arguments:

It turns out that Python allows programmers to call functions using keyword arguments as well. This is not possible in every language, but this is one of the very powerful features of Python

The drawSquare function can be called by writing drawSquare(length=l,turtle=t) using the keyword style of parameter passing.

Dictionary Parameter Passing

a dictionary of keyword/value pairs may be specified as a parameter to a function.A keyword/value dictionary parameter is defined by writing two asterisks in front of the parameter name.

def drawRectangle(turtle, **dimensions):width=0height=10drawFigure(turle,width,90,height,90,width,90,height,90)def main():drawRectangle(t,width=40,height=20)

Event Driven Programming:

Sequential execution is redirected by iteration (i.e. for and while loops) and function calls.

An event-driven application begins as a sequential program executing one statement after another until it enters a never-ending loop. This loop, sometimes called the event dispatch loop looks for an incoming event and then dispatches that event to an event handler.

An event handler is a function that is called to process the event.

An API is a set of classes, or types, and functions that can be useful when implementing a program.

Defining Classes

Classes provide us with a powerful tool for abstraction. Abstraction is when we forget about details of how something works and just concentrate on using it. For example, a file is an abstraction. So is a list. In fact, integers are abstractions, too. Classes provide the definitions for objects.

Python creates a special reference called self that always points to the object we are currently working with. The first method of a class definition is called the constructor and is named __init__. When the constructor is called, Python makes a new self local variable for the __init__ function call.

There are two activation records on the run-time stack.

  1. The first is the activation record for the function that creates the shape by executing the code.
shape = Circle(x,y, radius , edgeWidth=3, \ color=”red”,outline=” gray”)

2. The second activation record is for the __init__ function call (i.e. the call to the constructor). When the program returns from the constructor the top activation record will be popped and the self reference will go away.

Python Hooks : Python looks for the existence of the __str__ method in the class. If this method exists, Python will use it to convert the object to a string representation

The __repr__ method is a Python hook for producing a Python representation of an object

def __repr__(self):return “Rational(“+str(self.num)+”,” +str(self.den)+”)”

Difference between converting to a string and converting to a Python representation?

A string version of an object can be in whatever format the programmer determines is best. But, a Python representation should be in a format so that if the built-in Python function eval is called on it, it will evaluate to its original value.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store