Thursday, March 27, 2014

Exercise 8: While loops (rock, paper, scissors)

Exercise

Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input), compare them, print out a message of congratulations to the winner, and ask if the players want to start a new game)
Remember the rules:
  • Rock beats scissors
  • Scissors beats paper
  • Paper beats rock

Discussion

Concepts for this week:
  • While loops
  • Break statements

While loops

We have already discussed for loops, or loops that look sequentially (one by one) at elements in a list. There is a second type of loop that works in a slightly different way called a while loop.
The idea is simple: while a certain condition is True, keep doing something. For example:
a = 5
while (a > 0):
    print(a)
    a -= 1
The output of this code segment is:
5
4
3
2
1
A particularly useful way to use while loops is checking user input for correctness. For example:
quit = input('Type "enter" to quit:' )
while quit != "enter":
    quit = input('Type "enter" to quit:' )
The uses for this are infinite, and can (and should!) be combined with conditionals to yield the most efficient results.

Break statements

A break statement stops the execution of a loop before the original condition is met. While the use of a break statement will often start an argument about good coding practices, sometimes it is useful.
For example:
while True: 
    usr_command = input("Enter your command: ")
    if usr_command == "quit":
        break
    else: 
        print("You typed " + usr_command)
In this case, the break statement is used to break off the "infinite while loop" that we have constructed with the while True statement.

Happy coding!
Forgot how to submit exercises?

SOLUTION Exercise 7: list comprehensions

Exercise

Let's say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it.

Sample solutions

For the meat of the solution, check this out:

And for a "complete" solution, look at this:

For a solution that uses the random library to generate test lists, check this out:

Wednesday, March 19, 2014

Exercise 7: List comprehensions

Exercise

Let's say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it.

Discussion

Concepts for this week:
  • List comprehensions


List comprehensions

The idea of a list comprehension is to make code more compact to accomplish tasks involving lists. Take for example this code:
years_of_birth = [1990, 1991, 1990, 1990, 1992, 1991]
ages = []
for year in years_of_birth: 
    ages.append(2014 - year)
And at the end, the variable ages has the list [24, 23, 24, 24, 22, 23]. What this code did was translate the years of birth into ages, and it took us a for loop and an append statement to a new list to do that.

Compare to this piece of code:
years_of_birth = [1990, 1991, 1990, 1990, 1992, 1991]
ages = [2014 - year for year in years_of_birth]
The second line here - the line with ages is a list comprehension.

It accomplishes the same thing as the first code sample - at the end, the ages variable has a list containing [24, 23, 24, 24, 22, 23], the ages corresponding to all the birthdates.

The idea of the list comprehension is to condense the for loop and the list appending into one simple line. Notice that the for loop just shifted to the end of the list comprehension, and the part before the for keyword is the thing to append to the end of the new list.

Try it yourself!

Forgot how to submit exercises?

SOLUTION Exercise 6: String lists

Exercise

Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.)

Sample solution

Wednesday, March 12, 2014

Exercise 6: Strings as lists

Exercise

Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.)

Discussion

Concepts for this week:

  • List indexing
  • Strings are lists

List indexing

In Python (and most programming in general), you start counting lists from the number 0. The first element in a list is "number 0", the second is "number 1", etc.

As a result, when you want to get single elements out of a list, you can ask a list for that number element:

>>> a = [5, 10, 15, 20, 25]
>>> a[3]
20
>>> a[0]
5

There is also a convenient way to get sublists between two indices:

>>> a = [5, 10, 15, 20, 25, 30, 35, 40]
>>> a[1:4]
[10, 15, 20]
>>> a[6:]
[35, 40]
>>> a[:-1]
[5, 10, 15, 20, 25, 30, 35]

The first number is the "start index" and the last number is the "end index."

You can also include a third number in the indexing, to count how often you should read from the list:

>>> a = [5, 10, 15, 20, 25, 30, 35, 40]
>>> a[1:5:2]
[10, 20]
>>> a[0:3:-1]
[15, 10, 5]

To read the whole list, just use the variable name (in the above examples, a), or you can also use [:] at the end of the variable name (in the above examples, a[:]).

Strings are lists

Because strings are lists, you can do to strings everything that you do to lists. You can iterate through them:

string = "example"
for c in string: 
    print "one letter: " + c

Will give the result:

one letter: e
one letter: x
one letter: a
one letter: m
one letter: p
one letter: l
one letter: e

You can take sublists:

>>> string = "example"
>>> s = string[0:5]
>>> print s
exam

Now s has the string "exam" in it.

Moral of the story: a string is a list.

Happy coding!

Forgot how to submit exercises?

SOLUTION Exercise 5: list overlap

Exercise

Take two lists, say for example these two:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes.

Sample solution

Wednesday, March 5, 2014

Exercise 5: list overlap

Exercise

Take two lists, say for example these two:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes.

Extras:

  1. Randomly generate two lists to test this
  2. Write this in one line of Python (don't worry if you can't figure this out at this point - we'll get to it soon)

List properties

In other words, "things you can do with lists."

One of the interesting things you can do with lists in Python is figure out whether something is inside the list or not. For example:

>>> a = [5, 10, 15, 20]
>>> 10 in a
True
>>> 3 in a
False

You can of course use this in loops, conditionals, and any other programming constructs.

list_of_students = ["Michele", "Sara", "Cassie"]

name = input("Type name to check: ")
if name in list_of_students:
    print("This student is enrolled.")
Forgot how to submit exercises?

SOLUTION Exercise 4: divisors

Exercise

Create a program that asks the user for a number and then prints out a list of all the divisors of that number. (If you don't know what a divisor is, it is a number that divides evenly into another number. For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)

Sample solution

There were a number of tricky things with this exercise. First, the type conversions between input strings and integers for the range() function need to be carefully output. Second, the arguments to range() had to be carefully constructed to cover all the possible numbers. Third, the condition in the if statement had to be correct as well.