Вы находитесь на странице: 1из 80

Python

Tutorial

Basic Syntax
HelloWorld.py ———————————> p. 4
Variables.py ————————————> p. 5
ArithmeticOperators.py ——> p. 6
ComparisonOperators.py ——> p. 8
AssignmentOperators.py ——> p. 9
IfStatement.py ——————————> p. 10
TernaryOperator —————————> p. 11
LogicalOperators.py —————> p. 12
ForLoop.py ——————————————> p. 13
NestedForLoop.py ————————> p. 14
WhileLoops ——————————————> p. 15
Numbers.py ——————————————> p. 16
MathFunctions.py ————————> p. 17
String.py ———————————————> p. 18
List.py —————————————————> p. 19
Tuple.py ————————————————> p. 21
Sets.py —————————————————> p. 22
Dictionary.py ———————————> p. 23
Functions.py ————————————> p. 25
Recursion.py ————————————> p. 26
Scope.py ————————————————> p. 27

Advanced
UserMod.py ——————————————> p. 28
Modules.py ——————————————> p. 29
IO.py ———————————————————> p. 30
FileIO.py ———————————————> p. 31
Exceptions.py ———————————> p. 32
CommandLine.py ——————————> p. 33


Object Oriented
Classes.py ——————————————> p. 34
Init.py —————————————————> p. 35
SettersAndGetters.py ————> p. 36

Sample Programs
CoinFlip.py —————————————> p. 38
TempConverter.py ————————> p. 39
GuessThePassWord.py —————> p. 40
CpuSpeed.py —————————————> p. 41
ListAnalysis.py —————————> p. 42
SpellCheck.py ———————————> p. 44
DefualtDictDemo.py ——————> p. 45
ChemicalElement.py ——————> p. 46
PeriodicTable.py ————————> p. 47
BankAccount.py ——————————> p. 49
BankAccountDemo.py ——————> p. 50
FibRecursion.py —————————> p. 51
Knight.py ———————————————> p. 52
Wizard.py ———————————————> p. 54
Orc.py ——————————————————> p. 56
Elf.py ——————————————————> p. 58
Arena.py ————————————————> p. 60
Cards.py ————————————————> p. 61
BlackJack.py ————————————> p. 63
FlashCards.py ———————————> p. 64
FlashCardDemo.py ————————> p. 65








Author’s Note

Thank you very much for your purchase, and your interest in learning a wonderful
programming language. “Python Examples” contains over 50 examples that are fully functional,
easy to use, and unique. Previous programming knowledge is not required, however previous
knowledge can do nothing but help. The only requirement is patience, dedication, and a passion
for learning. However, as to not deter you from learning Python I am going to explain how to
create, compile, and run a “.py” source file.
In order to create an editable “.py” source file you first need to choose a text editor(emacs
vi, vim, notepad++, etc), I am going to use emacs. So to create a “.py” source file type the
following command into your command line:
emacs SourceFile.py

Then to compile and run a “.py” file use the command:

python SourceFile.py

New topics are presented in this book in an easy to understand way, then programs are
made using the new topic as well as previously discussed topics in order to review and learn
new material
simultaneously. This helps you maximize learning a new language. There is much to learn and
practice makes perfect. So let us begin.


Thank You












HelloWorld.py

#!/usr/bin/python

#The above line is the directory where your python
#interpreter is located. Yours may be located in a different
#directory. Do some research to find out where it is.
#You can run a python source code without it, but it
#is good practice to leave it in.

'''
Author | Email | Date
HelloWorld: Just a test to make sure that our Python environment is set up correctly. We will be
discussing basic syntax, comments, and
the print function. First of all a comment is not run by the Python interpreter, a comment is only
meant for human eyes. Second, there are two types of comments: block and single line. A block
comment
is stated with triple quotes, either single or double, and closed with the same quotes. We are in a
block comment right now, so now of this will be ran.
'''

#This is a single line comment, declared with a # sign

#Python uses indentations rather than curly brackets, {}
#to signify blocks of code
print('Hello World')#no semi colon

'''
in python 2 print wasn’t a function so
no parenthesis were needed, but in python 3
parenthesis are need because print is a function
print prints out whatever is in quotations onto your screen.
'''

'''
That is it for general set up, no need for a main function, semi colons, or brackets; pretty nice
right. Notice there is just one line of code in here, the rest are comments.
'''



Output:

Hello World


Variables.py

#!/usr/bin/python
'''
Author | Email | Date
Variables: How to initialize variables. Variables in Python are
different than other programming languages. We will discuss why.
'''

'''
Python has five standard Data Types:
Numbers, String, List, Tuple, Dictionary
That you can use as variables, these are not the only types
you can use, but they are all we need for now.
'''
#in other languages when you initialize a variable you need to
#declare a data type(i.e. int, float, etc)
#in Python all you have to do is name the variable and assign it.
name = ‘DoEasy'#string
#we just created a variable named ‘name’
#and initialized it to ‘DoEasy’

friendName="Frank"#string
#illegal “tom’, your quotes must match like comments
print("Name: "+ name)
print("friendName: "+friendName)
height = 72.5#floating pt(a decimal number)
weight = 132#integer(a whole number)
#you can initialize multiple variables on the same line
x, y, z = 23.4, 13, 'awesome'

#below is a variable conversion,
#python has all basic variables
#ready to easily convert with these functions
#this is necessary because print
#prints out a string, and you can not add a string to an int
#so we must convert our int to a string with the str() function
print("height: "+str(height)) #this is the conversion
print("weight: "+str(weight))
print("x: "+str(x)+"\ny: "+str(y)+"\nz: "+z)
#\n is a newline character


Output:

Name: DoEasy
friendName: Frank
height: 72.5
weight: 132
x: 23.4
y: 13
z: awesome

ArithmeticOperators.py

#!/usr/bin/python
'''
Author | Email | Date
ArithmeticOperators: Arithmetic operators include: +, -, *, /, %, **, and \\. They perform
arithmetic operations on data types.
'''
#+ is the addition operator, it works on strings, and ints
#but not the combination of the two
add = 5+3.4
concatenate = ‘Do'+'Easy'
#a concatenation is what you do when you combine two strings

#below is illegal
#combo = '5'+3
#however this is legal, 5 is a string you can tell by the quotes
#notice the new conversion function int()
combo = int('5')+3
print('add: '+str(add)+'\nconcatenate: '+concatenate+'\ncombo: ‘
+str(combo))
#subtract, divide, and multiply all work the same way, but they can't
#concatenate strings

'''
The Modulus Operator: % returns the remainder of a division
problem
'''
mod = 5%2 #will return 1

