Freecodecamp: Future Python Curriculum [Discussion]

Created on 25 Apr 2017  ·  56Comments  ·  Source: freeCodeCamp/freeCodeCamp

Python Curriculum

This issue will be the main thread for planning & developing the future FCC Python Curriculum.

For any discussion about Integrating REPL.it Classroom please visit https://github.com/freeCodeCamp/freeCodeCamp/issues/14736 instead

We are currently working on running a verifiable Python test suite on an iframe Repl.it widget. Once we get that to work we will begin implementing the laid out curriculum defined in this thread. If you are interested in developing this part of the FCC Python curriculum please message myself (Ethan Arrowood) on Gitter or comment below.

Please note to write all Python challenges in version 3.6



The current structure for the FCC Python Curriculum is: Beginner Section, Intermediate Section, & Special Topic Section.

Beginner Section:

  • [ ] Introduction to Python
  • [ ] Output

    • Print

    • Escape Characters

    • input

  • [ ] Data Types

    • Integers, Floats

    • Strings

    • Tuples

    • Lists

    • Sets

    • Dictionaries

  • [ ] Operators

    • +,-, , /, %, *

    • <, >, <=, >=, ==, !=

    • =

    • True, False, and, or, not

    • in, not in

    • is, is not

  • [x] Math - @bgroveben

    • Add, Subtract, Multiply, Divide

    • Power, sqrt(), abs(), round(), sum(), max(), min()

  • [ ] Variables
  • [ ] Conditionals

    • if, elif, else

  • [ ] Loops

    • while, for (in range), for (in list), for (in string)

  • [ ] Functions
  • [ ] Classes

Intermediate Section:

  • [ ] File I/O
  • [ ] Iterators & Generators
  • [x] Lambda - @robbiemu
  • [ ] Conditionals
  • [ ] OOP
  • [ ] Modules, Libraries, Packages
  • [ ] File and Error Handling
  • [ ] Advanced Objects and DataTypes
  • [ ] Print Formatting
  • [ ] List Comprehensions
  • [ ] Decorators

Special Topic Section:

  • [ ] Machine Learning
  • [ ] Game Development
  • [ ] Webscraping (BeautifulSoup)
  • [ ] GIS (Leaflet/Folium)
  • [ ] Flask/Django (better to focus on one not both)
  • [ ] Data Analysis (Panda/Numpy)
  • [ ] Data Visualization (brokeh)
  • [ ] GUI (tkinter)
  • [ ] Geocoding (geopy)
  • [ ] Natural Language Toolkit (NLTK)

Have an idea for an section lesson?

Comment below and please specify which Section it should be added to and why.

Want to develop the curriculum for a lesson?

Comment below the following details:

  • Title
  • Description/Explanation/Lesson
  • Code Prompt/Challenge
  • Pre-defined Code
  • Solution
  • Tests

Want to make changes to an existing lesson?

Provide your updates with detailed explanations why you are making the given changes.



Coming Soon

-

How to Propose a Python Challenge

https://github.com/freeCodeCamp/freeCodeCamp/tree/feature/python-challenges

Proposing a Python challenge? Make a PR against this branch with your challenge lessons and tests.

learn

Most helpful comment

Hey guys, I'm founder/ceo of Repl.it. FCC is near and dear to our hearts so we'll do whatever we can do so we can support here. What are the major hurdles to adopting Repl.it classrooms for this?

All 56 comments

Here is what we can add::
Beginner

  • Conditionals

Intermediate:

  • Iterators & Generators
  • Lambda
  • Conditionals
  • OOP
  • Modules, Libraries, Packages
  • File and Error Handling
  • Advanced Objects and DataTypes
  • Print Formatting

