Skip to main content
GameDev.net gamedev.net
🔒 Locked

Massive Python Example Script

Started by Tutorial Doctor May 20, 2015 at 12:03 AM 24 replies 28.5k views
Original Post
Tutorial Doctor
Tutorial Doctor

TL;DR

I am trying to make a massive example script, demonstrating all of the core syntax of Python (beginner to intermediate and maybe advanced). It could serve as a tutorial even.

I want it to be one sample project that includes all of the following syntax for python, but I can't think of a good example. Could use some help. I also want to do the same thing for LUA and eventually C#. I would like to use the same example. I used the analogy of cooking to make an intro to computer programming course, so I guess I could go with that, but I don't exactly know how I would incorporate all of the following constructs.

I could do the whole boring data base thing, but it's boring.

Currently the examples are unrelated.

Here is what I have so far:


# -*- coding: utf-8 -*-
print "Python Examples\n --By The Tutorial Doctor\n"

## PRINTING

print 'Hello'

print 'Hello','Editorial'

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

print 'Hello' + ' Folks' # have to add your own space

print 27


# VARIABLES
#There are different types of variables: character, string, integer, float, boolean, array/list, dictionary, and a few others.

# A character
at = "@"

# A string
name = 'Jackie'

# An integer
favorite_number = 4

# A float
height = 6.5

# A boolean
IamCool = True 

# You can assign a new value to a variable
IamCool = 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']

# EXTRA

# ID of a variable
print id(name)

#####

# STRINGS
# A string is string of characters 

## 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 another 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."""


# STRING FUNCTIONS
print first_name.capitalize()
print len(occupation) 

#####

# INTEGERS
# An integer is a whole number

number1 = 12
number2 = 144
number3 = "67" #not an integer

#Add
print number1 + number2

#Subtract
print number2 - number1

#Multiply
print number1 * number2

#Divide
print number2/number1

#Exponents
print number2**number1
#Same
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)

#####

#FLOAT
# A float is a decimal. Many of the integer operations can be applied to floats.
pi = 3.14
print pi
#####

# TUPLES
## 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/Array
# Called a list in python.

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

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

### LIST FUNCTIONS
# List Index
print Clients[0]

# List index range
print Clients[0:4]

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

# Remove from a list
Clients.remove('Joe')
print Clients

# Insert item into a list at a location
Clients.insert(0,'Lee')
print Clients

# Reverse a list
Clients.reverse()
print Clients

# Sort a list
Clients.sort()
print Clients

# Remove an item at a location
Clients.pop(0)
print Clients

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

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

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


### EXTRA

# Loop through a list
for item in Clients:
	print item
	
#Remove a list from a list
for i in Clients:
		if i in Employees:
			Clients.remove(i)
print Clients

#####

### DICTIONARIES/Associative array

# 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':'Atlanta'})
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
inventory.pop('phone')
# 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()

#####

### CONDITIONALS

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)
# if, else, and else if(elif)

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
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
# A function is a group of statements

IamCool = True
### BUILT-IN FUNCTIONS
# print() - Prints values to the screen
print(name)
print(favorite_number)

# Two ways to print
print height
print IamCool,",I am cool"

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
print(len(name))

# type() - Gets the type of a value
print(type(height))

# str() - Converts a value to a string
print(type(str(height)))

# int() - Converts a value to an integer
print(type(int(height)))

# list() - Converts a value to a list

# float() - Converts a value to a float

# round() - Rounds a number to a given percision
print(round(height,2))
print(round(height,1))


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

# 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
MyFunction()

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

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

Add(2,3)
Add(2.89,34.2)

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

print 'The product is',Multiply(2,89)

#####

### FOR LOOP

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

#####

# WHILE LOOP
i = 1
while i<11:
	print "uh",i, "and"
	i = i + 1 #increment i

### CLASSES

# 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.color)
print(apple.taste)
print(apple.type) # default value. a non-required argument.

# Using methods
apple.eat("vegetables")

#####

# Try to do something, and if there is an error, do something else
try:
    print "Hello World"
except:
	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.')

except:
    print('An error occured.')