'''
Floor Division: //
Retuns the quotient without the remainder, however if one operand
is negative it will round towards negative infinity
'''
floor = 5//2
negFloor = 5//-2
print('mod: '+str(mod)+'\nfloor: '+str(floor)+'\nnegFloor: '+str(negFloor))

'''
Exponent Operator
'''
exp = 2**3#two cubed
exp2 = 3**2#3 squared
print('exp: '+str(exp)+'\nexp2: '+str(exp2))





Output:

add: 8.4
concatenate: DoEasy
combo: 8
mod: 1
floor: 2
negFloor: -3
exp: 8
exp2: 9








































ComparisonOperators.py

#!/usr/bin/python
'''
Author | Email | Date
ComparisonOperators: Comparison operators compare two values they
include: ==, !=, >, <, >=, <=
'''

#please note python also supports using is
#rather than == (checkA is checkB)
#and is not in replace of != (checkA is not checkB)

'''
== compares if two values are equal, this works on numbers and strings
!= compares if two values are not equal
'''
s = 'hi'
t = 'hi'
print(s==t)
print(s!=t)
x = 100
y = 101
print(x==y)
print(x!=y)
'''
Then there are less than, greater than,
greater than or equal to, and less than or
equal to
'''
a = 99
b = 12
c = 99
print(a<b)
print(a>b)
print(a<=c)
print(b>=c)
'''
Note: These comparison operators return a boolean. A boolean can be true of false
'''

Output:

True
False
False
True
False
True
True
False

AssignmentOperators.py

#!/usr/bin/python
'''
Author | Email | Date
AssignmentOperators: Assignment operators assign a value to a variable while also performing
some sort of arithmetic operation, any
arithmetic operators we have discussed can be used along with
an assignment operator.
They include: =, +=, -=, *=, /=, %=, **=, //=
'''
x = 1
print('x before: '+str(x))
x += 3 #short hand notation for x = x+3
print('x after: '+str(x))

Output:

x before: 1
x after: 4




























IfStatement.py

