Friday, September 30, 2011

LPTHW Exercise 44

In this exercise we take the code written in exercise 43 and comment it.

There is still plenty of scope for improvement, such as proper super class and subclass relationships between individual rooms and a proposed Room superclass.

Here's the code.

LPTHW Exercise 43

In this exercise I have made a game. The program is not perfect, but it works well. I still need to refactor it for the following:

1. Use proper class..subclass relationships. For example SpacedRepitition should be a subclass of another class called Room

2. Add proper documentation

3. Use proper coding standards

I will address most of these issues in the next exercise

Thursday, September 29, 2011

LPTHW Exercise 42

In this exercise we re-create the Gothons game with classes instead of "functions and maps"

The getattr function is used to obtain an attribute from an object using a String to identify the needed attribute. Ref [1]

Wednesday, September 28, 2011

LPTHW Exercise 41

Gosh, I honestly could not type this in. Copy paste...

LPTHW Exercise 40

In this exercise we learn about Maps. They are also called 'dictionary' in Python. An interesting thing we do in this exercise is putting a function in the map.

LPTHW Exercise 39

In this exercise we do some stuff with lists...




Tuesday, September 27, 2011

LPTHW Exercise 37

Keywords

  • and - Logical AND operation
  • del- Deletes objects. These objects could be local variables, or even elements from a list. - References [1] [2]
  • from - Used for importing elements from modules
  • not - The logical NOT operation
  • while - Used for looping until the condition in while remains true
  • as - When used with the 'import' statement, the as keyword is used to rename the bound object. It can also be used with the 'with' statement... though I am not sure what that statement does.
  • elif - 'else if'
  • global - This causes a local variable to be visible outside of it's scope. Ref [1]
  • or - The logical OR operation
  • with - This seems like a more convenient alternative to try...finally when there is a setup, execution, and teardown cycle to be performed. Ref [1]
  • assert - The 'assert' statement is used to put error checking in your code. It seems to be very similar to what 'assert' does in Java
  • else - 'else' part of a conditional
  • if - Conditional
  • pass - The 'pass' statement does nothing. It is used when a statement is required syntactically, but nothing needs to be done. Ref [1]
  • yield - The yield statement causes a function to return a generator. When this generator is run, it will return a value specified by the yield statement and will do so every time it is run until the function runs out of values. This is also akin to continuations. Ref [1]. Do generators always return iterables ?
  • break - The 'break' statement breaks out of the immediately enclosing 'for' or 'while' loop. Ref [1]
  • except - The 'except' keyword is used as a counterpart to the 'try' keyword. It has a similar function to the 'catch' keyword in Java. Ref [1]
  • import - Used for importing modules and their elements
  • print - Used for printing something to the console
  • class - Used for defining a class
  • exec - Supports dynamic execution of Python code
  • in - The inclusion operator
  • raise - Raising an exception
  • continue - Continue back to the start of the loop
  • finally - The cleanup block after a try...except statement. Ref [1]
  • is - Used to determine if two values are stored in the same memory location. Ref [1]
  • return - Used to return a value from a function
  • def - Keyword used to define a function
  • for - The for loop
  • lambda - Used to create small anonymous functions. Ref [1]
  • try - Used to enclose code which could throw Exceptions. It must be followed by an 'except' statement.
Notes:
This webpage says that the 'del' keyword deletes objects. What exactly does that mean? Does it delete objects from lists, sequences, etc, or does it also delete objects from within other objects, or entire objects ?

Data Types

For data types, write out what makes up each one. For example, with strings write out how you create a string. For numbers write out a few numbers.

  • True - The boolean true value
  • False - The boolean false value
  • None - Represents nothing... looks like it is similar to the 'null' keyword in Java
  • strings - The string datatype which is a sequence of characters
  • numbers - Python supports several numeric data types
  • floats - Represents floating point numbers as per the IEEE 854-1987 standard
  • lists - An ordered collection of items

String Escapes Sequences

For string escape sequences, use them in strings to make sure they do what you think they do.

  • \\ - Result is a single backslash
  • \' - Result is the ' character
  • \" - Result is the " character
  • \a - Result is the ASCII bell
  • \b - ACSII backspace
  • \f - ASCII formfeed
  • \n - ASCII linefeed
  • \r - ASCII carriage return
  • \t - ASCII horizontal tab
  • \v - ASCII vertical tab

String Formats

