Does anyone wish to discuss any of the concepts presented in the Codecademy Python Track? This may be a good venue for that. Codecademy also provides Q&A forums for each section within the track. There is a button in the lower left corner of each exercise page for that. Most of the discussion there serves to answer questions related to problems with users’ Python code, so P2PU might be a better place to discuss the more general concepts.
Not actually a discussion but I am finding the way Codecademy loses connectivity very frustrating. The developers are aware of the problem and are working on it but it is causing a lot of wasted time and frustration.
The concept as a learning tool is great!
Sometimes the Codecademy server might get bogged down a bit, which is probably when a school day is in session, and lots of classes have their students working on Python at the same time. But when that happens, I usually stop working and come back later.
One of the important concepts that they slipped in to the first unit is functions. They did it so quietly, though, that it may escape notice. Here’s the example, from 6: Whitespace Means Right Space …
def spam(): eggs = 12 return eggs print spam()
In the above code, we defined, then called a
spam function. While our
spam function is not particularly useful, functions, in general, are re-usable units of code that we can create, and then use wherever we need them in a program.
Here’s a somewhat more useful example of defining and calling a function, kept simple for illustrative purposes …
def pythagoras(side_a, side_b): # given lengths of two sides, # compute the length of the hypotenuse hypotenuse = (side_a ** 2 + side_b ** 2) ** 0.5 return hypotenuse for a in range(1, 6): for b in range(a, 6): print a, b, pythagoras(a, b)
pythagoras function is being defined here with two parameters between the parentheses in the function header, namely
side_b. When we call the function, we need to supply two values between the parentheses, that get assigned to these two parameters. The function computes a result and assigns it to a variable,
hypotenuse. We then
return that result, which makes it available wherever the function is called.
for loop, we are calling the function with various combinations of side lengths, and printing each result. Within that loop, the variables
b are being used as arguments in the function call, and their values are getting assigned to the parameters
Hidden Codecademy Python Content
For those who dare, there is lots of unofficial Python content on Codecademy that has been contributed by users, but is not featured up front. As a result, this content is difficult to find through their web site.
After completing the Python track some time ago, I did my best to find this content, via some Googling, and through looking at other users’ profiles, where their badges are listed. Some of this content is buggy, but all that is listed below can be completed (or could some time in the past), sometimes with workarounds to circumvent bugs.
For each exercise in the Python track, as well as for contributed content such as this, Codecademy runs a submission correctness test (SCT) to determine whether to issue a pass after the user clicks the Save & Submit button. If the user’s submitted code is not passed, the SCT determines the content of the message to display. Part of the “art” and “science” of working though the exercises listed below is to be creative about finding workarounds for exercises that appear to have buggy SCTs. Some of these workarounds are discussed in the Q&A forums connected to the exercises.
So, having been briefed, give these a look, if you are feeling adventurous.
The NPR API
How to use APIs with Python
Get Started with Sunlight Foundation
Getting Started with Bitly
Data Management for Scientists
Fun with Python Strings!
Python for HPC
Intro to Data Science
Exceptions & Basic Error Handling
List comprehensions and Generators
Data Structure in Python
Pythonic Algorithms 101
Advanced Argument Passing and Receiving
The New York Times API
A Dash of Python
Python: Lists, Tuples, and Dictionaries
Text-Based Maze Game
Intro to Python
Welcome to Python - The Basics
Getting Started with Python
Strings and Functions
Get a feel for programming
Zebra Puzzle in Python
Continuing In Python
Pizza Shop Ordering System
Tic Tac Toe
Iteration and generators
Becoming the Next Webster
Control Flow in Python
Challenges Beta 1
Python Classes and Objects
Recursion in Python
How to use the WePay API - Python
Quick Learning About Everything
Entrada/Salida en Archivos
PyCon intro to Python
Introduction to Python
Intro to Bioinformatics
Listas y Funciones
Sintaxis de Python
Calculadora de Propinas
Variables, expressions et instructions
Strings y Salida en Consola
Fecha y Hora
Condicionales y Control de Flujo
Tomar unas Vacaciones
Listas y Diccionarios de Python
Un Día en el Supermercado
El Estudiante Se Vuelve Profesor
La Práctica Hace al Maestro
Estadísticas del Examen
Temas Avanzados en Python
Introducción a los Operadores a Nivel de
Introducción a las Clases
Rock Paper Scissor
HTML and python
Modul 1: Einführung
TEJ3M Culminating Day 1
Bioinformatica in de klas
Introduction to Computer Programming
Python for begginers
inputs,str formatting, and math
I luv python
How do you feel?
UEPB - Algoritmos 2013.2
Aprender a Programar con Python
Python Challenges #2
Basic math with Python
Teach Yourself Python
Python - Umons
@Glenn this is a great list! There is even a little something on Regular Expressions… Thanks for taking the time to put this together and share!!
Part of our assignment this week was to complete the Codecademy Lists and Functions exercises.
I thought one of the more interesting ones was Exercise 18: Using a list of lists in a function.
We are given the following code, and asked to create a function called
flatten that takes a single list and concatenates all the sublists that are part of it into a single list.
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]] # Add your function here print flatten(n)
So, from the given list,
n, the resulting list should be …
[1, 2, 3, 4, 5, 6, 7, 8, 9]
It should work for a list that contains any number of sublists, not only for 2 sublists. Has anyone here done this one?
Here’s one possible solution …
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]] def flatten(lists): result =  for sublist in lists: for item in sublist: result.append(item) return result print flatten(n)
In the above, the outer loop visits each sublist, and the inner loop accesses each item in the current sublist, and appends that item to the new list.
There are other ways to do this. One interesting approach is to use something called recursion. Would anyone like to try that approach?
Codecademy, by the way, has a course on its site, Recursion in Python, that was contributed by a user, and is not part of the official Python track.
I am almost done with that [Codecademy course], but I am very confused by something. I’m on the Roman Numeral converter portion. I wrote code that had a different approach from that which was suggested, reading left to right, two letters at a time, but only adding one letter at a time. Here is the code:
def rval(letr): if(letr == "I"): return 1 if(letr == "V"): return 5 if(letr == "X"): return 10 if(letr == "L"): return 50 if(letr == "C"): return 100 if(letr == "D"): return 500 if(letr == "M"): return 1000 else: return "error" def arabic(n): if(len(n) <= 1): return rval(n) elif(len(n) > 1): if rval(n) >= rval(n): return rval(n) + arabic(n[1:]) elif rval(n) < rval(n): return -rval(n) + arabic(n[1:]) #test cases to find bugs, not necessarily valid Roman Numerals. print arabic('MCMXCIX') print arabic('MCMXCIX')
The code works just fine on my Ubuntu Python 2.7.x interpreter, but the Codecademy interpreter, as well as the [repl.it] interpreter throw the same error:
File "python", line 30, in <module> File "python", line 26, in arabic TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'``` Line 30 is `print arabic('MCMXCIX')` and line 26 is `return rval(n) + arabic(n[1:])` When I do `arabic('IX')`, it returns `None`, which I suspect is the `NoneType` part of the error. However, I can't figure out why it returns `None`. Since `I` is less than `X`, the statement `elif rval(n) < rval(n):` evaluates to true, which means that `return -rval(n) + arabic(n[1:])` should run. I tried just that statement and it evaluates to 9, as it should. But for some reason when I run the whole code, `arabic('IX')` evaluates to `None` in online interpreters. I am so very confused by this behavior. In summary, the code works perfectly on Python 2.7.x on Ubuntu 14.04, however in online interpreters, `arabic('IX')` evaluates to `None` for reasons which I cannot comprehend. I think I'm just going to move on, since it works, and the course will let me pass. : http://codecademy.com/courses/python-intermediate-en-7f7dx : http://repl.it
That is strange. When I run your code on Codecademy from Chrome on a MacBook Air, there is no error. Your code also works correctly in my copy of IDLE 2.7.5.
Here’s what I have for that course. See if it works where yours produced an error:
def rval(letr): if(letr == "I"): return 1 elif(letr == "V"): return 5 elif(letr == "X"): return 10 elif(letr == "L"): return 50 elif(letr == "C"): return 100 elif(letr == "D"): return 500 elif(letr == "M"): return 1000 else: return "error" def arabic(n): if(len(n) == 1): return rval(n) #First Base Case elif (len(n) == 2): if rval(n) < rval(n): return rval(n) - rval(n) else: return rval(n) + rval(n) else: return arabic(n[:-2]) + arabic(n[-2:]) print arabic("XVI") print arabic("XIV")
Your code runs in repl.it as well as on my computer. I just tried my code again in Codecademy on a separate page from the original exercise, and it works there. However, when I go to the original exercise’s page to run it, it throws the same error. I think the SCT may be messing with me, or something. It’s weird though, since it still lets me pass. Maybe there’s some way that that exercise is formulated that prohibits other approachs. Your approach is the same as the one they suggest, which is a bit different from my approach but yours makes sense to me too. I’m not worried about it. I’ll move on.
Oh, and thank you for reminding me about Project Euler, they have some really cool problems to solve.
We can define the process of flattening of a list recursively as follows …
create a new empty list
for each item in the original list:
– base case: if the item is not a list, append the item to the new list
– recursive case: if the item is a list, flatten that list and append all the items from that flattened list to the new list
finally, return the new list
Following is a recursive solution to Codecademy Lists and Functions: Exercise 18: Using a list of lists in a function …
n = [[1, 2, , 3], [4, 5, [6, 7], 8, 9], 10, 11, 12, [, ]] def flatten(lists): # recursive version to handle multiple levels of nesting results =  for item in lists: results += flatten(item) if type(item) == list else [item] return results print flatten(n)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]