#!/usr/bin/python
'''
Author | Email | Date
IfStatement: How to declare an if, else if and else statement.
Remember python uses indents rather than curly brackets to separate
blocks of code.
‘''

check = 13
#we need some sort of condition to check
#it must evaluate to true or false
if check < 10:
print('If check passed, all else if and else skipped')
elif check > 10:
print('Else if check passed, all else skipped')
else:
print('No checks passed, yet this will still run')

'''
You can use any comparison operator inside if blocks.
If statements control the flow of your program please note, that all ifs will be checked, but else if
and else will be skipped if conditions up above are met. So if you want to check many things, use
a many if statements.
'''

Output:

Else if check passed, all else skipped



















TernaryOperators.py

#!/usr/bin/python
import random
"""
Author | Email | Date
TernaryOperator: Ternary operators are shorthand
notation for if blocks. They test some condition,
and based off of some condition a variable is assigned.
Please note we are importing random, random has a function
that gives us a random number from a given range.
"""
randNumber = random.randrange(0,2);
#randNumber will either be 0 or 1 but not 2

outcome = 'One' if randNumber == 1 else "Zero"
print("Outcome: "+ outcome)

Output:

Outcome: One



























LogicalOperators.py

#!/usr/bin/python
'''
Author | Email | Date
Logical Operators: Logical operators allow you to chain to together conditions to check in if
statements. They include the following
operators: and, or.
'''

checkA = 1
checkB = 2
checkC = 3

#please note python also supports using is
#rather than == (checkA is checkB)
#and is not in replace of != (checkA is not checkB)

if checkA != checkB and checkA == checkB:
print('If passed, all other code will skip')
elif checkB != checkC or checkA != checkC:
print('Elif passed, all other code will skip')
else:
print('No check passed, else executed')

'''
You can chain as many as these together as you like,
but it may become complicated. “Not” is similar to the
bang operator (!), it checks the opposite.
'''

Output:

Elif passed, all other code will skip

ForLoop.py

#!/usr/bin/python
'''
Author | Email | Date
ForLoop: There are many ways to use a for loop in python. For loops are very powerful. A useful
function for loops is range(), it gives you a range from 0 to the parameter - 1 with one parameter.
We will discuss the rest below. We will go more in depth on for loops later as we progress our
knowledge but this is a nice start.
'''

#one argument
#our range is from 0 to 4
for x in range(5):
print('x: '+str(x))

#two arguments, gives a base to start from
#so our range is from 4 to 9
for y in range(4,10):
print('y: '+str(y))

#three arguments, provide some sort of counter
#so were in the range 0 to 9 and we will count by 2’s
for z in range(0,10, 2):
print('z: '+str(z))

Output:

x: 0
x: 1
x: 2
x: 3
x: 4
y: 4
y: 5
y: 6
y: 7
y: 8
y: 9
z: 0
z: 2
z: 4
z: 6
z: 8




NestedForLoop.py

#!/usr/bin/python
"""
NestedForLoop: A nested for loop is a loop within
a loop, a double for loop.
"""
#lets print out a multiplication table
for i in range(1,13):
for j in range(1,13):
print str(i*j)+ "\t",
print("\n")
"""
our nested for loop should run 144 times, they are a great tool
but could slow down your program significantly, but for now
we should be alright. Try to understand this example.
\t is a tab character, it is like \n
"""

Output:

1 2 3 4 5 6 7 8 9 10 11 12

2 4 6 8 10 12 14 16 18 20 22 24

3 6 9 12 15 18 21 24 27 30 33 36

4 8 12 16 20 24 28 32 36 40 44 48

5 10 15 20 25 30 35 40 45 50 55 60

6 12 18 24 30 36 42 48 54 60 66 72

7 14 21 28 35 42 49 56 63 70 77 84

8 16 24 32 40 48 56 64 72 80 88 96

9 18 27 36 45 54 63 72 81 90 99 108

10 20 30 40 50 60 70 80 90 100 110 120

11 22 33 44 55 66 77 88 99 110 121 132

12 24 36 48 60 72 84 96 108 120 132 144

WhileLoop.py

#!/usr/bin/python
from random import randrange as rand
"""
WhileLoop: A while loop is similar to a for loop
however they are useful for when you don’t know
how long your loop will run for. Once again we will
use a random number.
"""
count = 1
randNum = rand(0,100)
while randNum is not 50:#no curly brackets just a colon
#so as soon as randNum == 50 the loop will terminate
#we don’t know how long it will take,
#it could take 1 try, it could take one million tries
#lets find out
count += 1 #count = count + 1
#don’t forget to change randNum
# to avoid an infinite loop
randNum = rand(0,100)
print("It took "+ str(count) + " tries to get 50.”)

"""
You can use the range function in a while loop just like a for loop,
they are both very similar.
"""

Output:

It took 38 tries to get 50.

















Numbers.py
'''
Author | Email | Date
Numbers: Covers the different types of numbers used within Python.
Numbers include: int, long, float, and complex. Numbers can be as large as you want in Python
there is no size limit based on bit length.
'''
#int numbers are whole numbers, pos or neg
a = -999999999
b = 999999999
print('a = '+str(a)+'\nb: '+str(b))

#long numbers, longs, are integers of unbounded size
long1= 2**45
print('long1: '+str(long1))

#floating point values, are decimal numbers
float = 98.98
print('float: '+str(float))

#complex numbers, have some imaginary part
#they take the form: a + bJ where a is real
#b is imaginary, and J is the square root of -1
#they are not used much in Python
complex = 8 + 3J
print('complex: '+str(complex))

'''
Each of these number types has a type conversion function associated
with it, like str(). They are: int(), long(), float(), and complex()
'''

Output:

a = -999999999
b: 999999999
long1: 35184372088832
float: 98.98
complex: (8+3j)










MathFunctions.py

#!/usr/bin/python
import math
'''
Author | Email | Date
MathFunctions: Covers the different type of math functions, trig functions, and math constants
available in Python.
Math functions include: abs(), ceil(), cmp(x,y), exp(),
fabs(), floor(), log(), log10(), max(x,y), min(x,y), modf(),
round(), pow(), and sqrt().
In order to use these you need to import math
'''
#We will discuss a few
#max, min find the biggest or smallest respectively
print('Max: '+str(max(100, 55)))

#floor finds largest int without going over
print('floor: '+str(math.floor(89.9)))

#ceil finds smallest integer not smaller than argument
print('ceil: '+str(math.ceil(89.9)))

'''
There are also many trigonometric functions available too.
They include: acos(), asin(), atan(), cos(), hypot(x,y), sin(),
tan(), degrees(), radians()
Please research further.
'''
print('convert 90 degrees to radians: '+str(math.radians(90)))
print('convert 1 radian to degrees: '+str(math.degrees(1)))

'''
There are also some constants pi and e
math.pi
math.e
'''

Output:
Max: 100
floor: 89.0
ceil: 90.0
convert 90 degrees to radians: 1.57079632679
convert 1 radian to degrees: 57.2957795131





String.py
'''
Author | Email | Date
String: Strings in Python can be expressed with single or double quotes. There are many built in
functions to support strings,
strings are limitless, so have fun.
'''
word = "hello"
string = 'this is a sentence'

'''
Special String Operators
'''
print(word+' '+string)
print(word*3)#creates repetition

#you can access individual characters of a String
print('word[2]: ‘+word[2])

#below does not include nine, [3,8]
print('string[3:9]: '+string[3:9])

#you can test to see if a letter in a string is present
#or if a string is present in a string
#using the in operator
print('e in word: '+str("e" in word))
print('ll in word: '+str("ll" in word))
#you can also use not in

'''
You can format a string with placeholders
'''
str1 = "Hello my name"
str2 = "is DoEasy ::)"
print ("%s %s" % (str1,str2))

"""
There are also over 30 functions to use with strings,
please research these and have fun playing around
with them.
“""

Output:

hello this is a sentence
hellohellohello
word[2]: l
string[3:9]: s is a
e in word: True
ll in word: True
Hello my name is DoEasy ::)

List.py
#!/usr/bin/python
'''
Author | Email | Date
Lists are very versatile, they are declared with square
brackets, where elements are separated by commas.
List can contain different data types.
Have fun.
'''

names =['Bob','Ross','Michael','Angie']
people = ['lisa',33,'Tom',13]
print('names: '+str(names))
print('people[2]: '+str(people[2]))

#you can slice lists just like a string,
#remember the end is non inclusive,
#when you leave the first blank, it counts as 0
print('people[:2]: '+str(people[:2]))

#delete an element as follows
del names[2]
print('names after deletion: '+str(names))
'''
Built in list functions include:
cmp(l1,l2), len(), man(), min(), list()
'''

#more for loops the len() function is great inside the range function
for i in range(len(names)):
print('names['+str(i)+']: '+str(names[i]))
#you could try list.pop() right here...
#another way to iterate through a list
#say like: for each name in names
for name in names:
print('name: '+name)

'''
There are also many other useful methods(functions) to
have fun with lists. They include, append, count, extend, index,
insert, pop, remove, reverse, and sort.
'''
scores = [2,7,8,1,2]
print('scores before sort: '+str(scores))
scores.sort()
print('scores after sort: '+str(scores))
#pop removes the last element from the list, for you
#to use or discard
print('scores before pop: '+str(scores))
scores.pop()
print('scores after pop: '+str(scores))

Output:

names: ['Bob', 'Ross', 'Michael', 'Angie']
people[2]: Tom
people[:2]: ['lisa', 33]
names after deletion: ['Bob', 'Ross', 'Angie']
names[0]: Bob
names[1]: Ross
names[2]: Angie
name: Bob
name: Ross
name: Angie
scores before sort: [2, 7, 8, 1, 2]
scores after sort: [1, 2, 2, 7, 8]
scores before pop: [1, 2, 2, 7, 8]
scores after pop: [1, 2, 2, 7]


































Tuples.py
#!/usr/bin/python
'''
Author | Email | Date
A tuple is like a list except it is immutable, meaning
once it has been initialized, you can not add to nor change the
tuple.
'''
#they are created with parenthesis
grades = ('Mike',45,'Lisa', 99)
print('grades: ‘+str(grades))

#you can access tuples how you access lists
print('grades[1]: '+str(grades[1]))
#or you could include two arguments

#you can check to see if an item is in a list
print('45 in grades: '+str((45 in grades)))

# you can also iterate through a tuple just like a list
for grade in grades:
print('grade: ‘+str(grade))

'''
Built in tuple functions include:
cmp(t1, t2), len(), max(), min(), tuple()
'''


Output:

grades: ('Mike', 45, 'Lisa', 99)
grades[1]: 45
45 in grades: True
grade: Mike
grade: 45
grade: Lisa
grade: 99










Sets.py
#!/usr/bin/python
from sets import Set
'''
Author | Email | Date
Sets are unordered collections of unique elements.
You can have a mutable set, or an immutable set.
You need to have the import statement however. Sets contain no
duplicate values.
'''
#how you declare a set
numbers = ([1,2,3,4,5])
print('numbers: ‘+str(numbers))

scores = [22,45,87,87,89,98,100,100]
print('scores before set(): '+str(scores))
print('scores after set(): ‘+str(Set(scores)))

#this will scramble so just throw it back into a list, and sort()
l = list(scores).sort()
print('after sort(): '+str(scores))

'''
You can also iterate through a Set the same way we learned before,
we can also use "in" to test if an element is in the set.
'''

"""
Check out all the functions associated with sets online to find out
all the cool stuff you can do with sets.
"""

Output:

numbers: [1, 2, 3, 4, 5]
scores before set(): [22, 45, 87, 87, 89, 98, 100, 100]
scores after set(): Set([98, 100, 45, 22, 87, 89])
after sort(): [22, 45, 87, 87, 89, 98, 100, 100]












Dictionary.py

#!/usr/bin/python
'''
Author | Email | Date
Dictionary: Dictionaries associate a key with a value. They are extremely useful in python. They
are not concerned with indices rather they are concerned with unique identifiers, the keys.
‘''

