Python

An extensive beginners guide to the world of Python and its applications

Table of Contents

  1. Python
  2. History
  3. Python Structure
  4. Building Main
  5. Print
  6. Variables
  7. Underscore Prefixes
  8. Easy Commands
  9. Operators
  10. Truthiness and Falsiness
  11. Conditionals and Loops
  12. Missing Operators
  13. Functions
  14. Parameters
  15. Assert and Exception Handling
  16. Array Like Structures
  17. Lists
  18. Tuples and Strings
  19. Python and OOP
  20. Creating a Class
  21. Self
  22. Inheritence and Polymorphism
  23. Super
  24. Credit

Python

Taking over the world, rapidly became the number one most popular language analytically


History

Began development in 1989


Python Structure

Python identifies code blocks through common tab structure

Syntax Structures

  1. One of the really nice things about Python Structure is a more regular syntax
  2. The major structures are all very similar, close to the same as english language

Building Main

{
	def main():
		print("Hello World")

	if __name__ = "__main__":
		main()
}
{
	def main():
		print("Hello World!")

	print("This is executed first\n")

	if __name__ = "__main__":
		main()
}

Output: This is executed first Hello World!


Print

print("Hello","this","is","test")

Output: Hello this is test

{
	var1 = 1
	var2 = 2
	var3 = 3
	print(var1, var2, var3)
}

Output: 1 2 3


Variables

Identifiers can start with an uppercase/lowercase letters

All other identifiers start with a lowercase letter


Underscore Prefixes

It is a python convention to prefix _ or __ varibales to be private/protected

'__' triggers a name mangling mechanism


Data Types

Python is Dynamically and Strong typed

Variables will remain strongly typed var1 = 1 is an integer However we can convert this integer to a string print(str(var1))

We can change a variable between different types without classifying the change. Use quotes to change from int to string

{
	var1 = 1
	var1 = "foo"
}

Nuances

When declaring vars you want to create with a default value to represent this data type

{
	myNum = 100 #Integer
	myNum = 100.0 #Float
	myNum = "100" #String
	myNum = 0 #Integer
	myNum = 0.0 #Float
}

Easy Commands

To get basic information from the user we use the input() command/function

Example.

{
	name = input("What is your name? --> ")
}

Be Careful!

Example.

{
	num = input("Choose a number? --> ")
	
}

This is something different in Python3. In Python2 this wasn’t and issue and python used to make the decision on the type of variable for you


Operators

Math Operators

There are a few differences but mostly the same

    • ; addition
    • ; subtraction
    • ; Multiplication
  1. / ; Floating Point Division
  2. // ; Integer Division
  3. ** ; Exponent

Bitwise Operators

Python allows us to manipulate binary as well and gives standard bitwise operators

Operator Description  
& Binary AND Performs a bit by bit AND if the bits are 1 in the same spot  
  Binary OR Performs an OR – 1 in either results in a 1 in the result
^ Binary XOR XOR if there is a 1 in either, but not both there is a 1 in the result  
~ Binary Ones Complement Flip all the bits in the variable  
« Binary Left Shift The left operands value is moved left by the number of bits specified by the right operand  
>> Binary Right Shift The left operands value is moved right by the number of bits specified by the right operand  

Logic Operators

Logic operators are used by the word. Rather than using || or && we type the word ‘or’ and ‘and’

Operator Description Example
and Logical AND True and False = False
or Logical OR True or False = True
not Logical NOT not True = False
is Evaluates to True if the two vars point to the same object obj1 is obj2
is not Evaluates to True if the two variables do NOT point at the same object obj1 is not obj2

Truthiness and Falsiness

False Things

Many things can be considered false. Follow this structure.

True Things

Conditionals and Loops

Standard, however some important differences

However it is missing:

{
def main():
    print("Hello")


    grade = int(input("Enter your grade: "))

    if grade >= 90:
        print("A")
    elif grade >= 80:
        print("B")
    elif grade >= 70:
        print("C")
    elif grade >= 60:
        print("D");
    else:
        print("E")


if __name__ == '__main__':
    main()
}

While Loops

While loops are exactly the same as other languages

{

count = 0
while count < 10:
	print(count)
	count+=1

}

Break and Continue

As Author Matthew Read noted:

Bad programmers speak in absolutes. Good programmers use the clearest solution possible (all other things being equal). Using break and continue frequently makes code hard to follow. But if replacing them makes the code even harder to follow, then that’s a bad change.

Missing Operators

In Python there are no:

These loops don’t work like we have seen them before. In languages such as Java we write


	for (int i=0; i<5; i++){

	}

}

However, in python we write them as:

{

	for i in range(5):
		[code]

}

Functions

Coding with functions and coding with methods are two different things

Here are the main differences

Method

Function

This is important for Python because it can act as many of these. Works with methods and functions

Functions in Python

{

	def <function name>(<param list>):
		<body>

}
{

	def isEven(value):
		if (value % 2 == 0):
			return True
		else:
			return False

}

What if we call a non-numerical value here?

Parameters and Python

Python passes parameters in a similar manner to Java. Primitive and immutable types are passed by value Mutable objects are passed by object reference

Parameters are like every other variable

This is not enforced as syntax Passing a float will not raise an error

{

	def isEven(value:int):
		assert isinstance(value, int)
		print(value)
		if(value % 2 == 0):
			return True
		else:
			return False

}

Python does not allow for overloading

