November 5, 2015

1129 words 6 mins read

Python - An Introduction

Python - An Introduction

An introduction to Python, based on the material Codecademy, covering: Python Syntax, Strings and Console Output, Conditionals and Control Flow, Functions, Lists and Dictionaries, Lists and Functions, Loops, Advanced Topics in Python, Introduction to Classes, File Input and Output.

Python - An Introduction:

Python Syntax

  • Basic Types: string, int, float, bool

  • Function: print (python 2)

  • Comment: #, """

  • Note: IndentationError: expected an indented block

  • Operators: +,-,*,/,**,%

  • Variables, which store values for later use

  • Data types, such as numbers and booleans

  • Whitespace, which separates statements

  • Comments, which make your code easier to read

  • Arithmetic operations

Strings and Console Output

  • Assignment, Escaping Chars
  • "MONTY"[4]
  • Functions: len(), lower(), upper(), str()
  • Printing String Variables
  • String Concatenation
  • Functions: raw_input()

Conditionals and Control Flow

  • Boolean Comparisons
  • Operators: and, or
  • Operators: not
  • Conditional Statement

PygLatin (Python Pig Latin)

  • Ask the user to input a word in English.
  • Make sure the user entered a valid word.
  • Convert the word from English to Pig Latin.
  • Display the translation result.

You move the first letter of the word to the end and then append the suffix ay. Example: python -> ythonpay

Functions

  • Importing a Module: a module is a file that contains definitions - including variables and functions - that you can use once it is imported
  • Math Standard Library
  • *args : one or more arguments
  • Functions: max, min, abs
  • Function: type

Lists and Dictionaries

  • List : Array
  • Dictionary : Asc. Array (notation {} -> object in JS)

List

  • Methods: append, len
  • Slicing: [index_inclusive:index_exclusive]
  • Methods: index, insert
  • for element in the_list
  • .sort()

Dict

  • Key : Value Pair
  • A dictionary (or list) declaration may break across multiple lines
  • del

List & Dict

  • remove
  • Complex Dict

Note that dictionaries are unordered, meaning that any time you loop through a dictionary, you will go through every key, but you are not guaranteed to get them in any particular order.

As we’ve mentioned, strings are like lists with characters as elements. You can loop through strings the same way you loop through lists!

Lists and Functions

  • Access to List
  • Method: .append(), .pop(), .remove()
  • Function: del

Loops

  • while
  • while, break
  • while, else
  • for in
  • Looping over a Dictionary
  • for index,item in enumerate(list)
  • for a, b in zip(list_a, list_b)
  • for, else

Advanced Topics in Python

List Comprehensions

What if we wanted to generate a list according to some logic - for example, a list of all the even numbers from 0 to 50? List comprehensions are a powerful way to generate lists using the for/in and if keywords.

Lambda - Anonymous Function

Functional programming : means that you’re allowed to pass functions around just as if they were variables or values. The function the lambda creates is an anonymous function. Lambdas are useful when you need a quick function to do some work for you.

When we pass the lambda to filter, filter uses the lambda to determine what to filter, and the second argument (my_list, which is just the numbers 0 – 15) is the list it does the filtering on.

Introduction to Classes

Python is an object-oriented programming language, which means it manipulates programming constructs called objects. You can think of an object as a single data structure that contains data as well as functions; functions of objects are called methods.

  • pass doesn’t do anything, but it’s useful as a placeholder in areas of your code where Python expects an expression
  • __init__() function is required for classes, and it’s used to initialize the objects it creates. __init__() always takes at least one argument, self, that refers to the object being created. You can think of __init__() as the function that “boots up” each object the class creates.
  • We can access attributes of our objects using dot notation

Class Scope

Another important aspect of Python classes is scope. The scope of a variable is the context in which it’s visible to the program.

It may surprise you to learn that not all variables are accessible to all parts of a Python program at all times. When dealing with classes, you can have variables that are available everywhere (global variables), variables that are only available to members of a certain class (member variables), and variables that are only available to particular instances of a class (instance variables).

Classes can be very useful for storing complicated objects with their own methods and variables. Defining a class is much like defining a function, but we use the class keyword instead.

We also use the word object in parentheses because we want our classes to inherit the object class. This means that our class has all the properties of an object, which is the simplest, most basic class. Later we’ll see that classes can inherit other, more complicated classes.

Notes for Variables:

  • To create instance variables, initialize them in the init function
  • When Python sees self.X (object.X) it looks if there’s a property X in your object, and if there is none, it looks at its class.

Inheritance

Inheritance is the process by which one class takes on the attributes and methods of another, and it’s used to express an is-a relationship.

For example, a Panda is a bear, so a Panda class could inherit from a Bear class.

  • Sometimes you’ll want one class that inherits from another to not only take on the methods and attributes of its parent, but to override one or more of them.

  • On the flip side, sometimes you’ll be working with a derived class (or subclass) and realize that you’ve overwritten a method or attribute defined in that class' base class (also called a parent or superclass) that you actually need. Have no fear! You can directly access the attributes or methods of a superclass with Python’s built-in super call.

  • Usually, classes are most useful for holding and accessing abstract collections of data.

  • One useful class method to override is the built-in __repr__() method, which is short for representation; by providing a return value in this method, we can tell Python how to represent an object of our class (for instance, when using a print statement).

File Input and Output

  • Built-in io functions
  • Write, Read
  • During the I/O process, data is buffered: this means that it is held in a temporary location before being written to the file.
  • Python doesn’t flush the buffer—that is, write data to the file - until it’s sure you’re done writing. One way to do this is to close the file. If you write to a file without closing, the data won’t make it to the target file.
  • File objects contain a special pair of built-in methods: __enter__() and __exit__(). The details aren’t important, but what is important is that when a file object’s __exit__() method is invoked, it automatically closes the file. How do we invoke this method? With with and as.
comments powered by Disqus