#declare a dictionary with curly brackets
zipcodes = {"Des Moines": 50301,
"Tallahassee": 32301,
"Honolulu":96801}

#we are using a key to access a value
print('zipcodes["Honolulu"]: '+str(zipcodes['Honolulu']))

#you can add new entries or update
print("zipcodes before: "+str(zipcodes))
zipcodes["Des Moines"] = 10000
zipcodes["Sacramento"] = 45678
print("zipcodes after: "+str(zipcodes))

#what about a list as a value, or a dict as a value?
#people, have a phone number and an age...
people = {'Bella':[5559089999, 23], 'Mike':[5557890000,55]}
print("people['Bella']: "+ str(people['Bella']))
print("people['Bella'][0]: "+ str(people['Bella'][0]))

#you can iterate through a list much the same way as before
for key in zipcodes:
print('Key: '+key+' Value: '+str(zipcodes[key]))

"""
There are many functions to deal with dictionaries:
cmp, len, str, type, clear, copy, fromkeys, get, has_key,
items, keys, setdefault, update, values
"""
print("zipcodes.items(): "+str(zipcodes.items()))
print("zipcodes.values(): "+str(zipcodes.values()))










Output:

zipcodes["Honolulu"]: 96801
zipcodes before: {'Tallahassee': 32301, 'Honolulu': 96801,
'Des Moines': 50301}
zipcodes after: {'Tallahassee': 32301, 'Sacremento': 45678,
'Honolulu': 96801, 'Des Moines': 10000}
people['Bella']: [5559089999, 23]
people['Bella'][0]: 5559089999
Key: Tallahassee Value: 32301
Key: Sacramento Value: 45678
Key: Honolulu Value: 96801
Key: Des Moines Value: 10000
zipcodes.items(): [('Tallahassee', 32301), ('Sacramento', 45678), ('Honolulu',
96801), ('Des Moines', 10000)]
zipcodes.values(): [32301, 45678, 96801, 10000]


































Functions.py

#!/usr/bin/python
'''
Author | Email | Date
How to declare and use your own functions.
We will be using the define keyword, def.
'''

'''
Return first returns the first element in an iterable sequence.
Notice no return type, or declaring data types within the parameter list. All you do is def
funName(parameter list)
'''
def returnFirst(list):
print("List: "+str(list))
return list[0]

'''
Multiplies x and y,
a function with multiple parameters.
'''
def multiply(x,y):
return x*y

'''
You can define a main function although, in most cases
there is no need for this, just calling your functions
is okay. The functions have to be defined before you
can call them.

'''
def main():
people = ['Kate','Bob', 'Kathy']
first = returnFirst(people)
print("firstReturned(): "+first)
print('Multiply(): '+str(multiply(2,3)))
#don't forget to call the main function.
main()

Output:

List: ['Kate', 'Bob', 'Kathy']
firstReturned(): Kate
Multiply(): 6





Recursion.py

#!/usr/bin/python
"""
Recursion: A recursive function is a function
that calls itself. There must be a base case and
a recursive step within a recursive function.
Recursion is good in that it is somewhat easier to
read and write, however it takes up more space on the
heap so they can take longer to run.
"""

"""
Calculates the factorial of n
0! = 1
"""
def factorial(n):
#this is the base case
if n is 0:
return 1
#recursive step
else:
return n * factorial(n-1)
print("5!: "+str(factorial(5)))
print("25!: "+str(factorial(25)))

Output:

5!: 120
25!: 15511210043330985984000000





















Scope.py

#!/usr/bin/share
"""
Scope: Scope is where you can use a variable
based off of where the variable was initialized.
You can have global or local scope. The scope concept
can be applied to variables as well as functions.
"""
#i = 0 #has global scope #comment this back in
#to make the very last line work

for i in range(10):
print ("i: "+str(i))
#trying to print i outside of the for loop
#will not work because i has a scope local to
#the for loop, in order to make below work you
#need to give i global scope
#print("i outside of for loop: "+str(i))

Output:

i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9

















UserMod.py
'''
UserMod: In Python we can create our own modules, that you
can then load into other .py files.
'''

def printMessage():
print("I am the imported function\nHave a nice day.”)










































Modules.py

#!/usr/bin/python
import InMod #our own created modules
import math
'''
Author | Email | Date
Modules: Imports a module the user made. Also, discusses how to get the functions contained
within a module using the dir() function.
'''
#using the imported function
InMod.printMessage()

'''
The dir() built in function returns a sorted list of strings
containing the names defined by module.
__name__ is module's name
__file__is filename where module was loaded
'''
print(dir(InMod))

print(dir(math))

Output:
I am the imported function
Have a nice day.
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'printMessage']
['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2',
'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial',
'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10',
'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', ‘trunc’]














IO.py

#!/usr/bin/python
'''
Author | Email | Date
IO: How to receive input from the user, from standard input. We have been dealing with output
since the beginning using the print function, now it is time to get some user input in order to make
some really
intersting programs.
'''

userInput = raw_input("Enter Input: ")
print("Raw_Input Entered: "+ userInput)

#note the difference: need quotes with input()
userInput = input("Enter Input: ")
print("Input Entered: "+ userInput)

