MEOW + RAWRRR =
Hacking Your Education┋ Indy Book Culture & Arts on Margins┋ Electricity, Electronics, Data Cables & Wireless Networks, Information Technology, Software Development / Testing / Documentation, Metal Craft & Fixing Things┋ Brain, Universe, Evolution, Math: Beautiful Stories in Science ┋ Zines, Comix, Bookfairs, & Rogue Spaces┋BIPOC, Intersectional, & Majority World Feminisms┋Theory vs. Materiality: A (Violent) Geneology of Utopia┋Love's Labor: Lust – Gazing Back at Patriarchy (with Google Glasses)┋Spinsters, Witches, Lesbians, Whores: Bad Girls As Collateral Damage in the Invention of Love & Marriage┋Queer/ Trans/ Crip Cyborg Bio-Hacking┋Transformative Justice: The color of Capitalism is the color of Prison ┋ To Be a Backpacking Taoist: A Nomad's Work of Care & Creativity
Notes 2: Creating my first Python game

Creating my first Python game – objects, expressions, variables, loops, containers, functions


# The following notes are taken from Lecture 2 and Recitation 1 of MIT Open Courseware’s Intro to CS; and the “Python Basics” module in TreeHouse.

game

# Programs are intended to be read by humans, not just executed. That is why we create comments to block out various sections of the script and provide explanations to other coders. These are called comments, and are notated by the symbol #. Blocking and indentation is important in writing code, even if it is necessary for the execution of the code because the visual structure of the program should reflect its semantic structure.

# After writing my first very simple number guessing “game” in Python, I’m finding this way of thinking to be really kind of fun. It requires careful consideration of all the things that can possibly go wrong, and then a very careful way of giving directions to the computer in each error scenario. Although the errors are a bit frustrating, I enjoy the process of critically breaking down each instruction to its most basic logical parts. I have to think more carefully about how to define intermediate objects – that is, how to create variables in for loops to store temporary values, which are necessary to calculate a different value. This is super-cool, and also kind of annoying.

 

========== LECTURE 2: CORE ELEMENTS OF A PROGRAM ==========

IDLE is Python’s Integrated Development Environment (IDE). It facilitates scripting in the Python language via:

  • Text editor that helps with syntax; it does so with features such as automatic indentation, and colors/highlights keywords (which can’t be used as variables)
  • Shell with syntax highlighting
  • Debugger that is integrated into the program (However, must programmers use “print” statements to debug, rather than relying on the integrated debugger in IDLE)

OBJECTS – Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. Every object has an identity, a type and a value.

  • The Type of object tells what kind of object it is and what can be done with it. There are two fundamental types of objects: scalar and non-scalar types.
  • A scalar object is an indivisible object, which means it is the most basic unit of data that can’t easily be broken down into more simple objects. Examples of scalars are: int, float, char, double, boolean
  • A non-scalar object is a set of elements that has internal structure (like a string, which is a set of characters). Examples of non-scalar are strings and lists.

SCALAR OBJECT TYPES

  1. Integers
  2. Floats (these decimals are the computer’s approximations of real numbers)
  3. Boolean (True or False)
  4. None

You can convert one type of object to another type. (Ex. int(3.493) = 3, truncating the floating point number to an integer.)

EXPRESSION – An expression is a sequence of operants and operatorsOperators are the symbols which tells the Python interpreter to do some mathematical or logical operation.

Relational Operators

Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to

Logical Operators

AND , OR, NOT

These relational and logical operators can be evaluated in boolean statements to a True or False.

 

VARIABLE  – Variables are reserved memory locations to store values. You can assign a value to a variable with the expression: “var =   ”

Python 2.0 takes two type of input statements: “raw_input” and “input.” In Python 3.0, only raw_inputs are taken.

Straight line programs are a sequence of commands you execute one after another with no loops. Every command is only executed once. Branching programs consist of various types of looping constructs, so that the program is reiterated until a certain condition is met. A conditional statement (if, else, elif), a while loop, and a for loop are all examples of looping constructs.
# The professor goes into a brief aside about Turing completeness, stating that any function that can be completed, can be completed in a “Turing complete” language. He does not go further into an explanation about Turing completeness, but more information on this very interesting topic can be found here on StackOverflow. 

 

========== BASIC SCRIPTS – EXAMPLES IN CLASS & RECITATION ==========

—1.  If, else, elif —- a simple branching program to show if an inputed number is even or odd —