"""

#####

### PART 2 ###

# -*- coding: utf-8 -*-
# BOOLEANS

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'
else:
	print 'Its an okay day out!'
	
	
if (cold and cloudy) or (cold and partly_cloudy):
	print 'Its gonna be a yucky day'
else:
	print 'Its an okay day out!'
	
	
if hot and sunny:
	print 'Its gonna be steaming!!'

class Animal():
	# two underscores mean the variable is private
	__name = ""
	__height = 0
	__weight = 0
	__sound = ''
	def __init__(self,name):
		self.__name = name
		
	def get_name(self):
		print self.__name

a = Animal('a')

a.get_name()

# CONDITIONALS

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:
		CheckAge()
CheckAge()

# FUNCTIONS (INTERMEDIATE)
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
PrintSomething()

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

PrintArgument(welcome)
PrintArgument(computer_response)

def push_argument(*argparams):
	print argparams
push_argument('a','b')


def push_keys(**keyparams):
	print keyparams
push_keys(ok='right')


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
fixed_passed_parameters('a','b')


#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

## FOMATTING
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)

# -*- coding: utf-8 -*-

# BETTER WAY

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'
	else:
		print 'Wrong way Josè!'



They call me the Tutorial Doctor.
TheChubu
TheChubu




I used the analogy of cooking to make an intro to computer programming course, so I guess I could go with that, but I don't exactly know how I would incorporate all of the following constructs.
Then it might not be a good idea.
"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"   My journals: dustArtemis ECS framework and 
smr
smr
It may be more effective to break it up into smaller, more concise scripts that are easier to digest.
Tutorial Doctor
Tutorial Doctor

I was just thinking of that actually. At most, I will only do 3. I am going to keep refining it until it is perfect. Then I am just going to mimic it in other languages. The reason I am doing this is because it can take a while for a person to become comfortable with a programming language, especially when they have to google something every time they want to do a relatively basic task.

I think I still want them in the same file though. I might add importing modules.

They call me the Tutorial Doctor.
ChaosEngine
ChaosEngine




I think I still want them in the same file though.

Why?

You're making it harder to edit, harder to read, and on top of everything else, you're teaching bad habits. Think about it, if someone came to you with a decent size program all in one file/function, the first thing you'd say to them would be to break it up into manageable chunks.

if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight
smr
smr
Also if someone is going to use this for a reference it should be well indexed. If I need to scan through your mega script for more than 5 seconds to find what I'm looking for in going to google instead.
Tutorial Doctor
Tutorial Doctor

I didn't want them to have to file hop as much, but if it is easier that way, I guess I will do it. I will just put them into one folder.

I wanted the file to be skimmed, not actually read. So yeah, I know I have to make the indexing better. I have the main titles in all caps, but is there a better way?

I am mainly looking on suggestions. So far so good.

They call me the Tutorial Doctor.
Bacterius
Bacterius

Why would someone new to Python skim a tutorial, and what could he hope to learn by skimming? Also, I feel there are enough tutorials online about basic Python syntax for beginners, how about doing something a little more useful such as how to create runnable Python scripts, creating and managing modules, usage of setup.py/pypi to distribute scripts and programs, etc... you know, the kinds of things that people still have to read through (mostly) technical documentation to figure out. In my opinion this is where clear, well-written tutorials and good code snippets are most urgently needed, everyone and their dog has already written Python intro tutorials and there are some really good ones out there.

“If I understand the standard right it is legal and safe to do this but the resulting value could be anything.”
mic_k
mic_k




So yeah, I know I have to make the indexing better. I have the main titles in all caps, but is there a better way?

smile.png Small angle from me..

Perhaps to put some thing like table of content at the very top page,

describe all the main sections title & subs there, so people who read can see the whole (possible)features/topics that available,

then they will find based on those section title to the related content, wherever.

Anyway, how is the finding method perform ?

If using html, can use hyperlink that pointing to certain section inside one page.

Onigiri Flash
Onigiri Flash




I want it to be one sample project that includes all of the following syntax for python, but I can't think of a good example. Could use some help. I also want to do the same thing for LUA and eventually C#. I would like to use the same example. I used the analogy of cooking to make an intro to computer programming course, so I guess I could go with that, but I don't exactly know how I would incorporate all of the following constructs.

If I may, I would suggest building an application (such as a chatbot, text adventure, ASCII roguelike, guess the number game, text RPG, shopkeeper sim, calculator, horoscope, personality test, etc.) with all the concepts you wish to demonstrate (strings, integers, input/output, functions, classes, if-statements, etc.), whilst commenting the code as you've done in your example. Your audience will feel more engaged while learning with your demo because it shows how these concepts come together to form a cohesive program. I can appreciate this tutorial series for that reason. happy.png I do wish you well on your project! I know you're going to help a lot of people with this.

Tutorial Doctor
Tutorial Doctor

Thanks for all of the replies!

@Onigiri Flash

I do hope it will help a lot of people. Trying to figure out if I should host it on Github or not. Great idea.

@mic_k

I should make a table of contents indeed.

@Bacterius

Great point! The point of this is exactly that, a way to eliminate having to read through technical documentation or stack overflow posts. I do need more ideas on essentials and your ideas sound great. I will look into it.

They call me the Tutorial Doctor.
Tutorial Doctor
Tutorial Doctor

I figured I should style the document better if I am going to do a massive script. There will be much more commenting in the file, but for now:


# -*- coding: utf-8 -*-
print "Python Examples\n --By The Tutorial Doctor\n"
print ("Remove tripple quotes around each secrion to test the code therein" )


## PRINTING
#---------------------------------------------------------------------
"""
print 'Hello'