'''
Once you have your input you can then put it into a list,
using the list() function, then on those individual members
you can use int(), float(), or whatever function you need
in order to manipulate the data how you like.
‘''

Output:

Enter Input: hello
Raw_Input Entered: hello
Enter Input: 'This is input 8 8 8'
Input Entered: This is input 8 8 8


















FileIO.py
'''
Author | Email | Date
FileIO: How to read and write to a file from a
python file.
'''
#lots of different options for opening a file
#we are choosing just to read

#print("File Name: "+file.name)
lines = tuple(open("test.txt","r"))
print(lines)


"""
try out the split function on your own
to split on what you choose, however if you
want to split on a new line character use splitlines()
"""
with open("test.txt","r") as file:
splitlines = file.read().splitlines()
print(splitlines)
file.close()

"""
We will now write to a file
"""
#this will over write the file
#or create a new file
output = open("output_test.txt","w")
message = """Hello I am writing to the output file...\n
this is how you have a multi line string in python\n
thanks for watching ::)
"""
output.write(message)
print("Successfully wrote to file.")

Output:

('hello i am a text file\n', 'i am only a couple minutes old\n', 'but i am pleased to make your
acquaintance\n')
['hello i am a text file', 'i am only a couple minutes old', 'but i am pleased to make your
acquaintance']
Successfully wrote to file.







Exception.py

#!/usr/bin/python
'''
Author | Email | Date
Exception: How to deal with exceptions, and some different exceptions
you will run across in Python. Exceptions are errors, there are many different types of errors, but
when one is thrown at you they are
pretty descriptive. You should only catch exceptions that are usually
thrown by your code.
'''
#try block is used to run high risk code
try:
quotient = 5/0
except ZeroDivisionError:#catching a specific exception
print("Please don't divide by zero.")
except Exception: #this final one will catch all exceptions
print("This will catch all other Exceptions")
print("Exception is the Base Class for all Exceptions")
else:
print("No exceptions thrown, rest of code will execute ::)")

"""
There are many exceptions in python, you can even create your own
once we cover how to make classes, I highly suggest researching them
how you deal with caught exceptions is totally up to you. Although it is usually very specific to
your program.
"""

Output:

Please don't divide by zero.



















CommandLine.py

#!/usr/bin/python
import sys
'''
Author | Email | Date
CommandLine: How to take in command line arguments.
Notice the new import statement. Command line arguments are arguments you pass to your
program through the command line.
‘''

#how you get command line arguments
cmdline = sys.argv

print("Args: "+str(cmdline))
#notice the file name is inlcuded
#to access individually think of as a list
print("cmdline[1]: "+str(cmdline[1]))

#or you could take a section
print("cmdline[1:]: "+str(cmdline[1:]))