x = int (raw_input ('Enter an integer  '))
   if x % 2 == 0:
       print 'Even'
   else:
       print 'Odd'
       if x % 3 != 0:
           print 'And not divisible by 3'

 

—2.  While loop —- find the cube root of a perfect cube —

x = input (raw_input ('Enter an integer   '))
ans = 0

while ans * ans * ans < abs(x):
     ans = ans + 1
     print 'current guess =  ',  ans
     if ans * ans * ans != abs(x):
           print x, ' is not a perfect cube'
     else:
           if x<0:
                 ans = -ans
                 print('Cube root of ' + str(x) + ' is ' + str(ans)


—3.  For loop —- “FizzBuzz”: find whether a number is divisible by 3 and/or 5 —

#Print numbers between 1 and 100. For multiples of 3, print “Fizz” instead of the number. For multiples of 5, print “Buzz” instead of the number. For multiples of both 3 and 5, print “FizzBuzz” instead of the number.

for i in range (1, 101):
    s = str(i)

    if i % 3 == 0 or i % 5 == 0:
         s = ' '

    if i % 3 == 0:
         s = s + ' Fizz'

    if i % 5 == 0:
         s = s + ' Buzz'

    print s 

 

#This concactenates (or adds) “Buzz” to “Fizz” when s is divisible by both 3 and 5.

 

========== TREEHOUSE: BASIC PYTHON ==========

CONTAINERS – Containers are any object that holds an arbitrary number of other objects. Generally, containers provide a way to access the contained objects and to iterate over them. Examples of containers include tuple, list, set, dict; these are the built-in containers.

FUNCTIONS –  (from TutorialsPoint) A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

You can define functions to provide the required functionality. Here are simple rules to define a function in Python.

  • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
  • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
  • The first statement of a function can be an optional statement – the documentation string of the function or docstring.
  • The code block within every function starts with a colon (:) and is indented.
  • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

Syntax:

def functionname( parameters ):
   "function_docstring"
   function_suite
   return [expression]


—Some commands learned in this module —

try/except
in
len
round ( )
[ ]
split(list)
join(list)
list.append()
"{ } { }".format( ( ), ( ))
def ( argument ):
return

EOF error “end of file” – I encountered this a lot. This is when the program tried to get more input but all of the lines of input had already been read (used up), causing an error.

#I did not think that this module of Python was very well put together. It jumps around quite a bit, and does not adequately prepare students for any of the questions at the end of each section. However, it was fairly simple to search online forums for hints and solutions to the challenge problems, and I enjoyed the process of querying the web for clues to the puzzles here. That said, this tutorial is not a very good introduction to “basic python” and a complete beginner would require some supplementary texts to be able to do the exercises.

 

— A script created in this module: finding the sum of items in a list —



def add_list(list):
   sum = 0

for num in list:
   sum = sum + num

return sum
print add_list (list)

def summarize(list):
      return "The sum of { } is { }." .format( str(list), sum(list))



— My first game in Python: the Number-Guessing Game —



python
import random

 
#Import the random library in Python. # Figure out what kinds of variables are needed to store temporary values.

rand_num = random.randint(1, 10)
guessed_nums = [ ]
allowed_guesses = 5
 

# Figure out what are the parameters for the inputs, and tell the computer what happens if the player tries to input a value that doesn't fit in the parameters.

while len(guessed_nums) < allowed_guesses:
    guess = input("Guess a number between 1 and 10: ")
    try:
       player_num = int(guess)
    except:
       print ("That's not a whole number!")
    break

    if not player_num > 0 or not player_num < 11:
       print( "That number isn't between 1 and 10!")
       break

# Keep track of the number guesses by adding the number of guesses to the player's number of guesses, the variable which I've just created above.

    guessed_nums.append(player_num)

# What happens if the player guesses the right number, and what happens if (s)he guesses a number that is too high or too low.

    if player_num == rand_num:
         print( "You win! My number was { }.".format(rand_num))
         print( "It took you { } tries." . format(len(guessed_nums)))
         break

    else:
         if rand_nm > player_num:
             print( "Nope! My number is higher than { }. Guess # { }".format(player_num, len(guessed_nums)))
         else:
             print( "Nope! My number is lower than { }. Guess # { }".format(player_nm, len(guessed_nums)))
             continue

# What happens if the player runs out of tries, and never reaches the correct number.

        
     if not rand_num in guessed_nums:
          print( "Sorry! My number was { }.".format(rand_num))

 

 

 

Comments are closed.