Same thing for string formats: use them in some strings to know what they do.

  • %d - signed decimal
  • %i - signed integer decimal
  • %o - signed octal value
  • %u - Obsolete type now... identical to %d
  • %x - Signed hexadecimal lowercase
  • %X - Signed hexadecimal uppercase
  • %e - Floating point exponential format (lowercase)
  • %E - Floating point exponential format (uppercase)
  • %f - Floating point decimal format
  • %F - Floating point decimal format
  • %g - Floating point format. Uses lowercase format if exponent is less than -4 or not less than precision. Decimal otherwise
  • %G - Floating point format. Uses uppercase format if exponent is less than -4 or not less than precision. Decimal otherwise
  • %c - Single character. Accepts integer or single character string
  • %r - Any Python object
  • %s - String
  • %% - Results in the % character... no argument is converted

Operators

Some of these may be unfamiliar to you, but look them up anyway. Find out what they do, and if you still can't figure it out, save it for later.

  • + - addition operator
  • - - subtraction operator
  • * - multiplication operator
  • ** - The power operator. a ** b will give a to the power b
  • / - The division operator
  • // - Floor division. 9 //2 is 4
  • % - Modulus operator
  • < - Less than
  • > - Greater than
  • <= - Less than equal to
  • >= - Greater than equal to
  • == - Equality
  • != - Not equal to
  • <> - Not equal to
  • ( ) - Parenthesis for defining proper precedence
  • [ ] - Used for defining lists
  • { } - Used for defining maps ?
  • @ - Decorator
  • , - Used to separate values in a tuple
  • : - Used to delimit the key and value in map entries
  • . - Used to identify a method on a referenced object or module
  • = - Assignment operator
  • ; - Combines multiple statements into one. See [1]
  • += - Add and assign (the ones below are similar... do something and assign)
  • -=
  • *=
  • /=
  • //=
  • %=
  • **=

LPTHW Exercise 36

In this exercise I created a simple text based game. This game consists of countries and capitals. A user is flown to a country, where the immigration officer asks them the name of the capital. If you answer correctly, you get a point, if you answer incorrectly you do not get any points. The game quits when the user has correctly guessed the capitals of all the countries, or if they type CTRL-C.

Stuff I learned:
  • How to generate a random number in Python
  • How to get the length of a list
  • We can nest lists within lists
  • A function can return multiple values
  • The main function has a really strange syntax
  • The ++ increment operator is not supported in Python
  • Making a simple game is fun




LPTHW Exercise 35

In this exercise we use branches in functions.

LPTHW Exercise 34

In this exercise we learn how to get elements from a list.

animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']

print "The first animal is %s" % animals[0]

I did not create any Python files for this exercise. Did it in the console.

LPTHW Exercise 33

Completed exercise 33. In this exercise we learn about the while loop in Python.

LPTHW Exercise 32

In this exercise we work with lists. A list is an ordered collection of items. We can iterate through all the items in a list, using a for..in loop. A range generates a list in an arithmetic progression. We can add elements to a list using the 'append' statement.

LPTHW Exercise 31

So far we used if..elif to print different things based on some values. But in real programs, we usually use conditions to make decisions based on user input. In this exercise, we take user input and make decisions based on it.

LPTHW Exercise 30

In this exercise, we learned how to use if...elif

LPTHW Exercise 29

Completed exercise 29. This exercise covered the 'if' statement in Python.

Some learnings:
  1. The if statement does not need () after it
  2. Should end with ':'
  3. Since it is a block, it's contents should be indented
Here is the code.

LPTHW Exercise 28

In this exercise we work with boolean and equality operators in Python. Interestingly Python uses the words 'and' 'or' 'not' for boolean operators, instead of '&&' '||'. Python also uses the words 'True' and 'False' to denote the boolean types true, and false respectively.

I completed the exercise which was to evaluate some logic statements and correctly guess what the answer should be.

For extra credits I also checked out the equality operators in Python. Here's the list:

== Equal to
!= Not equal to
<> Not equal to
< Less than
> Greater than
<= Less than equal to
>= Greater than equal to

While looking at the page describing Python operators, I came across membership operators, which I found quite interested. Python has two membership operators which can work with sequences such as lists, tuples, and strings.

LPTHW Exercise 27

Exercise 27 is about logic and truth tables. Since I have been programming for a while, I am familiar with this, and am skipping the exercise.

LPTHW Exercise 26 - Test

This is a simple test, where we are given a file with broken code, and we have to fix it. I fixed the file and tested it. Not including it to avoid spoiling anyone's experience.

LPTHW Exercise 25

Exercise 25 is an "even more practice exercise"

In this exercise we practice writing and using functions.

