Editorial Workflows

Python Examples

public workflow

Install Workflow...

This workflow contains at least one Python script. Only use it if you trust the person who shared this with you, and if you know exactly what it does.

I understand, install the workflow!

This is a workflow for Editorial, a Markdown and plain text editor for iOS. To download it, you need to view this page on a device that has the app installed.

Description: This workflow contains various example python scripts for learning python. The categories are:


To run an example, drag it above the stop action (not the entire group)

By Tutorial Doctor

Shared by: Tutorial Doctor

Comments: Comment Feed (RSS)

There are no comments yet.

+ Add Comment

Workflow Preview
View Tutorial? ?
Would you like to view the programming tutorial?
Button 1
Output Value
Button 2
Output Value
Button 3
(don't show)
Output Value
Show Cancel Button
Tutorial ?
Run the block if
  • is Equal to
  • is Not Equal to
  • Contains
  • Doesn't Contain
  • Matches Regular Expression
Help ?
Run the block if
  • is Equal to
  • is Not Equal to
  • Contains
  • Doesn't Contain
  • Matches Regular Expression
Markdown Help ?
Variable Name
Title: "Computer Programming Made **Actually** Simple" A computer program is a recipe for a computer. It looks something like... import editor import console import os import re import sys import codecs import workflow from StringIO import StringIO theme = editor.get_theme() workflow.set_variable('CSS', workflow.get_variable('CSS Dark' if theme == 'Dark' else 'CSS Light')) p = editor.get_path() term = workflow.get_variable('Search Term') pattern = re.compile(re.escape(term), flags=re.IGNORECASE) from urllib import quote dir = os.path.split(p)[0] valid_extensions = set(['.txt', '.md', '.markd', '.text', '.mdown', '.taskpaper']) html = StringIO() match_count = 0 for w in os.walk(dir): dir_path = w[0] filenames = w[2] for name in filenames: full_path = os.path.join(dir_path, name) ext = os.path.splitext(full_path)[1] if ext.lower() not in valid_extensions: continue found_snippets = [] i = 0 try: with codecs.open(full_path, 'r', 'utf-8') as f: for line in f: for match in re.finditer(pattern, line): start = max(0, match.start(0) - 100) end = min(len(line)-1, match.end(0) + 100) snippet = (line[start:match.start(0)], match.group(0), line[match.end(0):end], match.start(0) + i, match.end(0) + i) found_snippets.append(snippet) i += len(line) except UnicodeDecodeError, e: pass if len(found_snippets) > 0: match_count += 1 root, rel_path = editor.to_relative_path(full_path) ed_url = 'editorial://open/' + quote(rel_path.encode('utf-8')) + '?root=' + root html.write('<h2><a href="' + ed_url + '">' + name + '</a></h2>') for snippet in found_snippets: start = snippet[3] end = snippet[4] select_url = 'editorial://open/' + quote(rel_path.encode('utf-8')) + '?root=' + root select_url += '&selection=' + str(start) + '-' + str(end) html.write('<a class="result-box" href="' + select_url + '">' + snippet[0] + '<span class="highlight">' + snippet[1] + '</span>' + snippet[2] + '</a>') if match_count == 0: html.write('<p>No matches found.</p>') workflow.set_output(html.getvalue()) The computer reads the recipe and you get a game like **Angry Birds**, computer software like **Microsoft Office**, or a website like **Youtube**. # USER A person who uses a program is called a **user**. # DEVELOPER A person who creates a program is called a **developer**. # VARIABLES Recipes have various ingredents and various directions for using the ingedients. The various ingredients of a computer program are called **variables**. Variables are names like **nouns**. Your recipe might require an *apple* and some *sugar* and a *blender*. These would be variables in your program. # STATEMENTS The various directions are called **statements**. Computer are not naturally smart. If I told a computer to cut an apple, I would have to tell it how, step-by-step. To save time, I would create something called a *function*. # FUNCTION A **function** is a **group of statements**. Some people see them as machines, because functions do something to variables. They are usually named like **verbs**. For instance, if I put a strawberry into a blender function, the blender would blend and return a strawberry smoothie. So, I could type Blend() and the computer would know what to do. Let's see an example //VARIABLES var salt; var water; var bowl; var temperature; var pot; //FUNCTIONS function measure() { some statements here } function pour() { some statements here } function boil() { some statements here } function stir() { some statements here } function setTemperature() { some statements here } My variables are: - Salt - Water - Bowl - Pot - Temperature Even though a bowl and temperature are not food items, they are variables, because they are nouns. My functions are: - Measure() - Pour() - Boil() - Stir() - SetTemperature() The Measure() function measures something. Looking at our ingredients/variables, we might measure water. We could measure temperature also (although you don't measure temperature with a measuring cup). The Pour() function would pour something. We could pour water. We could pour water into a pot or into a bowl. The Boil() function would boil something. If we put water into a boil function, it would be boiled. We could also boil milk. The Stir() function stirs something. We could stir water in a bowl. The SetTemperature() function would set a temperature. If we had a stove variable, we could set the temperature of the stove. As you can see, some functions can be used on many variables. I can bake a cake, or I can bake a pie. I can boil water or milk. In computer programming, the things that can be **substituted** in and out of a function are called **arguments/parameters**. They work just like the arguments in Algebra: f(x) = 2x + 1 f(1) = 2*1 + 1 f(2) = 2*2 + 1 Let's say you wanted to make a game. First you would create all of your characters and game objects as variables. Next you would create some functions for your characters and game objects. You might create a function called Jump(), so that when you type Jump(), an animatioin would play and start moving the character in the up direction. Or, you might create a function called Run() which would move the character to the left or right while playing an animation. Perhaps Apple inc. uses functions names Shutdown() and Startup() and OpenAppStore() in their coding of IOS. Perhaps! # ALGORITHMS When people write recipes, there is a **certain order** in which you are supposed to cook or prepare the food or supplies. In computer programming, it is called an **algorithm**. For instance, you might tell the computer to gather all of the supplies first, and then you tell it to do stuff with those supplies. One main reason games or apps lag is because they have bad algorithms. For example, I might tell the computer to Cut() and Butter() the bread after I tell it to Eat() the bread. The computer cannot cut and butter bread that it has already eaten, so you get an **error**. Although a bad algorithm might not give you an error, it could take too much time, when there is an easier way. I once saw a computer program that was a page long, and all it did was make an object follow the mouse cursor. I did the same thing with one line of code, and it was faster! # DEBUGGING Say that you finish your game or app and run it, and nothing works! That means that somewhere, there is a mistake in your code. The process of **correcting errors** in your code is called **debugging**. # SOURCE CODE In compter programming, your **entire recipe** with its ingredients and instructions is called your **source code**. A lot of programmers keep their source code a secret, like a secret recipe. Programs that are not secret are called **Open Source** programs. # SYNTAX There are different types of langauges you can write in, and each language has its own grammar rules. The **grammar rules** of computer programming is called the **syntax** of the language. If your syntax is not correct, the computer will not understand what you are saying. In some languages they use a simicolon to end a statement, just like we use a period to end a sentence. Different syntax. # PROGRAMMING STYLE Your programming style is the way in which the developer **styles their source code**, usually according to a set of rules or standards. Just as there are various styles for writing poems , there are different styles to writing programs. Some rules a style might follow are: - Indent all function code - capitalize the first letter in a function name - white-space between statements. By default, the Python programming language forces you to indent function code (for style purposes). Styles are sometimes chosen for readability (by other developers). # IDE If you want to write a computer program, you need something to **write it in**. You use a word processor to write essays, and you write programs in an IDE (**Integrated Development Environment**). It is an environment that you develop in! Develop what? Develope programs -- those super tasty code recipe masterpieces! **XCODE** is Apple's IDE. You make iPhone apps in XCODE and Android apps in **Eclipse**. # MEMORY Computers, much like humans, can only remember so much at one time. Anything stored in the memory of the computer can be accessed quicker than something that isn't. Most data/directions go into the **RAM** (Random Access Memory) part of the computer brain. Another place information is stored is in the **ROM** (Read-only memory). I am no nerosurgeon so I will stop there. All you need to know is that you shouldn't overload the computer with instructions when it can only remember so much. I wrote a program that made my computer calculate the ccurrent Year, Month, Day, Hour, Minute, and Second 20,000 times fast. My computer fan started humming # FLOW CONTROL No one wries a recipe that says: *" Do this, do this, do this, do this, do that, done!" If you write intructions back to back like that, you are not being specific, and things could go wrong."* For example, You tell the computer to bake the cake, then you tell it to stop baking, then you tell it to take the cake out of the oven, then you tell it to let the cake cook. Finally you tell it to eat. However, how long is it supposed to bake? And how can you tell when it is ready? How long to let it cool? What temperature should it be when it is cool? Your recipe has to have a flow. It has to have control flow. # CONDITIONAL STATMENTS The way you **create flow** in computer programming is by using **conditional statments**. A conditional statement is a statment like: *"If the temperature is 100 degrees, take the cake out of the oven." Otherwise, if it is 90 degrees, leave it in the oven. If it is anything else.."* The way you say **if** in computer programming is with the "if" keyword. the way you say *otherwise* is **else if**." The way you say *if anything else* is **else**. Here is an example program in the Python language that aturally works. In Python, "def" means "define a functiion." Temperature is the variable: def BakeCake(): print "Baking the cake Sire..." def TakeCakeOutOfOven(): print "Taking the cake out of the oven Sire..." def LeaveCakeInOven(): print "Leaving the cake in the oven Sire..." def EatTheCake(): print "Eating his delcious scrumptious cake..." def BarkLikeAStarvingDog(): print "WOOF! WOOF! WOOF!!" temperature = 0 if (temperature==100): TakeCakeOutofOven() elif (temperature==90): LeaveCakeInOven() else: BarkLikeAStarvingDog() raw_input("Press Enter to leave this terrible place...") # LOOPS A **loop** is how you make a computer **repeat** an instruction. You could make it repeat a whole function or just a single statement. There are two main types of loop statements. There is the **while loop** and the **for loop**. ## While Loop A while loop is like saying, "**As long as**.." Short for "as long is" is *while.* If you have a temperature variable, temperature can chance. You might say, "While the temperature is 90 degrees, keep the cake in the oven." As long as the temperature is 90 we will keep it in the oven. ## For Loop A for loop is like saying, "**Until**..." The computer will do something until something else happens. If we have a cake variable and a temperature variable, we could Bake() the cake until the temperature is 100 degrees. Once the cake is 100 degrees, we stop baking it. # DATA TYPES An apple is a type of fruit. A pecan is type of nut. A male is a type of person. When you give a **variable** a **type** in computer programming, you are giving it a **data type**. The basic types of variables in a computer program are the: - string - integer - float - character - boolean - array ## String A string is a string of characters. Strings are like **words** in English. Strings are usually put in double or single quotes: - "This is a string" - 'This is a string also' The spaces between words count as a character too! ## Integer An **Integer** is a **number** - 1 - 345 - 9043 ## Float A **Float** is a number also, but it is a **number with decimals** - 1.5 - 345.67 - 1924.034 ## Character A **character** is a **single letter number symbol**: - "a" - "7" - "@" ## Boolean A Boolean is like a **switch**. You can turn a variable ON or you can turn a variable OFF. ON = TRUE in computer programming. OFF = FALSE. If you had a variable named *switch*, you could turn it OFF/FALSE. The on/off switches in your settings make use of Boolean variables, I would suppose. - light_on = True - door_open = False ## Array/List An **array** is a **list** of items. If you had a variable called *basketOfFruit*, inside of it you could put an array of fruit. An array is a variable that can contain other variables or data types. ## Tuple A **tuple** is a list that cannot be changed (it is **immutable**). ## Dictionary/Associative Array A **dictionary** is an **array** that pairs each **variable with a key**. The only way you can access each variable is by using the appropriate key. They can be used to store properties of values. # CLASSES What if you wanted to make your own data types? **Custom data types** are made using classes. Classes are used to classify variables. Classes allow you to give your variables **characteristics**. For example, all humans share certain characteristics. So, you could create a human calss and put some male and female variables in it. You can also create some functions for your human class like, Walk(), Run(), Speak(), Think(), etc. # SUPERCLASSES AND SUBCLASSES Sometimes classes can be part of other classes - HumanClasss - Female Class - Woman Class A woman is part of the female class, and a female is part of the human class. If I had an object named *Sarah*, she would be a part of the woman class and inherit traits from the female and human classes. The female is the superclass of the woman class, and the woman class is the subclass of the female class. - FruitClass - AppleClass - GrannySmithClass An apple is a type of fruit. A grannysmith is a type of apple. The superclass of the apple class is? the subclass of the fruit class is? # METHOD A **function** that is **in a class** is called a method. Classes should be named like types of things. An apple is a type of fruit, so it would be in a fruit class. Another way to name a class is as a subject. In math class you learn math. Methods in a math class might be Add() Subtract() Divide(), and Multiply(). Of course, you would have integer and float variables in it. # OBJECT Once you have given a variable characteristics it then becomes an object. They call an object an **instance** of a class because it contains all of the properties or characteristics of the class. Now your human variable(object) can either Walk(), Talk(), Speak(), or Think() when you want it to. You might type: - human.Speak() Now your human variable can do the Speak() function. Programing that uses objects is called Object Oriented Programming (OOP). # Instance/Member Variable A **variable** defined **inside of a class** is called an **instance variable**. Also called a **member variable** An apple is part of the fruit class, in which there are variables like taste, color, type etc. Taste, color, and type are instance variables. They are variables that belong to the fruit class. # MODULES/LIBRARIES Why bake bread from scratch when you can buy a loaf? **Collections of classes, functions and variables** made by other peope that you can use in your own program recipe are called modules/libraries. # INTERACTIVITY Interativity is a way for **users** like you and me to **interact with** and change the vode of a **program** without having to open the code in an IDE and change variables or functions. For example, when you select a number in the timer section of the clock app on your iPhone, you are actually changing the value of a ariable in the code. Let's say the name of that variable is *timer*. When you tap the "Start" button, you are starting a function (remember that functions do something to variables). If I had to guess, the start function counts down from the timer number. All you had to do was scroll and tap to manipulte the code. You *interacted* with the program. # EVENTS, EVENT LISTENERS, EVENT HANDLERS When you **press a key** on your keyboard, that is an event. When you **click a button** on your mouse or **swipe or pinch** on your ipad, that is an **event**. The **event listener** is a function that **detects the event**, and the **event handler** is a function that **links that event** to a function or class in your program. Events are what connect our physical actions to the didgital actions of the computer, making it interactive. # API (Application Programming Interface) An **API** is a bunch of **access points** that allow your own program to **communicate with anothers' program**, without having direct access to their secret recipe. In other words, if you want to make your own twitter app that can post to twitter, you have to use Twitter's API. Twitter has to give you a **key** to access certain parts of their API. An API is a bunch of custom variables and functions that make up Twitter. Twitter allows you to use them to program for their program. This keeps people from stealing the secret Twitter recipe of from hacking Twitter. http://markdownshare.com/view/eb975811-188e-4a9f-ab34-7a231dbfb4ee http://markdownshare.com/edit/aa620e66af991c60371fe1b6c9e3a264 http://markdownshare.com/delete/aa620e66af991c60371fe1b6c9e3a264 # COMPILE After you write your program you have to translate it back into something the computer actually understands (into machine language). This process is called **compiling**. A **compiler** is a program that compiles programs. # EXECUTE When you finally run your program, the computer executes it. In other words the instructions in the recipe are carried out by the computer. # PROGRAMMING LANGUAGES ## HIGH-LEVEL LANGUAGES The easier the language you program in is to understand by humans, the higher its level is (most of the time). A programming language like LUA is a high-level language. They say it is more "**human-readable**". ## LOW-LEVEL LANGUAGES Computers cannot understand high-level programming languages. Computers understand what is called "**machine language**." Machine language is the lowest level language. **Assembly** is the second lowest low-level programming language. Assembly is the middleman language between machine code and human-readable code. ## COMPILED LANGUAGES A compiled programming language is a program that gets compiled (into machine language) and thereafter, read by the computer. - C - C++ - BASIC - Lisp - Objective C - Pascal - COBOL ## INTERPRETED LANGUAGES An interpreted programming language is one that is not translated, but interpreted, by means of an **interpreter**. The interpreter executes the program directly, without having to translate it to machine code. - Java - Python - Ruby # ADDITIONAL INFO ## Operating System - An **Operating System** is a **big program** that **runs other programs** like: - Windows - Mac OSx - Linux - There are even mobile operating systems: - IOS - Android - Windows RT ## Virus - A **Virus** is a **program that corrupts** other programs. ## Hacker - A **Hacker** is a **person** who **uses unconventional means** to access something. - There are three types of hackers - White Hat hackers - Grey Hat a hackers - Black Hat hackers ## Pseudocode - Pseudocode-- false(fake) code, is the steps of a program written in plain English. No syntax is required. It's more of an outline. ## Fork - A fork is when a person modifies your secret recipe(source-code), making it distinctly different) and creates a separate program. This usually creates a schism between users. - Forks usually happen when users or developers
Store Help ?
Run the block if
  • is Equal to
  • is Not Equal to
  • Contains
  • Doesn't Contain
  • Matches Regular Expression
Convert Markdown ?
Markdown Extras: Footnotes
…Strikethrough (~~x~~)
…Superscript (^x)
…Smart Quotes etc.
…Strip Metadata Headers
Set Variable ?
Variable Name
…End If
Show Help ?
Run the block if
  • is Equal to
  • is Not Equal to
  • Contains
  • Doesn't Contain
  • Matches Regular Expression
Custom UI ?
User Interface
Presentation Style
  • Sheet
  • Full-Screen
  • Popover
Use Editor Theme
…End If
…End If
…End If
Show HUD ?
HUD Text
To run an example, drag it above the stop action (not the entire group)
  • 1 Second
  • 2 Seconds
  • 3 Seconds
  • "Success"
  • "Error"
Stop ?
  • This Workflow
  • Repeat Block
Show HUD Alert
To run an example, drag it above the stop action
Beginner ?
Run the block if
  • is Equal to
  • is Not Equal to
  • Contains
  • Doesn't Contain
  • Matches Regular Expression
Variables ?
Source Code

# A string
name = 'Jackie'

# An integer
favorite_number = 4

# A float
height = 6.5

# A boolean
amICool = True 

# You can assign a new value to a variable
amICool = False 

# An array
array_of_colors = ['red','orange','yellow','green','blue','indigo','violet']
array_of_numbers = [23,13.4,1,782]
mixed_array = ['Zillow',34.9,True,798]

# A dictionary
description = {'eyeColor':'brown','physique':'muscled','demeanor':'confident'}
print description['eyeColor']
print description['physique']
print description['demeanor']


# ID of a variable
print id(name)
Printing ?
Source Code

print 'Hello'

print 'Hello','Editorial'

# Concatenate (gives errors if not strings)
print 'Hello' + 'Folks'

print 27
Integers ?
Source Code

number1 = 12
number2 = 144
number3 = "67"

print number1 + number2

print number2 - number1

print number1 * number2

print number2/number1

print number2**number1
print pow(number2,number1)

#Square root
print number2**(1/2.0)

#Order of operations
print (number1 + number2) * 3 + (number1**3)

# Increment an integer
number1 = number1 + 1
print number1

# Convert a string to an integer
number3 = int(number3)
Strings ?
Source Code

## Empty string
first_name = ""
last_name = ""

## Asign a value to a string
first_name = "joe"
last_name = "shmo"
occupation = "Truck Driver"

## Adding strings (concatenation)
print first_name + last_name

## Adding a space between string variables
print first_name + " " + last_name

## Starting a new line (escape characters)
print first_name + "\n" + last_name 

## Adding variables inside of a string (string formatting)
print "Hello %s" %(first_name)

## Multiple variables inside of a string
print "Hello %s %s" %(first_name,last_name)

## There is a better way to format strings
greeting = 'Hello {name}, my name is {myname}'
print greeting.format(name='Joseph',myname='Joey')

## Print a string several times
print first_name * 4

## Get index of a string
## Indices begin at 0
print first_name[0]
print first_name[1]
print first_name[2]

## A multi-line string
"""Multi-Line strings are sometimes used as multi-line comments, since python doesn't have syntax for multi-line comments."""

print first_name.capitalize()
print len(occupation) 
Tuples ?
Source Code
## Tuples are like lists, but cannot be changed (they are immutable).

x = 0
y = 1

## Create a Tuple
position = (50,200)

## Get tuple index
print position[x]
Lists ?
Source Code

# Create a list
Clients = ['Cierra','Lisa','Ibrahim','Eric','Nancy','Terry','Sarah']
print Clients

Employees = ['Eric','Margaret','Paul','Ole','Yul']
print Employees

# List Index
print Clients[0]

# List index range
print Clients[0:4]

# Append to a list
print Clients
#Same as:
#Clients[len(Clients):] = ['Joe'].

# Remove from a list
print Clients

# Insert item into a list at a location
print Clients

# Reverse a list
print Clients

# Sort a list
print Clients

# Remove an item at a location
print Clients

# Return the index of an item in the list
print Clients.index('Lee')

# Extend a list with another list
print Clients
# Same as:
#Clients[len(Clients):] = Clients

# Count how many times an item appears in a list
print Clients.count('Lisa')


# Loop through a list
for item in Clients:
	print item
#Remove a list from a list
for i in Clients:
		if i in Employees:
print Clients
Dictionaries ?
Source Code

# Create a dictionary (dictionary_name = {key:value})
inventory = {'light':'flashlight'}
print inventory

# Print the value of a key
print inventory['light']

# Update Dictionary 
inventory.update({'map':'New York'})
inventory.update({'phone':'Flip Phone'})
print inventory

# Update the key if it is already in the dictionary
inventory.update({'map':'New York'})
print inventory['map']

# Get all keys (outputs as a list)
print inventory.keys()

# Get all values (ouptuts as a list)
print inventory.values()

# Copy dictionary items as a list of tuples
# Basically converts a dictionary to a a list of tuples.  
print inventory.items()

# Length of a dictionary
print len(inventory)

# Delete inventory item
del inventory['map']
print inventory

# Iterate over dictionary
#print iter(inventory)
#print inventory.iterkeys()
#print inventory.itervalues()

# Remove item, and returns its value
# Alternately: inventory.popitem()
print inventory

# View keys of a dictionary
print inventory.viewkeys()

# View values of a dictionary
print inventory.viewvalues()

# View all items in a dictionary
print inventory.viewitems()
Conditonals ?
Source Code

on = True
number = 51

# If equal to
if on == True:
	print on

# Same (for booleans)
if on:
	print on

# If not equal to
if on != False:
	print on

# If greater than
if number > 23:
	print number

# If less than
if number < 77:
	print number
Booleans (BEG) ?
Source Code

location = 0
if location == 50:
	print 'Halfway there.'
elif location > 50 and location < 100:
	print 'More than halfway there.'
elif location < 50 and location > 0:
	print 'Less than halfway there.'
elif location == 100:
	print "You are there!"
elif location < 0:
	print "You're moving in the wrong direction!"
elif location > 100:
	print "You've gone too far."
elif location ==  0:
	print "You aren't moving!"
While Loop ?
Source Code
age = 0
old_age = 30

while age < old_age:
	print 'Still young @ ' + str(age)
	age = age + 1
if age ==  old_age:
	print "You've reached the pinnacle @ " + str(age)
Functions ?
Source Code
# A string
name = 'Jackie'

# An integer
favorite_number = 4

# A float
height = 6.553

# A boolean
amICool = True 

# You can assign a new value to a variable
amICool = False 

# An array
array_of_colors = ['red','orange','yellow','green','blue','indigo','violet']
array_of_numbers = [23,13.4,1,782]
mixed_array = ['Zillow',34.9,True,798]

# print() - Prints values to the screen

# Two ways to print
print height
print amICool

print array_of_colors
print array_of_numbers

# raw_input() - Gets input from the user
occupation = raw_input('What is your occupation? ')
print 'You are a ' + occupation

# len() - Gets the length of a string

# type() - Gets the type of a value

# str() - Converts a value to a string

# int() - Converts a value to an integer

# list() - Converts a value to a list

# float() - Converts a value to a float

# round() - Rounds a number to a given percision

# pow() - Raises a number or integer to a power 
power = pow(height,favorite_number)

# sum()- sum of all elements in an iterable 
print 'sum of array is',sum(array_of_numbers)

# help() - prints Python help information
#help() commented out for now

# Create a function
def MyFunction():
	print name
	print height
	print favorite_number

# Use/Call a function

## Function arguments
# One argument
def Write(first_name):
	print first_name

# More than one argument (separated by commas)
def Add(a,b):
	print 'The sum is ' +  str(a + b)


# Function return
def Multiply(a,b):
	product = a*b
	return product

print 'The product is',Multiply(2,89)
For loop ?
Source Code

print range(0,10)

# Loop over a range
for i in range(0,10):
	print i
# For each element inside of the range, print the element.

# Loop over a string
name = 'Joseph'
for letter in name:
	print letter

# Loop over a list
my_list = ['eggs','milk','bread']
for item in my_list: 
	print item
Classes ?
Source Code

# A class
class Fruit():
	def __init__(self,color,taste,type='Fruit'):
		# Member Variables
		self.color = color
		self.taste = taste
		self.type = type
	# A Method	
	def eat(self, item):
		print "Eating " + item

# An object
apple = Fruit("red","sweet")

# Accessing member variables
print(apple.type) # default value. a non-required argument.

# Using methods
Try & Accept ?
Source Code
# Try to do something, and if there is an error, do something else
    print "Hello World"
	print('Goodbye World')

# Types of exceptions
exceptions= """except IOError:
    print('An error occured trying to read the file.')
except ValueError:
    print('Non-numeric data found in the file.')

except ImportError:
    print "NO module found"
except EOFError:
    print('Why did you do an EOF on me?')

except KeyboardInterrupt:
    print('You cancelled the operation.')

    print('An error occured.')
…End If
Intermediate ?
Run the block if
  • is Equal to
  • is Not Equal to
  • Contains
  • Doesn't Contain
  • Matches Regular Expression
Booleans ?
Source Code

cold = False
hot = False
normal = False

cloudy = False
partly_cloudy = False
sunny = False

temp = 12
overcast = 68

if temp < 65:
	cold = True

if temp > 85:
	hot = True

if temp > 65 and temp < 85:
	normal = True

if overcast > 55:
	cloudy = True

if overcast < 30:
	sunny = True

if overcast > 30 and overcast < 55:
	partly_cloudy = True
if (cold and cloudy) and (cold and partly_cloudy):
	print 'Its gonna be a yucky day'
	print 'Its an okay day out!'
if (cold and cloudy) or (cold and partly_cloudy):
	print 'Its gonna be a yucky day'
	print 'Its an okay day out!'
if hot and sunny:
	print 'Its gonna be steaming!!'
Classes (INT) ?
Source Code
class Animal():
	# two underscores mean the varianle is private
	__name = ""
	__height = 0
	__weight = 0
	__sound = ''
	def __init__(self,name):
		self.__name = name
	def get_name():
		print name

a = Animal('a')

Conditionals (INT) ?
Source Code

adult = False
miniumum_age = 18

def CheckAge():
	age = int(raw_input('How old are you: '))
	if age >= miniumum_age:
		adult = True
		print 'You are legal'
	elif age < miniumum_age:
		print 'That is not old enough'
		adult = False
	if not adult:
Function Arguments ?
Source Code
def push_argument(*argparams):
	print argparams

def push_keys(**keyparams):
	print keyparams

def default_parameters(a='A',b='B'):
	print a,b
default_parameters(a='Not A',b='Not B')

def fixed_passed_parameters(a,b):
	print a,b
Source Code
# Sets
#import dis

A = [1,2,3]
B = [4,5,6,3,2]
C = ['a','b',3]

def getIntersection(*S):
    sets = iter(map(set, S))
    result = sets.next()
    for s in sets:
        result = result.intersection(s)
    return list(set(result))
print getIntersection(A,B,C)

def getUnion(*S):
	result = set().union(*S)
	return list(set(result))
print getUnionS(A,B,C)
…End If
Advanced ?
Run the block if
  • is Equal to
  • is Not Equal to
  • Contains
  • Doesn't Contain
  • Matches Regular Expression
Planets.py ?
Source Code
	           Rad   Mass(kg) Dens   Abo  Vo     Rot(days)
Mercury      2440  3.30e23  5.43  .11  -1.9    58.6
Venus        6052  4.87e24  5.24  .65  -4.4    -243 
Earth        6378  5.97e24  5.52  .30   -      0.99
Mars         3397  6.42e23  3.93  .15  -2.0    1.03
Jupiter     71492  1.90e27  1.33  .52  -2.7    0.41
Saturn      60268  5.68e26  0.69  .47   0.7    0.45
Uranus      25559  8.68e25  1.32  .51   5.5   -0.72
Neptune     24766  1.02e26  1.64  .41   7.8    0.67
Pluto        1150  1.27e22  2.06  .55  13.6   -6.39  (z)

# I googled for a way to get the execution time for a python script.
# http://stackoverflow.com/questions/1557571/how-to-get-time-of-a-python-program-execution

import atexit
from time import clock

def secondsToStr(t):
    return "%d:%02d:%02d.%03d" % \
        reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],

line = "="*40
def log(s, elapsed=None):
    print line
    print secondsToStr(clock()), '-', s
    if elapsed:
        print "Elapsed time:", elapsed
    print line

def endlog():
    end = clock()
    elapsed = end-start
    log("End Program", secondsToStr(elapsed))

def now():
    return secondsToStr(clock())

start = clock()
log("Start Program")

#I googled how to put comma separators in numbers
#x = '{:,}'.format(238383)
#print x

## #http://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-separators
# Adds commas to floats
def float2comma(f):
    s = str(abs(f)) # Convert to a string
    decimalposition = s.find(".") # Look for decimal point
    if decimalposition == -1:
        decimalposition = len(s) # If no decimal, then just work from the end
    out = "" 
    for i in range(decimalposition+1, len(s)): # do the decimal
        if not (i-decimalposition-1) % 3 and i-decimalposition-1: out = out+","
        out = out+s[i]      
    if len(out):
        out = "."+out # add the decimal point if necessary
    for i in range(decimalposition-1,-1,-1): # working backwards from decimal point
        if not (decimalposition-i-1) % 3 and decimalposition-i-1: out = ","+out
        out = s[i]+out      
    if f < 0:
        out = "-"+out
    return out

import math

lesson_number = 1

title = "Calculate the Area of a Planet\n"

#\n is like hitting the RETURN key. A backslash is an escape character.

pie = math.pi 
e = math.e

#radius_of_my_head = None
#planet_to_head_ratio = None
# commented this code out for possinle later use.

km = 'kilometers'
abbr = '(km)' 


mercury = {'name':'Mercury','radius':2440,'units':km,'abbr':abbr}
venus = {'name':'Venus','radius':6052,'units':km,'abbr':abbr}
earth = {'name':'Earth','radius':6378,'units':km,'abbr':abbr}
mars = {'name':'Mars','radius':3397,'units':km,'abbr':abbr}
jupiter = {'name':'Jupiter','radius':71492,'units':km,'abbr':abbr}
saturn = {'name':'Saturn','radius':60268,'units':km,'abbr':abbr}
uranus = {'name':'Uranus','radius':25559,'units':km,'abbr':abbr}
neptune = {'name':'Neptune','radius':24766,'units':km,'abbr':abbr}
pluto = {'name':'Pluto','radius':1150,'units':km,'abbr':abbr}

sun = {'name':'Sun','radius':695000,'units':km,'abbr':abbr}
moon = {'name':'Moon','radius':1738,'units':km,'abbr':abbr}

# How to add to dictionary

planet = [mercury,venus,earth,mars,jupiter,saturn,uranus,neptune,pluto]
body = [sun,moon]

def Calculate_Volume(planet_arg):
	volume = 4 *(pie * math.pow(planet_arg['radius'],2))
	print 'The approximate volume of ' + planet_arg['name'] + ', regarding the atomispheric layers' +' is ' + str(volume) + ' ' + planet_arg['units'] + planet_arg['abbr'] + '^3'
	return volume

# V = (4/3)*pi*r^2

print "Lesson " + str(lesson_number)
print title

def Get_Radius(planet_arg):
	print 'The radius of ' + planet_arg['name'] + ' is ' + str(planet_arg['radius']) + ' ' + planet_arg['units'] + planet_arg['abbr']
	return planet_arg['radius']

def Set_Mass(coefficient,power):
	mass = str(coefficient) + 'e' + str(power)
	return mass
def Get_Mass(planet_arg):
	print 'The mass of ' + planet_arg['name'] + ' is ' + planet_arg['mass']
	return planet_arg['mass']
mercury['mass']= Set_Mass(3.30,23)
venus['mass']= Set_Mass(4.87,24)
earth['mass']= Set_Mass(5.97,24)
mars['mass']= Set_Mass(6.42,23)
jupiter['mass']= Set_Mass(1.90,27)
saturn['mass']= Set_Mass(5.68,26)
uranus['mass']= Set_Mass(8.68,25)
neptune['mass']= Set_Mass(1.09,26)
pluto['mass']= Set_Mass(1.27,22)

…End If
Other ?
Run the block if
  • is Equal to
  • is Not Equal to
  • Contains
  • Doesn't Contain
  • Matches Regular Expression
Variables are Nouns ?
Source Code
# -*- coding: utf-8 -*-
# Variables are Nouns
import string

person = 'Jackie Barns'

place = 'AT&T®'

thing = 'telephone'

area_code = 770
prefix = 456
line_number = 1234

number = str(area_code) + str(prefix) + str(line_number)

x = string.split(number,None,3)

for i in x:
	print string.joinfields(i,'...')

info = '%s works at %s where they provide service to a %s' % (person,place,thing)

print info
print number
Strings ?
Source Code
#String Funtions
import string

name = 'john jacob jingleheimer schmidt'

place = 'Wasington D.C.'
print place

place = place.lower()
print place

place = place.upper()
print place

## Format
formatted_string ='My name is %s' % ('Mr Editorial')
print formatted_string

multiVariable_formatted_string = "He crossed the %(blank)s at %(time)d o'clock" % {'blank':'street','time':12}
print multiVariable_formatted_string

## Classes
place = string.capitalize(place)
print place

split_name = string.split(name,None,-1)
print split_name

joined_split_name = string.join(split_name)
print joined_split_name

print string.capwords(joined_split_name,None)
Functions (INT) ?
Source Code
welcome = 'Welcome to Editorial! '
response = raw_input('How are you today? ')
computer_response = 'It seems you are ' + response

# Create a function
def PrintSomething():
	print 'Hi'
# Call the function

# Function arguments/parameters
def PrintArgument(argument):
	print argument

Run Python Script ?
Source Code
# -*- coding: utf-8 -*-

initial_position = 0
temperature = 0

def CheckTemperature(final_destination,temperature=0,location=''):	
	while temperature <= final_destination:
		diff = final_destination-temperature
		temperature = temperature + 1
		halfway_point = (final_destination-initial_position)/2
		info = str(temperature) + ' is ' + location + str(diff) + ' More to go!'
		if temperature == halfway_point:
			location= 'Halfway there.'
			print info
		elif temperature > halfway_point and temperature < final_destination:
			location= 'More than halfway there.'
			print info
		elif temperature < halfway_point and temperature > initial_position:
			location= 'Less than halfway there.'
			print info
		elif temperature == final_destination:
			location= "There!"
			print info
		elif temperature == initial_position:
			location= "Move it bub!!"
			print info
		elif temperature < initial_position:
			location= "Negative!"
			print info
		elif temperature > final_destination:
			location= "Too far."
			print info
		if temperature >= (temperature-1):
			print 'going in the right direction'
			print 'Wrong way Josè!'

print '\n'
Boolean (ALT) ?
Source Code
# -*- coding: utf-8 -*-


temperature = -10

initial_position = 0
final_destination = 100
halfway_point = (final_destination-initial_position)/2
location = ''
while temperature < final_destination:
	diff = final_destination-temperature
	temperature = temperature + 1
	if temperature == halfway_point:
		location= 'Halfway there.'
		print str(temperature) + ' is ' + location + str(diff) + ' More to go!'
	elif temperature > halfway_point and temperature < final_destination:
		location= 'More than halfway there.'
		print str(temperature) + ' is ' + location + str(diff) + ' More to go!'
	elif temperature < halfway_point and temperature > initial_position:
		location= 'Less than halfway there.'
		print str(temperature) + ' is ' + location + str(diff) + ' More to go!'
	elif temperature == final_destination:
		location= "There!"
		print str(temperature) + ' is ' + location + ' No more to go!'
	elif temperature < initial_position:
		location= "Negative!"
		print str(temperature) + ' is ' + location + str(diff) + ' More to go!'
	elif temperature > final_destination:
		location= "Too far."
		print str(temperature) + ' is ' + location + str(diff) + ' More to go!'
	if temperature >= (temperature-1):
		print 'going in the right direction'
		print 'Wrong way Josè!'
class INT ?
Source Code
# Import the math class
import math

number = 2272
print math.sqrt(number)

choice = raw_input('Take the square root of what number? ')
print math.sqrt(float(choice))
# The sqrt() function only takes floats
Programming Tutorial ?
Source Code
# the 'notes' variable is just a multiline-string

notes = '''
These concepts will be demonstrated in this program 

	- ROM
	- RAM
	- If
	- else if
	- else
	- While Loop
	- For Loop
	- String
	- Integer
	- Float
	- Character
	- Boolean
	- Array
	- OOP
- API (Application Programming Interface)
# Python doesnt have syntax for multi-line comments.
Info ?
Source Code
grade = "A"

# String
name = 'Joey'
print name

favorite_number = 24
print favorite_number

height = 6.3

you_are_tall = False

colors_of_the_rainbow = ['Red','Orange','Yellow','Greeen','Blue','Indigo','Violet']

print colors_of_the_rainbow
print colors_of_the_rainbow[0]
print colors_of_the_rainbow[-1]

car = {'make':'Pontiac','model':'Firebird','color':'Red'}

print car['color']
print car['make']
print car['model']

print car['color'] + car['make'] + car['model']

car = {'make':'Pontiac ','model':'Firebird ','color':'Red '}

print car['color'] + car['make'] + car['model']
Fuzzy Temperature ?
Source Code
# Fuzzy Logic 

# fuzzify a range of values as a state

import ui

def update(sender):
	value = slider.value * 100
	label.text = str(value)
	def fuzzify(min,max,condition):
		membership = (value-min)/(max-min)
		if value > min and value < max:
			print condition,membership
			state.text = condition + ' to the ' + str(round(membership,2)) + ' degree'
	print fuzzify(75,85,"warm")
	print fuzzify(0,30,"freezing")

view = ui.load_view()
slider = view['slider']
label = view['label']
state = view['state']

Load and save ?
Source Code
def saved(**object):
	var = object
	return var

stored = saved(name='Joe')

def load(x):
	print x


# Another simpler method

def store(**object): # ** creates a keyword argument
	var = object
	return var
stored = store(name='Joe',occupation='Janitor')

print stored['name']
…End If
Ignore duplicates ?
Source Code
letters = ['A','B','C','D','E']
nums = [1,2,3,4,5]

def append_to_other_list(A,B):
	for item in A:
		if item not in B:

print nums
AI ?
Run the block if
  • is Equal to
  • is Not Equal to
  • Contains
  • Doesn't Contain
  • Matches Regular Expression
Interpret ?
Source Code
sentence1 = 'Hello World'
sentence2 = "I am not afraid"
sentence3 = 'I am okay'
sentence4 = 'You are very cool'
sentence5 = 'The house is far away. I am so scared'

assocation = {
'far away':'not close at all',

def interpretationOf(sentence):
	for word in assocation:
		if word in sentence:
			sentence = sentence.replace(word,assocation[word])
	interpretation = sentence
	return interpretation

print sentence2
print interpretationOf(sentence2) + '\n'
print sentence1
print interpretationOf(sentence1)
print interpretationOf(sentence3)
print interpretationOf(sentence4)
print interpretationOf(sentence5)

def hasNegatives(sentence):
	if 'not' or 'Not' in interpretationOf(sentence):
		return True 
		return False 

print hasNegatives(sentence5)
print hasNegatives(sentence1)

hot = True 
sunny = True 
cold = False 
cloudy = False 
snowing = True 

clothingWhenIts = {
    (hot, sunny): "shorts",
    (cold, cloudy): "jeans",
    (cold, snowing): "jacket"

print clothingWhenIts[hot,sunny]
print clothingWhenIts[cold,cloudy]
print clothingWhenIts[cold,snowing]

def ifIts(a,b,function):
	if a ==  True  and b == True :
		print 'One or the other is not true.'

def goOutside():
	print 'Yay! Going outside!'
…End If