freeCodeCamp / freeCodeCamp

freeCodeCamp.org's open-source codebase and curriculum. Learn to code for free.
https://contribute.freecodecamp.org
BSD 3-Clause "New" or "Revised" License
405.29k stars 38.02k forks source link

Future Python Curriculum [Discussion] #14588

Closed Ethan-Arrowood closed 7 years ago

Ethan-Arrowood commented 7 years ago

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.~~
mstellaluna commented 7 years ago

Here is what we can add:: Beginner

Intermediate:

Advanced:

Ethan-Arrowood commented 7 years ago

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

mstellaluna commented 7 years ago

@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

jamesperrin commented 7 years ago

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

4nik4 commented 7 years ago

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

u-ways commented 7 years ago

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?

Ethan-Arrowood commented 7 years ago

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

Ethan-Arrowood commented 7 years ago

@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 :)

Ethan-Arrowood commented 7 years ago

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

QuincyLarson commented 7 years ago

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

whmcdonaldiii commented 7 years ago

I added list comprehensions to intermediate

t3h2mas commented 7 years ago

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

whmcdonaldiii commented 7 years ago

@t3h2mas I put decorators under intermediate.

4nik4 commented 7 years ago

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

whmcdonaldiii commented 7 years ago

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

4nik4 commented 7 years ago

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

cldershem commented 7 years ago

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:

Ethan-Arrowood commented 7 years ago

@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 😄

t3h2mas commented 7 years ago

@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?

Ethan-Arrowood commented 7 years ago

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

whmcdonaldiii commented 7 years ago

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

whmcdonaldiii commented 7 years ago

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

bgroveben commented 7 years ago

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

amasad commented 7 years ago

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?

Ethan-Arrowood commented 7 years ago

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

dmvaldman commented 7 years ago

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.

robbiemu commented 7 years ago

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

Ethan-Arrowood commented 7 years ago

@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!

robbiemu commented 7 years ago

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.

Ethan-Arrowood commented 7 years ago

@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 😄

bgroveben commented 7 years ago

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)
Ethan-Arrowood commented 7 years ago

@bgroveben LGTM. good work!

bgroveben commented 7 years ago

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

Ethan-Arrowood commented 7 years ago

@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!

amasad commented 7 years ago

@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?

Ethan-Arrowood commented 7 years ago

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

raisedadead commented 7 years ago

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.

Ethan-Arrowood commented 7 years ago

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

robbiemu commented 7 years ago

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:

bgroveben commented 7 years ago

Here are the rest of the beginner math challenges:

bgroveben commented 7 years ago

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.

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)
bgroveben commented 7 years ago

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

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))
bgroveben commented 7 years ago

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.

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)
bgroveben commented 7 years ago

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.

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)
bgroveben commented 7 years ago

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.

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)
bgroveben commented 7 years ago

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.

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)
bgroveben commented 7 years ago

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.

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')
bgroveben commented 7 years ago

Title: Python Multiplication

Description/Explanation/Lesson:

Python uses the asterisk (*) operator for multiplication.

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)
bgroveben commented 7 years ago

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

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)
bgroveben commented 7 years ago

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.

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)