total = 0
for number in cmdline[1:]:
total = total + int(number)
print("total: “+str(total))

'''
When you have a command line argument it is a string. So you must use
some of the handy conversion functions we have talked about in order to turn the argument into the
desired variable.
‘''



python CmdLine.py 1 2 3 4
Args: ['CmdLine.py', '1', '2', '3', '4']
cmdline[1]: 1
cmdline[1:]: ['1', '2', '3', '4']
total: 10









Classes.py
#!/usr/bin/python
'''
Author | Email | Date
Classes: How to define classes in a Python program.
Python is a very versatile language. A class is like a representation
of something physical or abstract. Classes have data and functions.
'''

#create the class
class Person:
#class variables/functions
name=""
age = 0

#now we have a very basic class,
#with this class we can start to create objects
#objects are instances of classes
#create a person object
person = Person()

#use the dot operator to access data inside the class
person.name = "Frank"
person.age = 77

#just printing out the person object
print("Name: "+str(person.name))
print("Age: “+str(person.age))

Output:

Name: Frank
Age: 77
















Init.py

#!/usr/bin/python
"""
Init: init is a special function with a Python class that initializes
an object. These special functions are sometimes called constructors, because they “build”
objects. When you create function within a class you need to include self, in order for the Python
interpreter to know
what object to call the functions on. But when you call the functions you do not need to include the
self
"""
class Person:
#notice no more variables in here
"""
Parameterized constructor: Initializes Person
data to given values. In this case name to n
and age to a
"""
def __init__(self, n, a):
#self refers to the object on which we are calling
#the function from
self.name = n
self.age = a

"""
printPerson: prints a representation of our person object.
A useful function to have within your class.
"""
def printPerson(self):
print("Name: "+str(self.name))
print("Age: "+str(self.age))


person = Person("Frank", 77)#notice no self
person.printPerson()

Output:

Name: Frank
Age: 77








SettersAndGetters.py

#!/usr/bin/python
"""
SettersAndGetters: Are functions within a class to access data
and to also change/initialize data.
"""
class Person:
#notice no more variables in here
#below is the new content
"""
Returns name
"""
def getName(self):
return self.name
"""
Sets name to n
"""
def setName(self, n):
self.name = n
"""
Returns age
"""
def getAge(self):
return self.age
"""
Sets age to a
"""
def setAge(self, a):
self.age = a
#back to old content, but with new functions
"""
Parameterized constructor: Initializes Person
data to given values. In this case name to n
and age to a
"""
def __init__(self, n, a):
#self refers to the object on which we are calling
#the function from
self.setName(n)
self.setAge(a)
"""
printPerson: prints a representation of our person object.
A useful function to have within your class.
"""
def printPerson(self):
print("Name: "+str(self.getName()))
print("Age: "+str(self.getAge()))
person = Person("Frank", 77)
person.printPerson()
person2 = Person("Bob", 22)
person2.printPerson()
Output:

Name: Frank
Age: 77
Name: Bob
Age: 22














































CoinFlip.py

#!/usr/bin/python
from random import randrange as rand
"""
CoinFlip: Simulates a coin flip.
"""
outcome = "Heads" if (rand(0,2) is 1) else "Tails"

print("It landed on: "+str(outcome))

Output:

It landed on: Heads





































TempConverter.py

#!/usr/bin/python
"""
TempConverter: Converts a user defined
fahrenheit temperature to C and K
"""
tempF = raw_input("Enter fahrenheit: ")
tempC = (float(tempF) - 32) / 180*100
tempK = tempC + 273.15
#print(5/9)
print("tempF: "+str(float(tempF)))
print("tempC: "+str(tempC))
print("tempK: “+str(tempK))

Output:

Enter fahrenheit: 0
tempF: 0.0
tempC: -17.7777777778
tempK: 255.372222222






























GuessThePassWord.py

#!/usr/bin/python
"""
GuessThePassWord: A little game to see if
your friends can guess your password
"""
password = "Password"
guess = ""
while(guess != password):
guess = raw_input("Take a guess: ")
print("You won the password was "+ password+" ::)”)

Output:

Take a guess: hello
Take a guess: apple
Take a guess: this
Take a guess: is
Take a guess: hard
Take a guess: Password
You won the password was Password ::)





























CpuSpeed.py

#!/usr/bin/python
import time
"""
CpuSpeed: A test to see how fast you CPU is.
Note different machines produce different results.
"""
print("Adding 1 million elements to a list")
list = []
begin = time.time()
for i in range(1000000):
list.append(i)
end = time.time()
print("That took "+str(end-begin)+ "seconds")
print("That's pretty fast”)

Output:

Adding 1 million elements to a list
That took 0.181584119797seconds
That's pretty fast





























ListAnalysis.py

#!/usr/bin/python
from random import randrange as rand
"""
ListAnalysis: Creates a random list filled with integers
Then finds the largest, smallest, mean, median and mode.
"""
"""
RandomArray: Creates a random array of
1000 ints.
"""
def randomArray():
nums = []
for i in range(1000):
nums.append(rand(0,10))
return nums

"""
biggest: Returns the biggest number in a sorted list.
"""
def biggest(list):
return list[len(list)-1]

"""
smallest: Returns the biggest number in a sorted list.
"""
def smallest(list):
return list[0]


"""
mean: Returns the mean of the list
"""
def mean(list):
return (sum(int(i) for i in list)) / len(list)

"""
median: Returns the median of the list
"""
def median(list):
return list[int(len(list)/2)]












"""
mode: Returns the mode of the list.
"""
def mode(list):
mode = {}
for num in list:
if mode.has_key(num):
mode[num] += 1
else:
mode[num] = 1
foundKey = -1
for key in mode:
if mode[key] > foundKey:
foundKey = key
return key

def main():
randomList = randomArray()
randomList.sort()

#no need to check duplicate values for biggest/smallest
noDuplicates = list(set(randomList))
big = biggest(noDuplicates)
small = smallest(noDuplicates)
average = mean(randomList)
middle = median(randomList)
most = mode(randomList)
print("Biggest: "+str(big))
print("Smallest: "+str(small))
print("Mean: "+str(average))
print("Median: "+str(middle))
print("Mode: "+str(most))

main()

Output:

Biggest: 49
Smallest: 0
Mean: 23
Median: 24
Mode: 49









SpellCheck.py

#!/usr/bin/python
"""
SpellCheck: Uses /usr/share/dict/words to perform
spell checks. All unix OS should have this. If it
is not in the previous directory it will be in
/usr/dict/words.
"""
"""
stripWords: Adds all words in directory to list
"""
def stripWords():
with open("/usr/share/dict/words","r") as words:
wordList = words.read().splitlines()
words.close()
return wordList

"""
spellCheck: Returns true if test is
present inside dictionary.
"""
def spellCheck(test, dictionary):
return True if test in dictionary else False

"""
test: Tests our spell check.
"""
def test():
words = stripWords()
print("Checking apple: "+str(spellCheck("apple",words)))
print("Checking kite: "+str(spellCheck("kite",words)))
print("Checking zebra: "+str(spellCheck("zebra",words)))
print("Checking nite: "+str(spellCheck("nite",words)))
test()

Output:

Checking apple: True
Checking kite: True
Checking zebra: True
Checking nite: False









DefaultDictDemo.py

from collections import defaultdict
"""
A default dict is a dict where the value is a
specified data type. In our case we are going to have
a dictionary be that specific data type. This is useful
for representing graphs. A graph data structure has edges and weights. For example, we are going
to graph cities and the weights will be the distance between those cities.
"""
cities = defaultdict(dict)
#our default value is a dict

#say we want to graph distances from
#L.A. to various other cities
print("Populating graph")
for dest, dist in ("Portland", 963.4), ("Sacramento",361):
cities["Los Angeles"][dest] = dist
print(cities)
#now we have the distances from L.A. to two
#different cities, we can make the tuples
#three elements long in order to
#for our for loop to be even more general
#or you could use this technique to read from
#a file and start mapping yourself
print('Printing cities["Los Angeles"]')
print(cities["Los Angeles"])
print('Printing cities["Los Angeles"]["Portland"]')
print(cities["Los Angeles”]["Portland"])

Output:

Populating graph
defaultdict(<type 'dict'>, {'Los Angeles': {'Sacramento': 361, 'Portland': 963.4}})
Printing cities["Los Angeles"]
{'Sacramento': 361, 'Portland': 963.4}
Printing cities["Los Angeles"]["Portland"]
963.4











ChemicalElement.py

"""
ChemicalElement: A class that represents
an individual element.
"""
class ChemicalElement:

"""
Constructor: Initializes name to n, mass to m,
and number to num.
"""
def __init__(self, n, m, num):
self.name = n
self.number = num
self.mass = m

"""
Go ahead and add the setters, getters, and any
other useful functions you think an element
should have.
"""

"""
display: Prints a representation of this element.
"""
def display(self):
print("Name: "+str(self.name))
print("\tAtomic Number: "+str(self.number))
print("\tAtomic Mass: “+str(self.mass))





















PeriodicTable.py

#!/usr/bin/python
from ChemicalElement import ChemicalElement
"""
PeriodicTable: A program to start mapping
out the periodic table. You could convert this
to read in from a file for some great practice.
"""
def periodicTable():
#you could convert this to
#read in from a file and
#store in a tuple, so it is
#immutable in order to have
#all the elements at your disposal
h = ChemicalElement("Hydrogren", 1, 1)
he = ChemicalElement("Helium", 4, 2)
o = ChemicalElement("Oxygen", 16, 8)
elements = []
elements.append(h)
elements.append(he)
elements.append(o)
return elements

listOfElements = periodicTable()
for i in range(len(listOfElements)):
listOfElements[i].display()
"""
Say you had a list of elements organized in a tuple by
atomic number you could access each element to start
building molecules.
Oxygen does not have an atomic number of two so this demo is a
bit off. But you could fix that.
"""
water = [listOfElements[0],listOfElements[0],listOfElements[2]]
print("")
print("Printing H2O: ")
for i in range(len(water)):
water[i].display()













Output:

Name: Hydrogren
Atomic Number: 1
Atomic Mass: 1
Name: Helium
Atomic Number: 2
Atomic Mass: 4
Name: Oxygen
Atomic Number: 8
Atomic Mass: 16

Printing H2O:
Name: Hydrogren
Atomic Number: 1
Atomic Mass: 1
Name: Hydrogren
Atomic Number: 1
Atomic Mass: 1
Name: Oxygen
Atomic Number: 8
Atomic Mass: 16































BankAccount.py

"""
BankAccount: A class to keep track
or your funds. The only major thing this program
is missing is checks to make sure you are not withdrawing too much,
that you are depositing a positive number, and initial
balance is greater than zero
"""
class BankAccount:
"""
Constructor: Constructs a BankAccount
with balance set to initialBalance
"""
def __init__(self, initialBalance):
self.balance = initialBalance

"""
deposit: Deposits money into this BankAccount
"""
def deposit(self, money):
self.balance += money

"""
withdraw: Withdraws money into this BankAccount
"""
def withdraw(self, money):
self.balance -= money

"""
display: Displays the balance in this
BankAccount
"""
def display(self):
print("Balance: $"+str(self.balance))
















BankAccountDemo.py

#!/usr/bin/share
from BankAccount import BankAccount
"""
BankAccountDemo: Exercises and tests our BankAccount
class. The bank account class is missing some exception
handling but it would be good practice for you to add those
in.
"""
def test():
myAccount = BankAccount(100)
#fix so you can have initial amount < 0
print("Initial Balance:")
myAccount.display()

#fix so you can not deposit a negative number
print("Balance after $1000 deposit:")
myAccount.deposit(1000)
myAccount.display()

#fix so you can not deposit a negative number
print("Balance after $1099 withdrawal:")
myAccount.withdraw(1099)
myAccount.display()
test()

























FibRecursion.py

"""
FibRecursion: More practice with recursion.
Generates fibonacci numbers up to a specified
index.
"""

"""
fibonacci: Generates n fibonacci numbers
recursively.

fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)
"""
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1)+fibonacci(n-2)

"""
test: Tests our recursive fibonacci
function
"""
def test():
for i in range(15):
print("fib["+str(i)+"]: "+str(fibonacci(i)))
test()

Output:

fib[0]: 0
fib[1]: 1
fib[2]: 1
fib[3]: 2
fib[4]: 3
fib[5]: 5
fib[6]: 8
fib[7]: 13
fib[8]: 21
fib[9]: 34
fib[10]: 55
fib[11]: 89
fib[12]: 144
fib[13]: 233
fib[14]: 377



Knight.py

"""
Knight: A class that creates a knight character in which
to battle with in the arena. Knights have medium health,
low power, medium critical, and high defense. You could
modify this however you want, like making the stats random,
or creating a special type of knight.
"""
class Knight:

"""
Constructor: Summons a Knight
"""
def __init__(self):
#health in between 0 and 100
self.health = 75
#power is how much damage you do
#in between 0 - 10
self.power = 3
#defense is how much damage you block
#in between 0 - 5
self.defense = 5
#critical is your chance to strike
# a critical hit, critical does 2x damage
self.critical = 3
#for critical to strike
#we will generate a random number in between 0 -9
#if self.critical is greater than that number
#we strike as a critical

#since we have a high health we want to
#promote this with special equipment,
#like potions, 3 potions
self.potions = [1,2,3]

"""
strike: Strikes enemy
"""
def strike(self, enemy):
enemyDefense = enemy.defense
enemy.health -= (self.power - enemyDefense)

"""
hasPotion: Returns true is potion size is
greater than 0
"""
def hasPotion(self):
return True if len(self.potions)>0 else False



"""
usePotion: Use a defense potion, increases defense
by 4.
"""
def usePotion(self):
if self.hasPotion():
self.defense += 4
self.potions.pop()
else:
print("No More Potions")



"""
displayHealth: Prints self.health
"""
def displayHealth(self):
print("Health: "+ str(self.health))



































Wizard.py

"""
Wizard: A class that creates a wizard character in which
to battle with in the arena. Wizards have high health,
medium power, medium critical, and low defense. You could
modify this however you want, like making the stats random,
or creating a special type of wizard
"""
class Wizard:

"""
Constructor: Summons a Wizard
"""
def __init__(self):
#health in between 0 and 100
self.health = 100
#power is how much damage you do
#in between 0 - 10
self.power = 5
#defense is how much damage you block
#in between 0 - 5
self.defense = 1
#critical is your chance to strike
# a critical hit, critical does 2x damage
self.critical = 3
#for critical to strike
#we will generate a random number in between 0 -9
#if self.critical is greater than that number
#we strike as a critical

#since we have a high health we want to
#promote this with special equipment,
#like potions, 3 potions
self.potions = [1,2,3]

"""
strike: Strikes enemy
"""
def strike(self, enemy):
enemyDefense = enemy.defense
enemy.health -= (self.power - enemyDefense)

"""
hasPotion: Returns true is potion size is
greater than 0
"""
def hasPotion(self):
return True if len(self.potions)>0 else False



"""
usePotion: Use a health potion, health potions
restore 75 health
"""
def usePotion(self):
if self.hasPotion():
self.health += 75
self.potions.pop()
else:
print("No More Potions")



"""
displayHealth: Prints self.health
"""
def displayHealth(self):
print("Health: "+ str(self.health))



































Orc.py

"""
Orc: A class that creates an orc character in which
to battle with in the arena. Orcs have medium health,
high power, low critical, and medium defense. You could
modify this however you want, like making the stats random,
or creating a special type of wizard
"""
class Orc:

"""
Constructor: Summons an Orc
"""
def __init__(self):
#health in between 0 and 100
self.health = 75
#power is how much damage you do
#in between 0 - 10
self.power = 10
#defense is how much damage you block
#in between 0 - 5
self.defense = 3
#critical is your chance to strike
# a critical hit, critical does 2x damage
self.critical = 1
#for critical to strike
#we will generate a random number in between 0 -9
#if self.critical is greater than that number
#we strike as a critical

#since we have a high power we want to
#promote this with special equipment,
#like potions, 3 potions
self.potions = [1,2,3]

"""
strike: Strikes enemy
"""
def strike(self, enemy):
enemyDefense = enemy.defense
enemy.health -= (self.power - enemyDefense)

"""
hasPotion: Returns true is potion size is
greater than 0
"""
def hasPotion(self):
return True if len(self.potions)>0 else False



"""
usePotion: Use a power potion, power potions
increase power permanently by 10 points.
"""
def usePotion(self):
if self.hasPotion():
self.power += 10
self.potions.pop()
else:
print("No More Potions")



"""
displayHealth: Prints self.health
"""
def displayHealth(self):
print("Health: "+ str(self.health))



































Elf.py

"""
Elf: A class that creates an elf character in which
to battle with in the arena. Elves have medium health,
low power, high critical, and medium defense. You could
modify this however you want, like making the stats random,
or creating a special type of wizard
"""
class Elf:

"""
Constructor: Summons an Elf
"""
def __init__(self):
#health in between 0 and 100
self.health = 75
#power is how much damage you do
#in between 0 - 10
self.power = 3
#defense is how much damage you block
#in between 0 - 5
self.defense = 3
#critical is your chance to strike
# a critical hit, critical does 2x damage
self.critical = 5
#for critical to strike
#we will generate a random number in between 0 -9
#if self.critical is greater than that number
#we strike as a critical

#since we have a high health we want to
#promote this with special equipment,
#like potions, 3 potions
self.potions = [1,2,3]

"""
strike: Strikes enemy
"""
def strike(self, enemy):
enemyDefense = enemy.defense
enemy.health -= (self.power - enemyDefense)

"""
hasPotion: Returns true is potion size is
greater than 0
"""
def hasPotion(self):
return True if len(self.potions)>0 else False



"""
usePotion: Use a critical potion, increases critical
by 2.
"""
def usePotion(self):
if self.hasPotion():
self.critical += 2
self.potions.pop()
else:
print("No More Potions")



"""
displayHealth: Prints self.health
"""
def displayHealth(self):
print("Health: "+ str(self.health))



































Arena.py

#!/usr/bin/python
from Orc import Orc
from Knight import Knight
from Wizard import Wizard
from Elf import Elf
"""
Arena: An arena to battle Knights, Orcs, Elves,
and Wizards. The game needs to be completed, it also
needs a user interface, a computer player, and more
rules. However this is just a test to make sure everything
is working so far.
"""
def battle():
orc = Orc()
knight = Knight()

print("Knight.defense before potion: "+str(knight.defense))
knight.usePotion()
print("Knight.defense after potion: "+str(knight.defense))

print("Orc.power before potion: "+str(orc.power))
orc.usePotion()
print("Orc.power after potion: "+str(orc.power))

print("Orc.health before strike: "+str(orc.health))
knight.strike(orc)
print("Orc.health after strike: "+str(orc.health))

print("Knight.health before strike: "+str(knight.health))
orc.strike(knight)
print("Knight.health after strike: "+str(knight.health))

print("Knight Power: "+str(knight.power))
print("Orc Defense: "+str(orc.defense))
battle()

Output:

Knight.defense before potion: 5
Knight.defense after potion: 7
Orc.power before potion: 10
Orc.power after potion: 20
Orc.health before strike: 75
Orc.health after strike: 75
Knight.health before strike: 75
Knight.health after strike: 62
Knight Power: 3
Orc Defense: 3

Cards.py

from random import randrange as rand
"""
Cards: Creates a deck of cards. Contains
a function to sort the deck as well.
"""
"""
cards: Generates a deck of cards. h is hearts,
a is aces, d is diamonds, and s is spades.
"""
def cards():
cards = []
for i in range(4):
for j in range(2,11):
if(i == 0):
cards.append((str(j), "Heart"))
if(i == 1):
cards.append((str(j), "Diamond"))
elif(i == 2):
cards.append((str(j), "Spade"))
elif(i == 3):
cards.append((str(j), "Club"))

cards.append(("Jack", "Heart"))
cards.append(("Queen", "Heart"))
cards.append(("King", "Heart"))
cards.append(("Ace", "Heart"))
cards.append(("Jack", "Diamond"))
cards.append(("Queen", "Diamond"))
cards.append(("King", "Diamond"))
cards.append(("Ace", "Diamond"))
cards.append(("Jack", "Spade"))
cards.append(("Queen", "Spade"))
cards.append(("King", "Spade"))
cards.append(("Ace", "Spade"))
cards.append(("Jack", "Club"))
cards.append(("Queen", "Club"))
cards.append(("King", "Club"))
cards.append(("Ace", "Club"))
return cards











"""
shuffle: Shuffle a deck of cards.
"""
def shuffle(deck):
#lets shuffle 10000 times
for i in range(10000):
randomIndex = rand(0,len(deck))
for i in range(len(deck)):
temp = deck[randomIndex]
deck[randomIndex] = deck[i]
deck[i] = temp
return deck









































BlackJack.py

#!/usr/bin/python
from Cards import *
"""
BlackJack: The beginning to a BlackJack game.
Exercises the Cards.py file.
"""

"""
deal: Gives players two cards.
"""
def deal(players, deck):
for i in range(len(players)):
players[i].append(deck.pop())
for i in range(len(players)):
players[i].append(deck.pop())

"""
game: A small game of Black Jack
Each player starts with 100 chips.
In black jack you play against dealer.
We will need to add this aspect later
"""
def game():
deck = shuffle(cards())
players = [["PlayerOne",100], ["playerTwo", 100]]
deal(players, deck)
print(players[0][0])
print("\tChips: "+str(players[0][1]))
print("\tCard One: "+ str(players[0][2]))
print("\tCard Two: "+str(players[0][3]))

print(players[1][0])
print("\tChips: "+str(players[1][1]))
print("\tCard One: "+ str(players[1][2]))
print("\tCard Two: "+str(players[1][3]))

game()

Output:

PlayerOne
Chips: 100
Card One: ('Ace', 'Spade')
Card Two: ('Jack', 'Spade')
playerTwo
Chips: 100
Card One: ('5', 'Spade')
Card Two: ('Jack', ‘Heart')

FlashCards.py

"""
FlashCards: Stores flash cards inside a dictionary.
To use later in a flash card player
"""
sampleCards = {"Card One":"Apple",
"Card Two":"Zebra"}
"""
you can put as many flash card sets in here as you like.
Math flash cards, computer science flashcards...
“""







































FlashCardPlayer.py


#!/usr/bin/python
from flashcards import *
from random import randint
"""
Runs a set of flashcards to review.
The answer have to be exact. The player
is case sensitive.
"""
def main():
print("---Welcome to FlashCard Player---")
cards = sampleCards.items()
count = 0
while(len(cards)>0):
count +=1
index = randint(0, len(cards)-1)
side = randint(0,1)
oppositeSide = 0 if (side/1) is 1 else 1

print("What is on the back of this card")
print(cards[index][side])

if input("---> ") == cards[index][oppositeSide]:
print("Correct")
del cards[index]
else:
print("Incorrect, the answer was: ")
print(cards[index][oppositeSide])

print("----Game Over---")
print("That took "+str(count)+" tries.")

main()

















Output:

---Welcome to FlashCard Player---
What is on the back of this card
Zebra
---> "Apple"
Incorrect, the answer was:
Card Two
What is on the back of this card
Zebra
---> "Card Two"
Correct
What is on the back of this card
Card One
---> "Apple"
Correct
----Game Over---
That took 3 tries.





























Conclusion
In conclusion, we have only scratched the surface with these examples.
However, now you have a great base on which to build. So get out there and start
building, breaking, and having fun with your own code. Please check out my
website for more information:

tfoss0001.github.io

For fun and interactive video tutorials check out my youtube channel:

DoEasy Productions

There are playlists on that channel to help guide you through these examples
and to give you ideas for your own programs. Thank you very much.

-Torin Foss

Вам также может понравиться