print 'Hello','Editorial'

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

print 'Hello' + ' Folks' # have to add your own space

print 27
"""
#---------------------------------------------------------------------


# VARIABLES
#---------------------------------------------------------------------
#There are different types of variables: character, string, integer, float, boolean, array/list, dictionary, and a few others.
"""
# A character
at = "@"

# A string
name = 'Jackie'

# An integer
favorite_number = 4

# A float
height = 6.5

# A boolean
IamCool = True 

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

# To set a boolean to the opposite of what it is
IamCool = not IamCool

# 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]

#Tuple
location = (32,128)

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

# EXTRA

# ID of a variable
print id(name)
"""
#---------------------------------------------------------------------


# STRINGS
#---------------------------------------------------------------------
"""
# A string is string of characters 

## 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 another 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.'''

# STRING FUNCTIONS
print first_name.capitalize()
print len(occupation) 
"""
#---------------------------------------------------------------------


# INTEGERS
#---------------------------------------------------------------------
"""
# An integer is a whole number

number1 = 12
number2 = 144
number3 = "67" #not an integer

#Add
print number1 + number2

#Subtract
print number2 - number1

#Multiply
print number1 * number2

#Divide
print number2/number1

#Exponents
print number2**number1
#Same
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)
"""
#---------------------------------------------------------------------


#FLOAT
#---------------------------------------------------------------------
"""
# A float is a decimal. Many of the integer operations can be applied to floats.
pi = 3.14
print pi
"""
#---------------------------------------------------------------------


#TUPLES
#---------------------------------------------------------------------
"""
## 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/Array
#---------------------------------------------------------------------
"""
# Called a list in python.

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

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

### LIST FUNCTIONS
# List Index
print Clients[0]

# List index range
print Clients[0:4]

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

# Remove from a list
Clients.remove('Joe')
print Clients

# Insert item into a list at a location
Clients.insert(0,'Lee')
print Clients

# Reverse a list
Clients.reverse()
print Clients

# Sort a list
Clients.sort()
print Clients

# Remove an item at a location
Clients.pop(0)
print Clients

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

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

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


### EXTRA

# Loop through a list
for item in Clients:
	print item
	
#Remove a list from a list
for i in Clients:
		if i in Employees:
			Clients.remove(i)
print Clients
"""
#---------------------------------------------------------------------


### DICTIONARIES/Associative array
#---------------------------------------------------------------------
"""
# 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':'Atlanta'})
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
inventory.pop('phone')
# 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()
"""
#---------------------------------------------------------------------


### CONDITIONALS
#---------------------------------------------------------------------
"""
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)
#---------------------------------------------------------------------
"""
# if, else, and else if(elif)

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
#---------------------------------------------------------------------
"""
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
#---------------------------------------------------------------------
"""
# A function is a group of statements

IamCool = True
### BUILT-IN FUNCTIONS
# print() - Prints values to the screen
print(name)
print(favorite_number)

# Two ways to print
print height
print IamCool,",I am cool"

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
print(len(name))

# type() - Gets the type of a value
print(type(height))

# str() - Converts a value to a string
print(type(str(height)))

# int() - Converts a value to an integer
print(type(int(height)))

# list() - Converts a value to a list

# float() - Converts a value to a float

# round() - Rounds a number to a given percision
print(round(height,2))
print(round(height,1))


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

# 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
MyFunction()

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

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

Add(2,3)
Add(2.89,34.2)

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

print 'The product is',Multiply(2,89)
"""
#---------------------------------------------------------------------


### FOR LOOP
#---------------------------------------------------------------------
"""
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
"""
#---------------------------------------------------------------------


# WHILE LOOP
#---------------------------------------------------------------------
"""
i = 1
while i<11:
	print "uh",i, "and"
	i = i + 1 #increment i