Stuff I learned:
  • We can pop an element from a list, and when we do that the element is removed from the list
  • We can split a String based on a delimiter
  • We can use the sort function to sort a list



Monday, September 26, 2011

Exercise 24 - More Practice

Completed exercise 24. This was a recap of some of the concepts covered till now. We recapped how to use different quotes in strings. We also learned how to format Strings using format character, we recapped how to define and use functions.




Friday, September 23, 2011

Exercise 23 - Read some code

For this exercise, we have to read some code and try to make sense of it. I have picked up 3 samples and will read each one of them.

  1. skills.py
  2. cookme_recipes.py
  3. Game of life
I read through the first two examples. The proved to be a very good starting point. They worked mostly with maps, creating them, getting keys, creating maps where the value is yet another map, etc.

The third one gameoflife.py is an implementation of Conways Game of Life in Python.

Completed reading it. This Python files used classed, functions, and a main function also. Nice experience, I will recommend that everyone try this exercise sincerely.


Exercise 22 - What do you know so far ?

In this exercise I am going to read through all the stuff I have done so far in the course, and then I will make a table of all the symbols, keywords, and concepts encountered in the course thus far.

# Used to comment a single like
+ Addition symbol
- Subtraction symbol
/ Division symbol
* Multiplication symbol
% Modulus symbol
< Less than symbol
> Greater than symbol
<= Less than equal to symbol
>= Greater than equal to symbol
= Assignment symbol
\ Escape character

* Can also precede an argument name given to a function. In this case it means that this variable will accept all the input given to the function as a list


def A keyword used to define functions
import Used to import a module or a symbol from a module

argv Is a symbol from the 'sys' module which contains all the command line arguments passed to a Python script, starting with the name of the script itself

print Prints the specified values to the standard console
raw_input Accepts raw input from a user from the standard console
open(filename) Opens a file and returns a handle to it. By default this function will open the file in read mode, but we can specify a mode and open it for writing, etc
read() A function which can be called on a file handle to read the contents of a file
close() A function which can be called on a file handle to close the file and free up resources on the OS
truncate() A function which can be called on a file handle to remove existing contents of a file to either the current position of the file pointer, or if we provide a size argument then it will be truncated to that size
write() A function which can be called on a file pointer to write to the file
exists() A function which takes a file pointer and determines if that file exists
len() A function which takes data and tells us the size of that data. It accepts a sequence or a mapping


Stuff I learned:
  1. In Python we use the 'print' function to print to the console
  2. In Python function calls need not have () like in Java
  3. In Python we use the '#' character to comment a single line. The C style comment '//' does not work in Python
  4. We do not have to end a statement with a ';' or any delimiter in Python
  5. Python Strings can be delimited by double quotes as well as single quotes
  6. A double quoted string can contain single quotes
  7. It is not compulsory to have a main method in Python
  8. The print function can take multiple arguments separated by ','
  9. When we give multiple values to the print function, it automatically puts a space in between them
  10. Since Python is dynamically typed, we do not need to specify the type of variables, nor do we need any special syntax like 'var' to define variable names
  11. When doing math operations in Python, if all the operands are integers, then the result will also be an Integer. If the operation is a division operation, then the result will be truncated to yield an Integer. However, if even one of the operands is a float, then all operands will be promoted to floating point numbers and the result will also be a float
  12. Python supports formatting of Strings with the % character
  13. There are many formatting characters in Python. %r is one of them. It will print the String representation of any object, by calling the repr() method of that object
  14. When we use %r for formatting, it surrounds the String between ''
  15. We can multiply a String with a number, such as "." * 10 - This will concatenate the String 10 times
  16. Strings can also be concatenated with the + operator
  17. We can specify triple quoted Strings. These can span multiple lines, and can also contain single and double quotes
  18. When we print something with the print statement, it automatically appends a newline character to the String when it is printed. We can override this functionality by ending the print with a ','
  19. raw_input("prompt") can also be given a String which will be used as a prompt
  20. In Python we can unpack a list into multiple variables by assigning a list to multiple variables (see ex13.py)
  21. If we type CTRL-C on the console when the program is expecting input, it results in a KeyboardInterrupt and the program will exit
  22. In Python functions do not have to be delimited with {}. Rather there contents are indented, and the function ends when the indentation comes back to the level before the function


LPTHW - Exercise 21

In this exercise we learn how to return values from functions.





Wednesday, September 14, 2011

LPTHW - Exercise 20

In this exercise, we combine functions and files. We create some functions to operate on files.

New things I learned:
1. We can use the seek() function on a file handle to take the file cursor to a particular position in the file
2. We can give multiple strings to the print function by separating them by a ','