This allows for the ability for Default Parameters

When a param is defined we use the ‘=’ operator

{

	def addNumbers(first, second, third = 0, fourth = 0):
		return first + second + third + fourth
	
	addNumbers(1,2)
	addNumbers(1,2,3)
	addNumbers(1,2,3,4)

}

What are the rules here?

Python has a lot of ways to get around its own rules We can use “Keyword Arguments” Parameters are filled from left to right- How can we skip to the fourth? Default params must go from left to right as well

We can change the order of calling parameters if we know the names

{

	def printinfo( name, age ):
		print "Name: ", name
		print "Age: ", age
		return

	printinfo( age = 52, name = "Billy")

}

Unknown/Arbitrary/Variable-Length Param

{

	def addThemAl(*numbers):
		total = 0

		for value in nums:
			total += value
		return total

	print(addThemAll(1,2,3))
	print(addThemAll(1,2,3,4,5,6,7,8,9))

}

Revisiting Print()

print() is actually more versatile than earlier

sep, file and flush can be set via keyword args

Assert

The assert command is essentially sanity check

Basically a way to force an error in your code if a condition is not met

Exception Handling - Raising an Exception

{

	def isEven(value:int):
		if not isinstance(value, int):
			raise TypeError("value expects integer")
		
		print(value)
		if(value % 2 == 0):
			return True
		else:
			return False

}

Array Like Structures

Python comes with a handful of data structures built into the language

Containers

Lists

Refers to a list collection type. Often called an array because it is similar, however… the list is NOT an array as we might be used to

Java ArrayList is underpinned by an Array, so it isn’t a Python list

Array ArrayList/PythonList
Fixed in Size Managed Array
Managed by programmer object will replace underpinning array
Can’t shrinkand grow, can only be replaced Programmer has no say in size after creation
Memory is managed by the programmer Automatically grows
  Can waste memory

Why is this so important?

  1. Like using ArrayLists in Java there is an inherent give and take to using lists
  2. We’re going to give up control and possibly effeciency
  3. Gain a dynamic feeling data structure that guarantees O(1) runtimes
  4. Since we often don’t care about memory efficiency as much in Python – we’re ok with this trade-off

Creating Lists

To create a list we simply assign a [] to the variable This [] can contain init values if we like:

Construct a list with

{

	myList = list(< iterable >)

}

Lists are Objects

With these methods lists can be used as a Stack or a Queue

Tuples and Strings

Tuples are immutable collection. Once built, they cannot change

Tuples have a key feature - they are HETEROGENEOUS

Strings are what you expect them to be

String Operators

{

	print("Hello"*2)

}

Common Methods

Python and OOP

Differences

There’s a dearth of keywords in Python

Inheritance and Polymorphism is supported

Encapsulation is partially supported. This means that coding python OOP requires a different pattern.

Creating a Class

A class in Python follows our same Python Code Block Pattern that we see in Ifs/Loops/Conditionals. We use the keyword class followed by class name

Class Constructor

In python, we don’t make contructors from the Class Name. To make a constructor we define the __init__ function

{
	class Box:
		def __init__(self):
			pass
}

Basic Anatomy

What do you do with methods?

How do we keep each call unique?

Self

Meaningful tab structure AND required use of self

Confusion and Problems

Each method requires the self parameter first Creation of properties happen in the init method

Instantiation

Destructor

Unlike Java we have a command to explicit delete an object

Creating a destructor

{

	def __del__(self):
		#delete things

}

This gives python greater memory effeciency

Other things we can Overload

Method | Description ——-|——————————— str(self): | This defines a ‘toString’ for the class, making printing objects easier add(self, other): | This overloads the ‘+’ operator for the class len(self): | Overloads a len() function for length abs(self): | Defines how the class responds to absolute value getitem(self, index): | lets your class respond to []

There are dozens of methods you can overload to customize your class

Inheritence and Polymorphism

Inheritence

Basic Inheritence

Class are just ‘passed in’ with inheritence from the parameters list

To accomplish multiple inheritence class Child(Parent1, Parent2, Parent3)

Constructors and Inheritence

Parent constructors must be called

super()

This allows us acces to the first param of the child class (first parent) Purpose:

Constructor is not invokes automatically, and must be invoked explicitly

{

	class A:
		def __init__(self):
			print("A")

	class Child(A):
		def __init__(self):
			print("child")

	ch = Child()

}

In the above function the outcome will only print ‘child’. The A constructor would not be called.

However, we can overcome this with:

{

	class A:
		def __init__(self):
			print("A")

	class Child(A):
		def __init__(self):
			super().__init__()
			print("Child")

ch = Child()

}

Here we would get “A” and “child”

Multiple Inheritence Super

The super() function only reference the first parent in the inheritence When we have multiple inheritence, we have to callout the aprents explicitly and invoke their init

{

	class A:
		def __init__(self):
			print("A")

	class B: 
		def __init__(self):
			print("B")

	class C:
		def __init__(self):
			print("C")

	class Child(A, B, C):
		def __init__(self):
			A.__init__(self)
			B.__init__(self)
			C.__init__(self)
			print("child")

	ch = Child()

}

This will output A, B, C and Child

Python will not build the parent portion of a child class if you do not invoke the init of the parent

Parent Constructon is Required In multiple inheritence just calling super().init() will not build all of the parents

Methods vs Properties

Polymorphism

Essentially change/difference at the same level of inheritence