Wednesday, February 26, 2014

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.)

Discussion

The topics that you need for this exercise combine lists, conditionals, and user input. There is a new concept of creating lists.
There is an easy way to programmatically create lists of numbers in Python.
To create a list of numbers from 2 to 10, just use the following code:
x = range(2, 11)
Then the variable x will contain the list [2, 3, 4, 5, 6, 7, 8, 9, 10]. Note that the second number in the range() function is not included in the original list.
Now that x is a list of numbers, the same for loop can be used with the list:
for elem in x: 
    print elem
Will yield the result:
2
3
4
5
6
7
8
9
10
Happy coding!
Forgot how to submit exercises?

SOLUTION Exercise 3: lists

Exercise

Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.
Extras:
  1. Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.
  2. Write this in one line of Python.
  3. Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user.

Sample solution

I will note that none of the solutions that were submitted were written in one line of Python. There will be more exercises later that show you how to do this!
Here is a sample solution that solves the exercise, including extras 1 and 3.

Saturday, February 15, 2014

Exercise 3: lists

Followers and friends, I apologize for not posting this week. Sometimes life throws you lemons (or appendicitis) and you need to make lemonade (or spend a few nights in the hospital and have emergency surgery). I am now recovering, and this post will be up for a week and a half. Happy hacking!

Exercise

Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.

Extras:

  1. Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.
  2. Write this in one line of Python.
  3. Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user.

  4. Discussion

    This week's topics:
    1. Lists
    2. More conditionals (if statements)


    3. Lists


      This week's exercise hits on a topic critical for all types and styles of programming: lists. Lists are basically an ordered way of grouping things (called elements) - the cool thing about lists in Python is that you can have a list that contains objects of multiple types. Your list can mix between strings, integers, objects, other lists, what have you.
      The way to construct an empty list is just to do
      x = []
      And your variable x now holds an empty list. To add things to this list, just "append" them to the list. Like so:
      x = []
      x.append(3)
      Your list x now looks like [3].

      In Python, lists are also iterables, which means you can loop through them with a for loop in a convenient way. (If you come from other languages like C++ or Java you are most likely used to using a counter to loop through indices of a list - in Python you can actually loop through the elements.) I will let the code speak for itself:
      my_list = [1, 3, "Michele", [5, 6, 7]]
      for element in my_list:
          print element
      Will yield the result:
      1 
      3
      "Michele"
      [5, 6, 7]
      There are many other properties of lists, but for the basic exercise all you should need is this for loop property. Future weeks will address other properties of lists.
      For more information about lists in Python, check out these resources:
      • The official Python documentation on lists
      • Tutorialspoint on Python lists
      • Someone else's blog post about lists

      • More Conditionals


        The nice thing about conditionals is that they follow logical operations. They can also be used to test equality. Let's do a small example. Let's say I want to make a piece of code that converts from a numerical grade (1-100) to a letter grade (A, B, C, D, F). The code would look like this:
        grade = input("Enter your grade: ")
        if grade >= 90:
            print("A")
        elif grade >= 80:
            print("B")
        elif grade >= 70:
            print("C")
        elif grade >= 65:
            print("D")
        else:
            print("F")
        What happens if grade is 50? All the conditions are false, so "F" gets printed on the screen. But what if grade is 95? Then all the conditions are true and everything gets printed, right? Nope! What happens is the program goes line by line. The first condition (grade >= 90) is satisfied, so the program enters into the code inside the if statement, executing print("A"). Once code inside a conditional has been executed, the rest of the conditions are skipped and none of the other conditionals are checked.

        Forgot how to submit exercises?


        SOLUTION Exercise 2: conditionals

        Full exercise post

        Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2?

        Extras:

      • If the number is a multiple of 4, print out a different message.
      • Ask the user for two numbers: one number to check (call it num) and one number to divide by (check). If check divides evenly into num, tell that to the user. If not, print a different appropriate message.

      • Sample solution

        There are many ways of doing the exercise, so I am posting a few sample solutions. The very basics:

        And something that looks slightly more complex (but is just a more complicated conditional):


        Wednesday, February 5, 2014

        Exercise 2: conditionals

        Again, the exercise comes first (with a few extras if you want the extra challenge or want to spend more time), followed by a discussion. Enjoy!

        Exercise

        Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2?

        Extras:
        1. If the number is a multiple of 4, print out a different message. 
        2. Ask the user for two numbers: one number to check (call it num) and one number to divide by (check). If check divides evenly into num, tell that to the user. If not, print a different appropriate message.

        Discussion

        Concepts for this week:
        • Modular arithmetic (the modulus operator)
        • Conditionals (if statements)
        • Checking equality

        Modular arithmetic (the modulus operator)

        We have been doing arithmetic (addition, subtraction, multiplication, division) since elementary school, and often it is useful for us to find not the answer to a division problem but the remainder when we do a division operation. This operation is called the "modulus operation." For example, when I divide 5 by 3, the remainder is 2, and the sentence reads like this: "5 modulo 3 is 2."

        In the Python shell:
        ```
        >>> 5 % 3
        2
        >>> 6 % 3
        0
        >>> 7 % 3
        1
        ```
        The % sign is exactly the modulus operator.

        Conditionals

        When a computer (or a program) needs to decide something, it checks whether some condition is satisfied, which is where the term conditional comes from. Conditionals are a fancy way of saying "if statements". If Michele was born in New York, she has an American passport. That statement is a conditional (if statement) that in this case is true. In Python this works the same way:

        if age > 17: 
            print("can see a rated R movie")
        elif age < 17 and age > 12:
            print("can see a rated PG-13 movie")
        else: 
            print("can only see rated PG movies")
        
        
        When the program gets to the if statement, it will check the value of the variable called age against all of the conditions, in order, and will print something to the screen accordingly. Note that elif is a portmanteau of "else" and "if". So if the variable age holds the value 15, the statement "can see a rated PG-13 movie" will be printed to the screen.

        Note how the statement elif age < 17 and age > 12 has the statement and - you can use or and not in the same way. Understanding a bit about logic and how it works, or being able to rationally think about logic will help you get the conditions right - oh, and a lot of practice.

        Links about conditionals:



        Checking for equality (and comparators in general)

        A fundamental thing you want to do with your program is check whether some number is equal to another. Say the user tells you how many questions they answered incorrectly on a practice exam, and depending on the number of correctly-answered questions, you can suggest a specific course of action. For integers, strings, floats, and many other variable types, this is done with a simple syntax: ==. To explicitly check inequality, use !=.

        if a == 3: 
            print("the variable has the value 3")
        elif a != 3:
            print("the variable does not have the value 3")
        
        
        Notice how in this example, the condition is redundant. In the first condition we are checking whether the variable a has the value 3 and in the second, we are checking whether a does NOT have the value 3. However, if the first condition is not true (a is in fact not 3), then the second condition is by definition true. So a more efficient way to write the above conditional is like this:

        if a == 3: 
            print("the variable has the value 3")
        else:
            print("the variable does not have the value 3")
        
        
        The same equality / inequality comparisons work for strings.

        Links about equality and comparators:
        Good luck and enjoy!
        Forgot how to submit an exercise?

        SOLUTION Exercise 1: inputs and strings

        Great job this week with finishing the first weekly problem! Because I cannot include every single submission I get, I will choose one or two that are example answers and include those within each post.

        Exercise (click to see the full post and explanation)

        Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.

        Sample solution

        Note how a sample correct solution makes liberal use of the int and str functions - changing from one type to another.