Advanced:

  • Webscraping (BeautifulSoup)
  • GIS (Leaflet/Folium)
  • Flask/Django (i'd lean more toward Django)
  • Data Analysis (Panda/Numpy)
  • Data Visualization (brokeh)
  • GUI (tkinter)
  • Geocoding (geopy)

@mstellaluna Thank you for your recommendations. What would be the difference between the Beginner conditional section and the Intermediate conditional section?

@Ethan-Arrowood for me the basics should just be imo the minimal knowledge (if, else, for, which) . My entry for the "conditional" in the intermediate would be conditionals based on user input or ternary statements.. same thing for print formatting .. basic would be a simple print statement whereas intermediate we can introduce print statements with variables, the %s .. etc

Repl.it has new area for creating custom classrooms. You can create assignments with instructions.

Repl.it Classrooms
https://repl.it/site/classrooms

List of Community classrooms
https://repl.it/community

I suggest adding basic, intermediate and advanced algorithm sections (similar to what FCC Front End curriculum has for JavaScript).

I have looked at the FCC-Python-Variable-Challenge example given, and I noticed that the challenge expects a bit of ‘prerequisites’ knowledge. As if the camper had been introduced to variables before.

The Description/Explanation for the variable challenge does not explain what variables are. Unlike JavaScript’s Declare JavaScript Variables challenge, which goes into a bit of an introduction about what variables are.

I know this is just an example – but just to be sure – are we going to assume that the camper already went through the JavaScript curriculum while building the Python curriculum?

@jamesperrin Yes we looked into that but we are trying to keep the user on FCC's site so the challenges must be embedded. Furthermore there is no way for us to access the results of the unit tests of the Repl Classrooms.

@U-ways Yeah that was my mistake. The goal is for this to be an independent curriculum so the actual explanations will be much more detailed (like the JS version). Thank you for you highlighting this :)

@AnikaErceg these will be great practice sections. Will definitely keep it in mind. Thank you!

@Ethan-Arrowood You might want to include the Natural Language Toolkit.

I added list comprehensions to intermediate

How about decorators under advanced? I assume context managers will come up during the file handling?

@t3h2mas I put decorators under intermediate.