"""
#---------------------------------------------------------------------


### CLASSES
#---------------------------------------------------------------------
"""
# 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.color)
print(apple.taste)
print(apple.type) # default value. a non-required argument.

# Using methods
apple.eat("vegetables")
"""
#---------------------------------------------------------------------


#FILES
#---------------------------------------------------------------------
"""
file = open('words.txt','w')
# Create a file named 'words.txt' that we can write to (current directory).

file.write('Hello')
#Write to the file
file.write(' world\n')
file.write(':)')

file.close()
#close the file

file = open('words.txt','r')
#open the file. the variable name doesnt have to be 'file'

print file.read()
# read the contents of the file

# Try to do something, and if there is an error, do something else
try:
    print "Hello World"
except:
	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.')

except:
    print('An error occured.')
    '''
"""
#---------------------------------------------------------------------


### PART 2 ###
#---------------------------------------------------------------------
"""
# -*- coding: utf-8 -*-
# BOOLEANS

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'
else:
	print 'Its an okay day out!'
	
	
if (cold and cloudy) or (cold and partly_cloudy):
	print 'Its gonna be a yucky day'
else:
	print 'Its an okay day out!'
	
	
if hot and sunny:
	print 'Its gonna be steaming!!'

class Animal():
	# two underscores mean the variable is private
	__name = ""
	__height = 0
	__weight = 0
	__sound = ''
	def __init__(self,name):
		self.__name = name
		
	def get_name(self):
		print self.__name

a = Animal('a')

a.get_name()

# CONDITIONALS

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:
		CheckAge()
CheckAge()
"""
#---------------------------------------------------------------------


# FUNCTIONS (INTERMEDIATE)
#---------------------------------------------------------------------
"""
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
PrintSomething()

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

PrintArgument(welcome)
PrintArgument(computer_response)

def push_argument(*argparams):
	print argparams
push_argument('a','b')


def push_keys(**keyparams):
	print keyparams
push_keys(ok='right')


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
fixed_passed_parameters('a','b')
"""
#---------------------------------------------------------------------


# PARAMETERS cont'd
#---------------------------------------------------------------------
"""
#Tutorial Doctor

def push_argument(*argparams):
	print argparams
push_argument('a','b')

def push_keys(**keyparams):
	print keyparams
push_keys(ok='right')
"""
#---------------------------------------------------------------------


#ARGUMENT PARAMETERS
#---------------------------------------------------------------------
"""
empty_list = []
def add_to(x,*items):
	x.append(items)

add_to(empty_list,'up','down','left','right')
updated_list = empty_list[0]
#This has to be done, else a list of tuples will be created.
print updated_list
"""
#---------------------------------------------------------------------


#KEY PARAMETERS
#---------------------------------------------------------------------
"""
inventory= {}
#Our inventory is an empty dictionary

def add_to_inventory(**items):
	inventory.update(items)
	#Adding key parameters to the empty inventory dictionary

add_to_inventory(food='pizza')
#Now we can add keys, with their values to the inventory
print inventory

add_to_inventory(food='apple')
#This will overwrite the food key with a new value
print inventory

add_to_inventory(light='flashlight')
print inventory
#Adds another item to the inventory 

print inventory['light']
print inventory['food']
"""
#---------------------------------------------------------------------


#STRING FUNCTION:
#---------------------------------------------------------------------
"""
import string

name = 'john jacob jingleheimer schmidt'

place = 'Wasington D.C.'
print place

place = place.lower()
print place

place = place.upper()
print place
"""
#---------------------------------------------------------------------


## FOMATTING
#---------------------------------------------------------------------
"""
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)

# -*- coding: utf-8 -*-

# BETTER WAY

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'
	else:
		print 'Wrong way Josè!'
"""
#---------------------------------------------------------------------


# MODULE EXAMPLE
#---------------------------------------------------------------------
"""
#Definer
# By Tutorial Doctor
import re
import console

sentence = 'okay we go'

dictionary = {}

expression = re.compile('\w+')
matches = expression.findall(sentence)


for match in matches:
	definition = raw_input('defition of %s? ' % (match))
	dictionary.update({match:definition})
	
print dictionary
"""
#---------------------------------------------------------------------



They call me the Tutorial Doctor.
iDingo
iDingo

So yeah, I know I have to make the indexing better. I have the main titles in all caps, but is there a better way?

smile.png Small angle from me..

Perhaps to put some thing like table of content at the very top page,

describe all the main sections title & subs there, so people who read can see the whole (possible)features/topics that available,

then they will find based on those section title to the related content, wherever.

Anyway, how is the finding method perform ?

If using html, can use hyperlink that pointing to certain section inside one page.

This guy ^

Tutorial Doctor
Tutorial Doctor
Definitely going to add the table of contents.
They call me the Tutorial Doctor.
Tutorial Doctor
Tutorial Doctor

Been thinking about a demo project that displays every construct. Perhaps a game about moving through an invisible level? Anyhow, this is how my commenting looks so far (code not cleaned yet). I am going to add perhaps one example of inheritance without using super() because that is only in version 3 I think. Basically, if the current location of the character is the same as a preset location of an object, something happens (perhaps the player gets reset at the start or something else):


#Tutorial Doctor 5/27/15

#Axis constants
AXIS_X = 'x'
AXIS_Y = 'y'

#Vector class
class Vector2:
	def __init__(self,x,y):
		self.x=x
		self.y=y
	def __str__(self):
		#Return the vector's x and y components as a tuple (for printing the vector)
		return str((self.x,self.y))
	
	def move(self,axis,amount):
		if axis.upper()=='X':
			self.x=self.x+amount
		elif axis.upper()=='Y':
			self.y=self.y+amount
		print 'moved by %s on the %s axis' %(amount,axis.upper())
		print(self.x,self.y)
	
	#Returns True if x and y components are equal to zero(or reset)
	def is_reset(self):
		#If the x component is equal to 0...
		if self.x==0:
			#And if the y component is also equal to zero..
			if self.y==0:
				#return True
				return True
		#By default, return False
		return False
	
	#Sets x and y components to zero(resets)
	def reset(self):
		self.x=0
		self.y=0
		
	def get_location(self):
		print 'located at : ' + str(self)
	
		
#Now, create a point vector called "P"
P = Vector2(0,0)

#print the point to test the string(str) constructor 
print P

#move point P along the x-axis -9 units
P.move(AXIS_X,-9)

#move point P along the y-axis 34 units
P.move(AXIS_Y,34)

#Check P
P.get_location()

P.x=3
P.get_location()
P.y=9
P.get_location()

#P.reset()

print P.is_reset()

P.move(AXIS_X,6)
P.reset()

P.get_location()

They call me the Tutorial Doctor.
Tutorial Doctor
Tutorial Doctor

Okay. I guess this could almost turn into a sort of game engine eh (not a full or correct one necessarily)?

Here is the base of the code for the project with comments.


#Tutorial Doctor 5/27/15-5/28/15
#------------------------------------------------------------------------------

#Import the math module for later use
import math

#Axis constants
AXIS_X = 'x'
AXIS_Y = 'y'

#Create a 2D Vector class
class Vector2:
	def __init__(self,x,y):
		self.x=x
		self.y=y
	
	#Returns a string version of the object as a tuple of the x and y components
	def __str__(self):
		#Return the vector's x and y components as a tuple (for printing the vector)
		return str((self.x,self.y))
	
	#Moves the object along a specified axis by a specified amount
	def move(self,axis,amount):
		#If the axis is 'x' (accounting for upper or lowercase input)...
		if axis.upper()=='X':
			#add an amount to the x component
			self.x=self.x+amount
		#Otherwise if the axis is y (accounting for upper or lowercase input)...
		elif axis.upper()=='Y':
			#add an amount to the x component
			self.y=self.y+amount	
		print 'moved by %s on the %s axis' %(amount,axis.upper())

	
	#Returns True if the x and y components of the object are equal to zero(or reset)
	def is_reset(self):
		#If the x component is equal to 0...
		if self.x==0:
			#and if the y component is also equal to zero..
			if self.y==0:
				#return True
				return True
		#By default, return False
		return False
	
	#Sets x and y components of the object to zero(resets them)
	def reset(self):
		self.x=0
		self.y=0
	
	#Get's the location of the object
	def get_location(self):
		print 'located at '+str(self)

		
#Now we can create a point vector called "P"
P = Vector2(0,0)
#Print the point to test the __str__ constructor 
print P

#Move point P along the x-axis -9 units
P.move(AXIS_X,-9)

#Move point P along the y-axis 34 units
P.move(AXIS_Y,34)

#Check P's location
P.get_location()

#Change P's x component
P.x=3
P.get_location()

#Change P's y component
P.y=9
P.get_location()

#Reset P's location
P.reset()

#Check if P has been reset
print P.is_reset()


#FUNCTIONS
#------------------------------------------------------------------------------
#Create another point...
R = Vector2(0,0)
#and move it
R.move(AXIS_Y,30)
R.move(AXIS_X,-20.9)

#Returns the distance between two points as a float
def distance_between(a,b):
	#Distance =....
	D = math.sqrt(pow((b.y-a.y),2.0) + pow((b.x-a.x),2.0))
	#Equation is from the distance formula
	
	#Return the distance
	return D

#Returns the midpoint between two points as a tuple
def midpoint_between(a,b):
	#Midpoint =....
	M = ((a.x+b.x)/2.0,(a.y+b.y)/2.0)
	#Equation is from the midpoint formula
	
	#Return the midpoint
	return M

# Returns the slope between two points
def slope_between(a,b):
	# Slope =....
	S = (b.y-a.y)/(b.x-a.x)
	#from the slope formula
	
	#Return the slope
	return S

#print by itself makes an empty line(for seperating code output)
print
print 'The distance between the points is '+ str(distance_between(R,P)) + ' units'
print str(midpoint_between(R,P)) + ' is the midpoint between the points'
print 'The slope between the points is ' + str(slope_between(R,P))
#------------------------------------------------------------------------------


#INHERITANCE
#------------------------------------------------------------------------------
class Character(Vector2):
	pass
	"""
	def jump(self):
		if self.y==0:
			if raw_input('command: ').upper()=='JUMP':
				while self.y < raw_input('height: '):
					self.y+=1
					print self.y
	"""

sam = Character(0,0)
sam.move(AXIS_X,14)
sam.location=sam
print sam.location
#sam.jump()


They call me the Tutorial Doctor.
Aardvajk
Aardvajk
Just a point regarding interfaces to vectors. It would be much clearer and more sensible to have:

def move(self,xamount,yamount):
    self.x=self.x+xamount
    self.y=self.y+yamount

#usage
p.move(10, 0); #instead of p.move(AXIS_X, 10)

One enormous file trying to demonstrate every feature of a language is a terrible idea by the way, but I assume that has been pointed out already in this thread.
Tutorial Doctor
Tutorial Doctor
Good point. Thanks.
They call me the Tutorial Doctor.
Aardvajk
Aardvajk
I'm not sure if Python supports overloading operators or passing class objects as parameters, forgive my ignorance here, but in languages that do this sort of thing is normally handled as an addition. For example in C++, rather than have a move() method, you would do:

Vec2 a(10, 20);
a += Vec2(5, 4);

In something like Javascript which would not support overloading, you tend to see (not a javascript guy either so this is probably wrong):

var a = new Vec2(10, 20);
a.add(new Vec2(5, 4));

Most of the things you would want to do with vectors when treating them as points in a Cartesian space have an equivalent mathematical interpretation that applies in the far more general sense, where "move" would be the wrong term but "add" is always correct.
SimonForsman
SimonForsman

I'm not sure if Python supports overloading operators or passing class objects as parameters, forgive my ignorance here, but in languages that do this sort of thing is normally handled as an addition. For example in C++, rather than have a move() method, you would do:


Vec2 a(10, 20);
a += Vec2(5, 4);
In something like Javascript which would not support overloading, you tend to see (not a javascript guy either so this is probably wrong):


var a = new Vec2(10, 20);
a.add(new Vec2(5, 4));
Most of the things you would want to do with vectors when treating them as points in a Cartesian space have an equivalent mathematical interpretation that applies in the far more general sense, where "move" would be the wrong term but "add" is always correct.

in python you can implement the __add__ and __radd__ methods to overload the + operator. x+y will try to call x.__add__(y) and if the method returns NotImplemented and x and y are of different types it will try y.__radd__(x) instead (if that also fails it will raise an exception)

something like:

[source]

class Vector2:

.....

def __add__(self, v):

if not isinstance(v, Vector2):

return NotImplemented

return Vector2(self.x + v.x, self.y + v.y)

def __iadd__(self, v):

if not isinstance(v, Vector2):

return NotImplemented

self.x += v.x

self.y += v.y

return self

def __mul__(self, v):

if not isinstance(v, numbers.Number):

return NotImplemented

return Vector2(self.x * v, self.y * v)

def __rmul__(self, v):

return self.__mul__(v)

def __imul__(self, v):

....

....

....

etc

[/source]

[size="1"]I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.