Home Backend Development Python Tutorial Learn Python using Jupyter Notebook

Learn Python using Jupyter Notebook

Sep 28, 2020 pm 04:26 PM
learn python

With Jupyter, PyHamcrest, and a little test code tying them together, you can teach any Python content that applies to unit testing.

##Python video tutorial column will give you a detailed introduction~

Learn Python using Jupyter Notebook

Some things about the Ruby community have always impressed me, two examples of which are the commitment to testing and the emphasis on ease of getting started. The best example of both is Ruby Koans, where you can learn Ruby by fixing tests.

If we could bring these amazing tools to Python, we should be able to do better. Yes, using Jupyter Notebook, PyHamcrest, and a little duct tape-like glue code, we can make a tutorial that includes instruction, working code, and code that needs fixing.

First, you need some "tape". Typically, you'll use some nifty command-line tester like pytest or virtue to do your testing. Often, you won't even run it directly. You use a tool like tox or nox to run it. However, with Jupyter, you need to write a small piece of glue code where you can run the test directly.

Luckily, this code is short and simple:

import unittest

def run_test(klass):
    suite = unittest.TestLoader().loadTestsFromTestCase(klass)
    unittest.TextTestRunner(verbosity=2).run(suite)
    return klass复制代码
Copy after login

Now, the gear is ready for your first practice session.

When teaching, it's always a good idea to start with a simple exercise to build confidence.

So, let's fix a very simple test:

@run_test
class TestNumbers(unittest.TestCase):
   
    def test_equality(self):
        expected_value = 3 # 只改这一行
        self.assertEqual(1+1, expected_value)复制代码
Copy after login
    test_equality (__main__.TestNumbers) ... FAIL
   
    ======================================================================
    FAIL: test_equality (__main__.TestNumbers)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "<ipython-input-7-5ebe25bc00f3>", line 6, in test_equality
        self.assertEqual(1+1, expected_value)
    AssertionError: 2 != 3
   
    ----------------------------------------------------------------------
    Ran 1 test in 0.002s
   
    FAILED (failures=1)复制代码
Copy after login

"Change just this line" is a useful tag for students. It indicates exactly what needs to be modified. Otherwise, students can fix the test by changing the first line to

return.

In this case, the fix is ​​easy:

@run_test
class TestNumbers(unittest.TestCase):
   
    def test_equality(self):
        expected_value = 2 # 修复后的代码行
        self.assertEqual(1+1, expected_value)复制代码
Copy after login
    test_equality (__main__.TestNumbers) ... ok
   
    ----------------------------------------------------------------------
    Ran 1 test in 0.002s
   
    OK复制代码
Copy after login

Soon, however, the

unittest library's native assertions will prove insufficient. In pytest this problem is solved by rewriting the bytecode in assert to have magic properties and various heuristics. But this is not easy to achieve in Jupyter notebook. It’s time to dig out a good assertion library: PyHamcrest.

from hamcrest import *
@run_test
class TestList(unittest.TestCase):
   
    def test_equality(self):
        things = [1,
                  5, # 只改这一行
                  3]
        assert_that(things, has_items(1, 2, 3))复制代码
Copy after login
    test_equality (__main__.TestList) ... FAIL
   
    ======================================================================
    FAIL: test_equality (__main__.TestList)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "<ipython-input-11-96c91225ee7d>", line 8, in test_equality
        assert_that(things, has_items(1, 2, 3))
    AssertionError:
    Expected: (a sequence containing <1> and a sequence containing <2> and a sequence containing <3>)
         but: a sequence containing <2> was <[1, 5, 3]>
   
   
    ----------------------------------------------------------------------
    Ran 1 test in 0.004s
   
    FAILED (failures=1)复制代码
Copy after login

PyHamcrest isn't just good at flexible assertions, it's also good at clear error messages. Because of this, the problem is obvious.

[1, 5, 3] does not contain 2, and looks ugly:

@run_test
class TestList(unittest.TestCase):
   
    def test_equality(self):
        things = [1,
                  2, # 改完的行
                  3]
        assert_that(things, has_items(1, 2, 3))复制代码
Copy after login
    test_equality (__main__.TestList) ... ok
   
    ----------------------------------------------------------------------
    Ran 1 test in 0.001s
   
    OK复制代码
Copy after login

Using Jupyter, PyHamcrest and a little test glue code, you can Teach any Python topic applicable to unit testing.

For example, the following helps show the differences between Python's different ways of stripping whitespace from strings.

source_string = "  hello world  "