If you added for (in list), perhaps you could also add for (in string)?
Also, an introduction to in operator would also be good (I know I found my life easier when I discovered that it doesn't have to be used only with for loops :smiley: ).

@AnikaErceg good suggestion. Done. I added is and is not as well.

@ginoskotheon You forgot to add for (in string) under loops or you see no point in introducing that? :smiley:

I'm a developer who's first language was Python...I already help out with my local FCC chapter and the organizer suggested I might like to assist with the new curriculum. I'm not 100% sure how to start contributing, but I would definitely like to. I'm also quite active in the Python community, both locally and at large, so I can get lots of knowledgeable eyes when it's needed.

My first suggestions:

  • [ ] make all of the examples follow PEP 8
  • [ ] boolean lesson should be in 'datatypes' along with 'truthy' and 'falsy' values
  • [ ] some of the standard library should be included somewhere (itertools, collections)
  • [ ] some basic libraries could be included (requests, scrapy, etc)
  • [ ] I'm not sure what 'Escape sequences' means in 'Output', but if it refers to %s style strings....leave that for a 'legacy stuff you might encounter, but don't really need to worry about' section and just teach new style f and .format() style strings.
  • [ ] the loop section mentions range, list, and 'string' like they're all different, but in Python they're all iterables which is why you can loop over them with the same keywords. Maybe that can be touched on in the 'iterators & generators' section.

    • [ ] enumerate()

  • [ ] context managers should be mentioned somewhere.
  • [ ] there could be an advanced section for asyncio
  • [ ] traditionally PEP 20 is taught somewhere at the beginning along with some spam and eggs examples.
  • [ ] tests
  • [ ] virtualenvs
  • [ ] installing
  • [ ] comments
    I would be more than happy to help with this project in any way I can. I've been thinking for a quite a while we needed something like this.

@cldershem So many great suggestions thank you! With your experience, the best kind of contributions you can make are writing the lessons/challenges themselves. Let me know which ones you'd be interested in writing 😄

@cldershem

I'm not 100% sure how to start contributing, but I would definitely like to.

https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/Pull-Request-Contribute

Might point you in the right direction.

Maybe @Ethan-Arrowood would take submissions through Github comments as well?

@t3h2mas Yes, as I said at the very top lesson/challenge submissions can be done right here on this thread as comments 😄

@cldershem Another way you can help is if you know of a good way to create an in browser challenge that can actually be tested (with unittest). We're exploring all kinds of options form REPL.it to codeMirror to Skulpt.

@cldershem I probably should write "escape characters". Those are things like '\n', '\t', etc.

And I know they're iterables but I am starting to break things up in terms of individual bite-sized lessons.

By the way, thanks for all of the suggestions and all of the help. I'm planning on working on a sample lesson/challenge over the weekend and hopefully it can be a kind of template for others. If you want to tackle a lesson/challenge that functions similarly to how Free Code Camp challenges work, then please post your code. I would love to see that.

@Ethan-Arrowood @ginoskotheon @cldershem
I would also like to help write the lessons and challenges for the FCC-Python course.
I see from previous comments that Repl.it Classrooms aren't the best choice, but I can begin working on the lessons (title, description, tests, etc described above) there. Once a platform/framework has been settled on, I can always modify the code and move it.
I wrote a couple of sample exercises that you can find here; you should be able to see them, but you have to be signed in to import them, take a look under the hood and modify them.
Please feel free to comment, critique, and change the lessons themselves, and please let me know when a more appropriate platform/framework has been decided on.
In the meantime, I can work on the Beginner lessons detailed above, starting with math and moving on to whatever else needs to be done.

Hey guys, I'm founder/ceo of Repl.it. FCC is near and dear to our hearts so we'll do whatever we can do so we can support here. What are the major hurdles to adopting Repl.it classrooms for this?

@amasad hello! Glad to have you here 😄
The main hurdle we are facing adopting Repl.it into the FCC Python course is interfacing with the Repl.it Classroom unittests. We love the Repl.it Classroom structure of being able to run an independent file with unit tests; however, we cannot figure out how to tell when a user completes the challenge (passes all of the unittests). Of course this behavior is embedded within Repl.it, but in order to keep the feel of the current FreeCodeCamp we'd like to be able to advance the user to the next challenge automatically (or prompt them to do so) once they complete the current challenge ( i.e. successfully pass all of the unittests).

Any ideas on how we could implement this? FCC is written in JavaScript so any sort of web api or npm module would work pretty well.

If you think many of your viewers will come from the JavaScript background, I think a primer on the differences would be useful. For example

// javascript
var dict = {
    a : 1
};

console.log(dict.a)
# python
dict = {
    "a" : 1
}

print(dict["a"])

Another example would be looping through a dictionary or array with for loops. This trips me up all the time.

_Title_ Introduction to Lambdas

_Description/Explanation/Lesson_
srcs:

1 http://stackoverflow.com/questions/890128/why-are-python-lambdas-useful
2 http://www.secnetix.de/olli/Python/lambda_functions.hawk
3 https://pythonconquerstheuniverse.wordpress.com/2011/08/29/lambda_tutorial/
4 http://stackoverflow.com/questions/16501/what-is-a-lambda-function
5 https://en.wikipedia.org/wiki/Anonymous_function

"An anonymous function (function literal, lambda abstraction) is a function definition that is not bound to an identifier." [5] The word "Lambda comes from the Lambda Calculus" [4]. In python, a lambda is an keyword for defining an anonymous function. Using the lambda keyword instead of the def keyword, a basic lambda looks like this: lambda x: x**2 These can be assigned to variables and reused much like functions:

>>> def f (x): return x**2
>>> print f(8)
64
>>> g = lambda x: x**2
>>> print g(8)
64

_src 2_

The most common use cases are to keep code short and readable, instead of splitting definition and use as per this example:

def __init__(self, parent):
    """Constructor"""
    frame = tk.Frame(parent)
    frame.pack()

    btn22 = tk.Button(frame,
        text="22", command=self.buttonCmd22)
    btn22.pack(side=tk.LEFT)

    btn44 = tk.Button(frame,
        text="44", command=self.buttonCmd44)
    btn44.pack(side=tk.LEFT)

def buttonCmd22(self):
    self.printNum(22)

def buttonCmd44(self):
    self.printNum(44)

_src 3_

In this Tkinter GUI interface, a function must be passed to the _command_ attribute. The functions are named with numbers because they were generated with a RAD builder. This is fine and functional, but not very legible. You can rename them and that does make things clearer, but if you had many buttons it could become cumbersome to go seeking through the code to find the right command, and since they just return a basic value, a better solution would be to define the function right there, anonymously:

frame = tk.Frame(parent)
frame.pack()

btn22 = tk.Button(frame,
        text="22", command=lambda: self.printNum(22))
btn22.pack(side=tk.LEFT)

btn44 = tk.Button(frame,
        text="44", command=lambda: self.printNum(44))
btn44.pack(side=tk.LEFT)

_src 3_

Another key feature of this use is that it makes the code shorter as well, meaning it is more readily available for the programmer when seeking a tool as part of a larger solution.

_Code Prompt/Challenge_
Write a lambda expression that has the key features described above; making the code more legible by moving all the code in use to the same place; resulting in shorter, more natural code.

_Pre-defined Code_

# only edit below this line
def y(z):
  return abs(5-z)

print(sorted([1, 2, 3, 4, 5, 6, 7, 8, 9], key=y))

_src 1_

_Solution_
print(sorted([1, 2, 3, 4, 5, 6, 7, 8, 9], key=lambda x: abs(5-x)))

@robbiemu great work! My only suggestion would be to add a comment in the Pre-defined Code section next to the print line that says something like # only edit this line. Also I believe this is python 2 code and we are going to be teaching python 3 so I think the only change is the print line requires wrapping '( )'.
Thank you for your contribution!

Ethan, thank you. I'll continue to work on this. The problem and solution could be changed so there are reasonable tests as well (not using a static data set, as I have here). I'd like to see an example lesson for the best approach to do this.

@robbiemu of course. We are still working on REPL.it and will update this thread as soon as we know more information. Good job for now 😄

This is one of the code challenges for the Beginner - Math section listed at the beginning of this thread.

_Title_ -- Absolute Value

_Description/Explanation/Lesson_ --
Absolute value refers to how far a number is from zero.
If a number is negative, abs() will convert it to positive.
In abs(x), x may be an integer, float, or complex number.
https://docs.python.org/3/library/functions.html#abs
https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex

>>> abs(2)
2
>>> abs(-2)
2
>>> abs(-2.0)
2.0

_Code Prompt/Challenge_ --
The variable absolute_value equals -42.
Change absolute_value so that it equals the absolute value of -42.

_Pre-defined Code_ --

absolute_value = -42

_Solution_ --

absolute_value = abs(-42)

_Tests_ --

class UnitTests(unittest.TestCase):
    def test_main(self):
        self.assertIsInstance(absolute_value, int)
        self.assertEqual(absolute_value, 42)

@bgroveben LGTM. good work!

@Ethan-Arrowood Thank You! I have also written lessons for the other basic/math challenges listed above. I can post each of them on this thread if you'd like. Also, I think it would be a good idea to include round(), sum(), max(), and min() with the math basics lessons -- they will come in handy.

@bgroveben I'll mark it as completed and yes please. Do each challenge in a separate comment too please; it'll be easier to reference for changes or whatever. Thank you for your contributions!

@Ethan-Arrowood

@amasad hello! Glad to have you here 😄

Glad to be here 💃

The main hurdle we are facing adopting Repl.it into the FCC Python course is interfacing with the Repl.it Classroom unittests. We love the Repl.it Classroom structure of being able to run an independent file with unit tests; however, we cannot figure out how to tell when a user completes the challenge (passes all of the unittests). Of course this behavior is embedded within Repl.it, but in order to keep the feel of the current FreeCodeCamp we'd like to be able to advance the user to the next challenge automatically (or prompt them to do so) once they complete the current challenge ( i.e. successfully pass all of the unittests).

Any ideas on how we could implement this? FCC is written in JavaScript so any sort of web api or npm module would work pretty well.

The easiest is that we bake it in. Have a setting on the teacher side of things that says "auto-advance" or something. (We're not against adding webhooks etc, but for the sake of reducing complexity) Would that work?

@amasad using an "auto-advance" feature we would surely be able to emulate FreeCodeCamp in a Repl.it classroom, but we still wouldn't be able to track user progress on FCC's end which is pretty crucial to the feel of FCC.

What about a feature that lets us GET/POST data of a 'Classroom'. This way we could do something like:

repl.getUser('classroomID', 'userID').then( () => {
    // do stuff async 
}).catch( (error) => {
    // handle error
});

or better yet:

repl.getProgress('classroomID', 'lessonID', 'userID').then( () => { }).catch( (e) => { });

Now both of these methods would run on our end, but because the REPL Classroom is embedded via an iframe we would at least need some simple event triggers from REPL's side in order to properly track individual user progress.

Furthermore, because the Classroom would be embedded via an iframe, could we potentially get a feature that when a user completes a lesson the REPL Classroom runs some lines of JavaScript (that we can define via the Teachers portal) so we can get the classroom to communicate with FCC?

We hope to be able to use REPL classrooms for not just Python, but other languages as well. Once the FCC Python Curriculum is up and running successfully we will move on to implement languages like Java or C++ (or literally any language that REPL can offer us to use!).

I'd love to get @QuincyLarson opinion on this as well as some other main FCC contributors (I'll try reaching out to them on Gitter/Forums).

Hi everyone, thanks a lot for the comments and suggestions.

@amasad Thanks for taking the time to share your thoughts and ideas here. Its great to know that REPL.it is working on the classroom product, which we would love to integrate within the platform.

For starters, it would be great if we can take this up in a separate discussion instead of this curriculum thread, to keep it more relevant to the integration itself.

@Ethan-Arrowood Awesome job with the initiative. Thanks for your hard work.

@amasad @QuincyLarson I have officially moved the REPL classroom discussion to this issue thread (per @raisedadead recommendation). https://github.com/freeCodeCamp/freeCodeCamp/issues/14736

following up on the comment by cldershem (commented 8 days ago), here's one forcollections -

Title

namedtuples

Description/Explanation/Lesson

1 https://en.wikipedia.org/wiki/Tuple
2 https://docs.python.org/3.6/library/collections.html
3 https://docs.python.org/3.6/library/collections.html#collections.namedtuple
4 https://pythonprogramming.net/reading-csv-files-python-3/

A tuple is a concept common in mathematics. It is considered a finite ordered list of elements.[1] In python, these are functionally similar to dictionaries, where keys are defined in advance. Namedtuples can be used to provide a quick property tree for any use: like if your app must deal with socks and all socks have a size and a price, then a tuple with two fields is useful, approximating the dictionary {size: _size_, price: _price_}. To get a tuple with these fields you pass the fields to the collections.namedtuple factory function: [2]
collections.namedtuple(Socks, ['size', 'price'])
For convenience, especially when processing information from plain text sources, the fieldnames can be an array, or a single string with comma separated and/or space separated values: [3]
EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
Any valid Python identifier may be used for a _fieldname_ except for names starting with an underscore. Valid identifiers consist of letters, digits, and underscores but do not start with a digit or underscore and cannot be a keyword such as class, for, return, global, pass, or raise.[3]
Once generated, they can be used to make instances with dictionary-like entries:

Point = namedtuple('Point', ['x', 'y'])
p = Point(x=11, y=22)
p[0] + p[1] # 33
x, y = p # (11, 22)
p.x + p.y # 33
p # Point(x=11, y=22)

_from_ [3]

Code Prompt/Challenge

A good use of namedtuples is to facilitate ingesting data, like from a csv export from a database. In the following code, fix this CSV import with a tuple.

Pre-defined Code

import csv
import collections

# only change code below this line!
recordData = ['fieldNames'] # find the fieldnames in the code below
# only change code above this line!
EmployeeRecord = collections.namedtuple('EmployeeRecord', recordData)

with open('employee-records.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
# onlt change code below this line!
        name = row[0]
        age = row[1]
        title = row[2]
        department = row[3]
        paygrade = row[4]

        processEmployee([name, age, title, department, paygrade]) # fails because processEmployee accepts an EmployeeRecord Tuple!
# only change code above this line!

_derived from_ [4]

_note_: the above uses an actual file, but we could replace the with ... readCSV lines with something like:
readCSV = csv.reader(['Alan,42,Manager,Sales, N1', 'Beth,38,Regional Director,Operations,CO','Robin,23,Associate,Sales,C2']

Solution

import csv
import collections

# only change code below this line!
recordData = ['name', 'age', 'title', 'department', 'paygrade']
# only change code above this line!
EmployeeRecord = collections.namedtuple('EmployeeRecord', recordData)

with open('employee-records.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
# onlt change code below this line!
        employee = EmployeeRecord(*row)

        processEmployee(employee)
# only change code above this line!

Lesson 2:

Title

namedtuples._make

Description/Explanation/Lesson

1 https://docs.python.org/3.6/library/collections.html#collections.namedtuple

A method of NamedTuples called __make_ facilitates the generation of instances within an iterator function.This would make the problem from the previous lesson even more terse.
This is used like:

for emp in map(EmployeeRecord._make, allRows):
    print(emp.name, emp.title)

Code Prompt/Challenge

We are revisiting the previous lesson and revising the code. It's almost there, but the job is unfinished. For your convenience, some records are printed out where you should process the record. Remember, we need to create an EmployeeRecord and pass that to a function elsewhere in the code, like:

        employee = EmployeeRecord(*row)

        processEmployee(employee)

Pre-defined Code

import csv
from collections import namedtuple

EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
# only change code below this line!
    print(emp.name, emp.title)

Solution

EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
# only change code below this line!
    processEmployee(emp)

We could probably also use quick lessons illustrating:

  • n = NamedTuple(**Dictionary)
  • use of ._fields to make alternate forms: TwoD = namedtuple('TwoD', 'x y') => ThreeD = namedtuple('ThreeD', TWo._fields + ('z',))
  • coverage of basic use cases: data ingestion (like the csv), database transactions, network transactions, facilitating POJOs (or.. is POPOs a thing in Python? lol)

Here are the rest of the beginner math challenges:

__Title:__ Python Addition

__Description/Explanation/Lesson:__

In Python, an integer (int) is one of 3 distinct numeric types.
In this exercise, you will add two integers using the plus (+) operator.

>>> 2 + 2
4

__Code Prompt/Challenge:__

Change the 0 so that total will equal 20.

__Pre-defined Code:__

total = 10 + 0

__Solution:__

total = 10 + 10

__Tests:__

class UnitTests(unittest.TestCase):
    def test_main(self):
        self.assertIsInstance(total, int)
        self.assertEqual(total, 20)

__Title:__
Compute quotient and remainder using the divmod() function.

__Description/Explanation/Lesson:__

Divmod takes two (non complex) numbers as arguments and returns a pair of numbers consisting of their quotient and remainder when using integer division.
For integers, the result is the same as (a // b, a % b).

>>> divmod(1, 1)
(1, 0)
>>> divmod(3, 2)
(1, 1)

__Code Prompt/Challenge:__

In this exercise, variables a and b are defined for you.
Define a variable named result that calls the divmod function on variables a and b (in that order).

__Pre-defined Code:__

a = 11
b = 3

__Solution:__

a = 11
b = 3
result = divmod(a, b)

__Tests:__

class UnitTests(unittest.TestCase):
    def test_main(self):
        self.assertIsInstance(result, tuple)
        self.assertEqual(result, (3, 2))

__Title:__ Python Exponents

__Description/Explanation/Lesson:__

Python uses the double asterisk (**) operator to handle exponentiation.
The number before the asterisks is the base, and the number after is the exponent.
Python also lets you use the built-in function pow(x, y), which gives you x to the power of y.

>>> 2 ** 2
4
>>> pow(2, 4)
16

__Code Prompt/Challenge:__

In the console, you are given two variables, a and b.
Using either method described in this lesson, define a variable named power that equals a to the power of b.

__Pre-defined Code:__

a = 3
b = 4

__Solution:__

a = 3
b = 4
power = pow(a, b)
# or #
power = a ** b

__Tests:__

class UnitTests(unittest.TestCase):
    def test_main(self):
        self.assertIsInstance(power, int)
        self.assertEqual(power, 81)

__Title:__ Python Float Division

__Description/Explanation/Lesson:__

Python 3 distinguishes between integer (floor) division and float (true) division.
Python uses a single forward slash (/) operator for float division.
When using float division, even if the quotient (result) is a whole number like 1 or 2, a floating point number will be returned instead of an int.

>>> 1 / 1
1.0
>>> 3 / 2
1.5

__Code Prompt/Challenge:__

When you run the existing code, the variable named quotient will have a value of 1.0.
Change the the second number (the denominator) so that quotient has a value of 2.5.

__Pre-defined Code:__

quotient = 5 / 5

__Solution:__

quotient = 5 / 2

__Tests:__

class UnitTests(unittest.TestCase):
    def test_main(self):
        self.assertIsInstance(quotient, float)
        self.assertEqual(quotient, 2.5)

__Title:__ Python Integer Division

__Description/Explanation/Lesson:__

Python 3 distinguishes between integer (floor) division and float (true) division.
Python uses a double forward slash (//) operator for integer division.
When using integer division, Python will round the quotient down to the nearest whole number.

>>> 1 // 1
1
>>> 3 // 2
1

__Code Prompt/Challenge:__

When you run the existing code, the variable named quotient will have a value of 1.
Change the the second number (the denominator) so that quotient has a value of 2.

__Pre-defined Code:__

quotient = 5 // 5

__Solution:__

quotient = 5 // 2

__Tests:__

class UnitTests(unittest.TestCase):
    def test_main(self):
        self.assertIsInstance(quotient, int)
        self.assertEqual(quotient, 2)

__Title:__ Python Maximum Value

__Description/Explanation/Lesson:__

The function max() returns the largest item in an iterable (like a list or string), or the largest of two or more arguments.
While giving an iterable as an argument we must make sure that all of the elements in the iterable are of the same type.
If the iterable is empty and default is not provided, a ValueError is raised.

>>> max(1,2,3,4)
4
>>> list1 = ['a', 'e', 'i', 'o', 'u']
>>> max(list1)
'u'
>>> string1 = "largest"
>>> max(string1)
't'

__Code Prompt/Challenge:__

The starter code has a list of numbers named, well, numbers.
The variable highest is initialized to numbers.
Make the value of highest equal the largest number in numbers.

__Pre-defined Code:__

numbers = [8, 2, 4, 3, 6, 5, 9, 1]
highest = numbers

__Solution:__

numbers = [8, 2, 4, 3, 6, 5, 9, 1]
highest = max(numbers)

__Tests:__

class UnitTests(unittest.TestCase):
    def test_main(self):
        self.assertIsInstance(highest, int)
        self.assertEqual(highest, 9)

__Title:__ Python Minimum Value

__Description/Explanation/Lesson:__

The function min() returns the smallest item in an iterable (like a list or string), or the smallest of two or more arguments.
While giving an iterable as an argument we must make sure that all of the elements in the iterable are of the same type.
If the iterable is empty and default is not provided, a ValueError is raised.

>>> min(1,2,3,4)
1
>>> list1 = ['a', 'e', 'i', 'o', 'u']
>>> min(list1)
'a'
>>> string1 = "smallest"
>>> min(string1)
'a'

__Code Prompt/Challenge:__

The starter code has a list of letters named, well, letters.
The variable lowest is initialized to letters.
Make the value of lowest equal the 'smallest' (alphabetically first) letter in letters.

__Pre-defined Code:__

letters = ['m','o','n','t','y','p','y','t','h','o','n']
lowest = letters

__Solution:__

letters = ['m','o','n','t','y','p','y','t','h','o','n']
lowest = min(letters)

__Tests:__

class UnitTests(unittest.TestCase):
    def test_main(self):
        self.assertIsInstance(lowest, str)
        self.assertEqual(lowest, 'h')

__Title:__ Python Multiplication

__Description/Explanation/Lesson:__

Python uses the asterisk (*) operator for multiplication.

>>> 3 * 3
9

__Code Prompt/Challenge:__

Change the 0 so that product will equal 80.

__Pre-defined Code:__

product = 8 * 0

__Solution:__

product = 8 * 10

__Tests:__

class UnitTests(unittest.TestCase):
    def test_main(self):
        self.assertIsInstance(product, int)
        self.assertEqual(product, 80)

__Title:__ Python Remainder

__Description/Explanation/Lesson:__

The % (modulo) operator yields the remainder from the division of the first argument by the second.
The modulo operator always yields a result with the same sign as its second operand (or zero).

>>> 3 % 2
1
>>> 3 % 2.0
1.0

A simple way to determine if a number is odd or even is to check the remainder when that number is divided by 2.
For odd numbers, the remainder is 1.
For even numbers, the remainder is 0.

>>> 3 % 2
1
>>> 4 % 2
0

__Code Prompt/Challenge:__

Set the variable remainder equal to the remainder of 11 divided by 3 using the modulo (%) operator.

__Pre-defined Code:__

remainder = "Solution goes here"

__Solution:__

remainder = 11 % 3

__Tests:__

class UnitTests(unittest.TestCase):
    def test_main(self):
        self.assertIsInstance(remainder, int)
        self.assertEqual(remainder, 2)

__Title:__ Python Rounding

__Description/Explanation/Lesson:__

The function round(number, n-digits) returns a given number rounded to n-digits precision after the decimal point.
If n-digits is omitted or is None, it returns the nearest integer to its input.
The return value is an integer if called with one argument, otherwise it is of the same type as the given number.

>>> round(5)
5
>>> round(5.5)
6
>>> round(5.555, 1)
5.6

__Code Prompt/Challenge:__

The variable longer_pi has too many digits after the decimal place.
Create a variable named shorter_pi that we can use instead.
Use the round() function to display just the first 2 digits after the decimal point, and assign that value to shorter_pi.

__Pre-defined Code:__

longer_pi = 3.14159265358979323846

__Solution:__

longer_pi = 3.14159265358979323846
shorter_pi = round(longer_pi, 2)

__Tests:__

class UnitTests(unittest.TestCase):
    def test_main(self):
        self.assertIsInstance(shorter_pi, float)
        self.assertEqual(shorter_pi, 3.14)

__Title:__ Python Square Root

__Description/Explanation/Lesson:__

The math.sqrt() function is a part of Python's math module, which is always available but must be imported.
Math.sqrt(x) returns the square root of x as a floating-point number.

>>> import math
>>> math.sqrt(4)
2.0
>>> math.sqrt(2)
1.4142135623730951

__Code Prompt/Challenge:__

The variable square_root is defined as the number 81.
Change square_root so that it equals the square root of 81.
The math module has been imported for you.

__Pre-defined Code:__

import math
square_root = 81

__Solution:___

import math
square_root = math.sqrt(81)

__Tests:__

class UnitTests(unittest.TestCase):
    def test_main(self):
        self.assertIsInstance(square_root, float)
        self.assertEqual(square_root, 9.0)

__Title:__ Python Subtraction

__Description/Explanation/Lesson:__

In Python, an integer (int) is one of 3 distinct numeric types.
In this exercise, you will subtract two integers using the minus (-) operator.

>>> 2 - 1
1

__Code Prompt/Challenge:__

Change the 0 so that total will equal 10.

__Pre-defined Code:__

total = 20 - 0

__Solution:__

total = 20 - 10

__Tests:__

class UnitTests(unittest.TestCase):
    def test_main(self):
        self.assertIsInstance(total, int)
        self.assertEqual(total, 10)

__Title:__ Python Sum

__Description/Explanation/Lesson:__

The function sum(iterable) adds all of the items in a Python iterable (list, tuple, and so on) from left to right and returns the total.
There is an optional second argument, start, that defaults to 0 and is added to the total.
The iterable‘s items are normally numbers, and the start value is not allowed to be a string.

>>> numbers = [1, 2, 3, 4, 5]
>>> sum(numbers)
15
>>> sum(numbers, 1)
16
>>> sum(numbers, 10)
25

__Code Prompt/Challenge:__

There are two lists of numbers.
Find the sum of all of the items in both lists and assign that value to a variable named total.

__Pre-defined Code:__

list1 = [1, 3, 5, 7, 9]
list2 = [2, 4, 6, 8, 10]

__Solution:__

list1 = [1, 3, 5, 7, 9]
list2 = [2, 4, 6, 8, 10]
total = sum(list1, sum(list2))

__Tests:__

class UnitTests(unittest.TestCase):
    def test_main(self):
        self.assertIsInstance(total, int)
        self.assertEqual(total, 55)

I think that covers all of the lessons listed in the basics/math section.
Please let me know if you want to add any more.
Also, feel free to make edits, changes, suggestions, and so on.
I have the all of the lessons I just posted in .py and .md files at:
https://github.com/bgroveben/FCC_Python.
I have also set up a REPL Classroom at:
https://repl.it/community/classrooms/18388.

Please note - we are moving discussion of our Python coding challenges to this new repository: https://github.com/freeCodeCamp/python-coding-challenges/issues

Posting here for reference:
I think the Max and Min may want to both:

  1. Use numbers for clarity -- users may not know how a char is an integer
  2. Be sure to use multiple instances of one number -- to really drive in the behavior
Was this page helpful?
0 / 5 - 0 ratings