LPTHW - Exercise 19

In this exercise, we reinforce the things we learned in the previous exercise on functions. We also learn that variables inside a function are not connected to the variables outside the functions (scope).

LPTHW - Exercise 18

In this exercise, we learn how to define functions. Functions can be thought of as creating custom commands.

We use the 'def' keyword to create functions. The function's body needs to be indented with the same number of spaces in every line.

We can accept a parameter called *args (args can be replaced with anything else). This I believe takes a list of parameters which can be unpacked into multiple arguments as seen in the function 'print_two'

LPTHW - Exercise 17

In this exercise we will copy the contents of one file to another. In a past exercise, we learned how to read the contents of a file, and in another past exercise we learned how to write to a file. In this exercise, we will read the contents of one file and write it to another file.

The new things I learned in this exercise are:
1. We can use the exists() function to find out if a file exists
2. We can use the len() function to determine the size of data in a file=

Tuesday, September 13, 2011

LPTHW - Exercise 16

In the previous exercise we read the contents of a file. In this exercise we are going to read and write files.

We will open a file in the 'w' mode and then truncate it. Then we accept three lines of input from the user, and append them to the file.



Extra Credit:

In the next example, we comment most of the lines of the solution and also reuse the prompt by using replacement characters.



We need not have called truncate on the fp, since opening a file in 'w' mode automatically truncates it.

Monday, September 12, 2011

LPTHW - Exercise 15

In this exercise, we will read the contents of a file and print them to the console.



Notes:

We use the open(filename) function to get a file handle, and then we use the read() function of the file handle object to read the contents of the file as a string.

I am sure there is a different way to read a binary file, and I am also sure there should be a way to buffer the input in case the file is very large, but read is the simplest way to get the job done. This is much better than Java where we have to jump through tons of hoops to read a file.

LPTHW - Exercise 14

In this exercise we use a value from the command line input to prompt the user.



Questions:

1. The unpacking thing seems to basically work with lists on the RHS and a bunch of variables on the LHS. Not sure if that is right. Will have to find out.

LPTHW - Exercise 13

In this exercise we will learn how to accept command line arguments.



In the script above in the first line we import the 'argv' variable from the 'sys' module. This variable will hold the name of the script and all command line arguments given to it.

We unpack these values and assign them to the variables on the LHS.

Questions:
1. Does importing argv make is available, or does it also turn on the function of accepting command line arguments?

2. Here we assign the values to the variables on the LHS. However, we need to be sure that the command line parameters and the number of variables are the same. This is not always possible, especially when we do not know how many values the user will enter. Perhaps, this issue will be dealt with in a later exercise. I will leave it as is for now, but will try to answer it if it is not dealt with in a later exercise.

LPTHW - Exercise 12

In this exercise, we will provide some text to the raw_input() function as a parameter. This text will be used as the prompt. This is much easier than the previous exercise, where we first printed something (as a prompt) and then asked for input using the raw_input() function.



Extra Credits:

We can read the documentation of any function using the pydoc command. To quit the documentation, press 'q' on the command prompt.

LPTHW - Exercise 11

In this exercise we are going to accept input from the user.



Notes and extra credits:

When we print something with the print statement, it normally ends with a newline. We can prevent the new line by ending the print statement with a ',' as shown in the example above.

The raw_input() function is used to read input from the console. It will read one line of input, and pass it to the program with the ending newline stripped out.

It seems we can load the 'readline' module to provide some elaborate editing and history features.

In the output of the above program, all the instances of %r are replaced by the output of running __repr() on the arguments. The output is always delimited with ''. Since the height also uses a ' within it, it must be escaped.

LPTHW - Exercise 10

In this exercise, we look at some more printing and escape characters. The "\" is the escape character in Python (just like in many other programming languages).



Extra Credit:

Escape characters are used to change the meaning of the character following it. For example \t will print the 'tab' character instead of 't'. All escape sequences supported by Python are listed on this page from the Python docs.

I tried replacing the triple double quotes in the example above with triple single quotes. When I ran the example, it ran just like the one with triple double quotes. I am not sure if there is any difference between them. Maybe if we use triple single quotes, then we can embed triple double quotes in them.

%s is better for printing because it is replaced by the String value, whereas %r is replaced by what is returned by the __repr function of the object (usually this is surrounded by double quotes).

LPTHW - Exercise 9

In this exercise, we executed some more printing code. The new concept I learned in this exercise, is that we can use triple quotes to represent a string which can span multiple lines.