@run_test
class TestList(unittest.TestCase):
   
    # 这是个赠品:它可以工作!
    def test_complete_strip(self):
        result = source_string.strip()
        assert_that(result,
                   all_of(starts_with("hello"), ends_with("world")))

    def test_start_strip(self):
        result = source_string # 只改这一行
        assert_that(result,
                   all_of(starts_with("hello"), ends_with("world  ")))

    def test_end_strip(self):
        result = source_string # 只改这一行
        assert_that(result,
                   all_of(starts_with("  hello"), ends_with("world")))复制代码
Copy after login
    test_complete_strip (__main__.TestList) ... ok
    test_end_strip (__main__.TestList) ... FAIL
    test_start_strip (__main__.TestList) ... FAIL
   
    ======================================================================
    FAIL: test_end_strip (__main__.TestList)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "<ipython-input-16-3db7465bd5bf>", line 19, in test_end_strip
        assert_that(result,
    AssertionError:
    Expected: (a string starting with &#39;  hello&#39; and a string ending with &#39;world&#39;)
         but: a string ending with &#39;world&#39; was &#39;  hello world  &#39;
   
   
    ======================================================================
    FAIL: test_start_strip (__main__.TestList)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "<ipython-input-16-3db7465bd5bf>", line 14, in test_start_strip
        assert_that(result,
    AssertionError:
    Expected: (a string starting with &#39;hello&#39; and a string ending with &#39;world  &#39;)
         but: a string starting with &#39;hello&#39; was &#39;  hello world  &#39;
   
   
    ----------------------------------------------------------------------
    Ran 3 tests in 0.006s
   
    FAILED (failures=2)复制代码
Copy after login

Ideally, students will realize that

.lstrip() and .rstrip() will meet their needs. But if they don't do that and instead try to use .strip() everywhere:

source_string = "  hello world  "

@run_test
class TestList(unittest.TestCase):
   
    # 这是个赠品:它可以工作!
    def test_complete_strip(self):
        result = source_string.strip()
        assert_that(result,
                   all_of(starts_with("hello"), ends_with("world")))

    def test_start_strip(self):
        result = source_string.strip() # 改完的行
        assert_that(result,
                   all_of(starts_with("hello"), ends_with("world  ")))

    def test_end_strip(self):
        result = source_string.strip() # 改完的行
        assert_that(result,
                   all_of(starts_with("  hello"), ends_with("world")))复制代码
Copy after login
    test_complete_strip (__main__.TestList) ... ok
    test_end_strip (__main__.TestList) ... FAIL
    test_start_strip (__main__.TestList) ... FAIL
   
    ======================================================================
    FAIL: test_end_strip (__main__.TestList)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "<ipython-input-17-6f9cfa1a997f>", line 19, in test_end_strip
        assert_that(result,
    AssertionError:
    Expected: (a string starting with &#39;  hello&#39; and a string ending with &#39;world&#39;)
         but: a string starting with &#39;  hello&#39; was &#39;hello world&#39;
   
   
    ======================================================================
    FAIL: test_start_strip (__main__.TestList)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "<ipython-input-17-6f9cfa1a997f>", line 14, in test_start_strip
        assert_that(result,
    AssertionError:
    Expected: (a string starting with &#39;hello&#39; and a string ending with &#39;world  &#39;)
         but: a string ending with &#39;world  &#39; was &#39;hello world&#39;
   
   
    ----------------------------------------------------------------------
    Ran 3 tests in 0.007s
   
    FAILED (failures=2)复制代码
Copy after login

they'll get a different error message showing that too much whitespace has been removed:

source_string = "  hello world  "

@run_test
class TestList(unittest.TestCase):
   
    # 这是个赠品:它可以工作!
    def test_complete_strip(self):
        result = source_string.strip()
        assert_that(result,
                   all_of(starts_with("hello"), ends_with("world")))

    def test_start_strip(self):
        result = source_string.lstrip() # Fixed this line
        assert_that(result,
                   all_of(starts_with("hello"), ends_with("world  ")))

    def test_end_strip(self):
        result = source_string.rstrip() # Fixed this line
        assert_that(result,
                   all_of(starts_with("  hello"), ends_with("world")))复制代码
Copy after login
    test_complete_strip (__main__.TestList) ... ok
    test_end_strip (__main__.TestList) ... ok
    test_start_strip (__main__.TestList) ... ok
   
    ----------------------------------------------------------------------
    Ran 3 tests in 0.005s
   
    OK复制代码
Copy after login

In a more realistic tutorial, there will be more examples and more explanations. This technique of using Jupyter Notebook can be used for some examples, and some examples need to be corrected. It can be used for real-time teaching, for video lessons, and even for more other scattered purposes, allowing students to complete a tutorial by themselves.

Share your knowledge now!

More related free learning recommendations: python video tutorial

The above is the detailed content of Learn Python using Jupyter Notebook. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles