Giter Site home page Giter Site logo

kyclark / tiny_python_projects Goto Github PK

View Code? Open in Web Editor NEW
1.4K 61.0 2.3K 14.91 MB

Code for Tiny Python Projects (Manning, 2020, ISBN 1617297518). Learning Python through test-driven development of games and puzzles.

License: MIT License

Python 96.31% Makefile 1.44% Shell 2.12% Dockerfile 0.12%

tiny_python_projects's Introduction

Introduction

This is the code repository for the Manning Publications book, Tiny Python Projects, by Ken Youens-Clark:

https://www.manning.com/books/tiny-python-projects?a_aid=youens&a_bid=b6485d52

http://tinypythonprojects.com/

There is a directory for each chapter of the book. Each directory contains a test.py program you can use with pytest to check that you have written the program correctly. I have included a short README to describe each exercise. If you have problems writing code, see my book for the skills you need.

Testing is integral to writing and solving these challenges as well as to the methodology of the book. I advocate for "test-driven development" where you write tests before you write code. The tests should define what it means for a program to be correct, and then you write programs to satisfy the tests. In this project, I've written all the tests for you, but I also encourage you to write your own functions and tests. You should run the test suite after every change to your program to ensure you are making progress!

Videos

I made videos for each chapter on my YouTube channel:

https://www.youtube.com/user/kyclark

Here are the videos I've completed so far:

  • Chapter 1: How to write and test a Python program: How to create a Python program, understanding comments and the shebang, how to make a program executable and install into your $PATH, how to write a main() function, add docstrings, format your code, and run tests.

  • Chapter 2: Crow's Nest: How to write a Python program that accepts a single, positional argument and creates a newly formatted output string.

  • Chapter 3: Picnic: Writing a Python program that accepts multiple string arguments and formats the results depending on the number of items.

  • Chapter 4: Jump The Five: Writing a Python program to encode the numerals in a given text using an algorithm called "Jump The Five." Use of a dictionary as a lookup table, characters not in the dictionary remain unchanged. Introduction to encoding/decoding text, basic idea of encryption.

  • Chapter 5: Howler: Writing a Python program that can process input text either from the command line or from a file.The output prints either to STDOUT or to a file. Learning about "os.path.isfile", how to "open" a file handle for reading/writing, how to read/write the contents of a file.

  • Chapter 6: Word Count: Writing a Python program to emulate the wc (word count) program. Validates and processes multiple file inputs as well as STDIN and creates output of the counts of lines, words, and bytes for each file optionally with a "total" if more than one file is provided.

  • Chapter 7: Gashlycrumb: Writing a Python program that processes an input file to build a lookup table (dictionary) that is used with multiple positional arguments to translate to the values from the file.

  • Chapter 8: Apples and Bananas: Writing a Python program to find and replace elements in a string. Exploring multiple ways to write the same idea from for loops to list comprehensions to higher-order functions like map().

  • Chapter 9: Abuse: Writing a Python program to generate Shakespearean insults by randomly combining some number of adjectives with a randomly chosen noun. Learning about randomness, seeds, testing, how to use triple-quoted strings.

  • Chapter 10: Telephone: Using probabalistic and deterministc approaches to randomly mutating a string.

  • Chapter 11: Bottles of Beer: Writing a Python program to produce the verse to the "99 Bottles of Beer" song from a given starting point. Learning to count down, format strings, algorithm design. A focus on writing a function and unit test, exploring ways to incorporate our function to generate the verses from for loops to list comprehensions to map().

  • Chapter 12: Ransom: Writing a Python program that will randomly capitalize letters in a given piece of text for the nefarious purpose of creating a ransom note. Exploration of for loops, list comprehensions, and the map() function.

  • Chapter 13: Twelve Days of Christmas: Writing a Python program to create the verses for "The Twelve Days of Christmas" from a given day. Learning how to write a function and the test for it, then using the function in a list comprehension and a map to generate the output.

  • Chapter 14: The Rhymer: Writing a Python program that can split off any initial consonants from a word and append a list of prefixes to create new rhyming "words." Exploration of regular expressions to handle words with no initial consonants, with one or more leading consonants, and nothing but consonants. Writing a stemmer() function and the test_stemmer() function to understand it. Using list comprehensions with guard statements and how that relates to the filter() function.

  • Chapter 15: The Kentucky Friar: In this chapter we delve further into regular expressions, first learning how to split a string using a regex so we can separate things that look like "words" from non-words like punctuation and whitespace. Then we try to identify the word "you" (case-insensitive) to turn into "y'all" and any 2-syllable words ending in "-ing" so we can replace the final "g" with an apostrophe so that "cooking" becomes "cookin'" but "swing" would remain "swing." We then apply this to an entire body of text to Kentucky fry the words with amusing results.

  • Chapter 16: The Scrambler: Writing a Python program to find each "word" in a body of text and then scramble the letters such that the first and last letters remain in place, then reconstructing the text for output. Using regular expressions to split text, using random.shuffle() and understanding in-place mutation vs returning a new value. Comparing for loops to list comprehensions and the "map()" function.

  • Chapter 17: Mad Libs: Writing a Python program to play the classic Mad Libs game. Reading an input file with placeholders for parts of speech like "adjective" or "noun." Getting the inputs to replace those from the user interactively via the "input()" function or taking them from the command-line arguments. Using regular expressions to find and replace the placeholders. Learning about greedy regex and how to make them not greedy. Using the re.findall() and re.sub() functions. Using sys.exit() to prematurely exit a program with an error message/value.

Forking GitHub repo

If you like, you can use the GitHub interface to fork this repository into your own account. Then do git clone of your repository to get a local copy.

Copyright

© Ken Youens-Clark 2019-2024

tiny_python_projects's People

Contributors

kyclark avatar mistermatze avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tiny_python_projects's Issues

Request

it it possible to have a project that have connect to database that commonly use with real world application

01_hello/test.py does not work for Windows 10 Professional

The https://github.com/kyclark/tiny_python_projects/blob/master/01_hello/test.py script does not work on Windows 10 Professional.

The problem is due to the following two lines of code in the script:

prg = './hello.py' # line 7
out = getoutput(f'python3 {prg}') # line 21

A solution to this problem is to change the two lines above as follows:

prg = '.\hello.py' # line 7: change './hello.py' to '.\hello.py' (or simply 'hello.py', removing the './' entirely)
out = getoutput(f'python {prg}') # line 21: change 'python3' to 'python'

Windows: WSL is Required

Although the introduction to the book says "If you use a Windows computer, you may want to install Windows Subsystem for Linux (WSL)." If fact, WSL is required. I don't think this is necessarily a problem but it should be clarified that the book assumes a POSIX environment and plain Windows isn't going to work.

I tried to get the book's code working in a Windows VM (to mimic the environment my adult son is using) and quickly ran into problems. As pointed out by others, the code uses POSIX directory separators, assumes Python is installed as python3 and uses shebangs and chmod.

Below are my notes for getting Windows configured so the code in this book works correctly. The notes are a bit brief and written from the point of view of a novice Windows user but experienced Linux user. If something doesn't make sense or there is a problem in these instructions please let me know.

Correctly Configuring Windows

  1. Install Visual Studio Code:

    https://code.visualstudio.com

  2. Install the Windows Subsystem for Linux (WSL) Version 2:

    https://docs.microsoft.com/en-us/windows/wsl/install-win10

    NOTE: This is a rather complicated installation.

  3. Install the Ubuntu Linux Distribution (20.04 or Latest LTS)

    https://www.microsoft.com/store/apps/9n6svws3rx71

  4. Start Ubuntu and install dependencies:

    sudo apt update
    sudo apt upgrade
    sudo apt install python3-pip
  5. Get the book's source code, install more dependencies,
    and then start Visual Studio Code:

    mkdir src
    cd src
    git clone https://github.com/kyclark/tiny_python_projects.git
    cd tiny_python_projects
    pip3 install -r requirements.txt
    code .
  6. Configure Visual Studio Code to use login shells:

    In order to use tools like pytest (which are installed in
    ~/.local/bin) you'll need to configure Visual Studio Code to
    start a login shell when opening terminals:

    • In Visual Studio: File -> Preferences -> Settings
    • Location: Features -> Terminal
    • Scroll down to: Terminal -> Integrated -> Shell Args: Linux
    • Add the following item: -l

Issue with command line arguments example

Hi. I love this book and have started the journey a few days before. I do not know whether this is an issue or just the way python/argparse handles the situation below

#!/bin/env python3
#Purpose: Say hello

import argparse

parser = argparse.ArgumentParser(description='Say hello')
parser.add_argument('-n','--name',metavar='name',default='World',help='Name to greet')
args = parser.parse_args()
print('Hello, ' + args.name + '!')

This code when executed gives proper output as per the book like

./hello.py -n Keshav
OUTPUT
Hello, Keshav!

./hello.py --name Keshav
OUTPUT
Hello, Keshav!

However, correct output is also given if code is executed the following way :-

./hello.py --n Keshav
OUTPUT
Hello, Keshav!

./hello.py --na Keshav
OUTPUT
Hello, Keshav!

./hello.py --nam Keshav
OUTPUT
Hello, Keshav!

Please suggest and explain if possible what is happening. Thank you so much. :-)

Add Code Of Conduct and Contibuting.md

Hi @kyclark I think your repository is fabulous but its missing the following files,

  • CODE_OF_CONDUCT.md
  • Contirbuting.md

I think these are essential to your repository as you expect contributions

Correct if i'm wrong or if any reasons why you didn't add those files

Thank you

One more possible solution to telephone.py?

Hello! Thanks for the cool book!

I might be wrong, but in telephone.py you suggest to use:
new_char = random.choice(alpha.replace(new_text[i], ''))

And my workaround for this was:

while True:
    new_char = random.choice(alpha)
    if new_char != new_text[i]:
        break

Is it valid? I think it is, but, using this solution I cannot pass the test... The reason for this is that after replacing character for nothing you are get random choice from another string...

Chapter 6 - Test File

Hi,

I think there is a bug in the test file for Chapter 6 - tiny_python_projects/06_wc/test.py/

The following is a test function

def test_more():
    """Test on more than one file"""
    rv, out = getstatusoutput(f'{prg} {fox} {sonnet}')
    expected = ('       1       9      45 ../inputs/fox.txt\n'
                '      17     118     661 ../inputs/sonnet-29.txt\n'
                '      18     127     706 total')
    assert rv == 0
    assert out.rstrip() == expected

I think the above test function should have been

def test_more():
    """Test on more than one file"""
    rv, out = getstatusoutput(f'{prg} {fox} {sonnet}')
    expected = ('       1       9      45 ../inputs/fox.txt\n'
                '      17     118     669 ../inputs/sonnet-29.txt\n'
                '      18     127     714 total')
    assert rv == 0
    assert out.rstrip() == expected

A small discrepancy

The README.md file in the appendix_argparse directory mentions sys_argv.py, but no such file exists in that directory.

test_excutable() E AssertionError: asser ''=='Hello, World!' E -Hello, World!

________________________________________________________________ test_executable __________________________________________________

def test_executable():
    """Says 'Hello, World!' by default"""

    out = getoutput(prg)
  assert out.strip() == 'Hello, World!'

E AssertionError: assert '' == 'Hello, World!'
E - Hello, World!

test.py:30: AssertionError

To fix this I went into the "test.py" file and changed line: 29. It works when you change it to this:
out = getoutput(f'python {prg}')

Unable To Run pytest For 01_hello

I am experiencing an error when running pytest -xv test.py in the 01_hello directory.

============================================================================= ERRORS =============================================================================
____________________________________________________________________ ERROR collecting test.py ____________________________________________________________________
/usr/lib/python2.7/dist-packages/_pytest/python.py:507: in _importtestmodule
mod = self.fspath.pyimport(ensuresyspath=importmode)
/usr/lib/python2.7/dist-packages/py/_path/local.py:701: in pyimport
import(modname)
E File "/home/zmazza/tiny_python_projects/01_hello/test.py", line 21
E out = getoutput(f'python3 {prg}')
E ^
E SyntaxError: invalid syntax
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
==================================================================== 1 error in 0.11 seconds =====================================================================

pytest -v test.py throwing an error

=========================================================================== test session starts ============================================================================
platform linux2 -- Python 2.7.18, pytest-4.6.9, py-1.8.1, pluggy-0.13.0 -- /usr/bin/python2
cachedir: .pytest_cache
rootdir: /home/yev/Documents/PyProjects/tinypythonprojects/tiny_python_projects/01_hello
collected 0 items / 1 errors

================================================================================== ERRORS ==================================================================================
_________________________________________________________________________ ERROR collecting test.py _________________________________________________________________________
/usr/lib/python2.7/dist-packages/_pytest/python.py:507: in _importtestmodule
mod = self.fspath.pyimport(ensuresyspath=importmode)
/usr/lib/python2.7/dist-packages/py/_path/local.py:701: in pyimport
import(modname)
E File "/home/yev/Documents/PyProjects/tinypythonprojects/tiny_python_projects/01_hello/test.py", line 21
E out = getoutput(f'python3 {prg}')
E ^
E SyntaxError: invalid syntax
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
========================================================================= 1 error in 0.09 seconds ==========================================================================

I'm unsure why it's using python2, and how to fix this.

I'm using Ubuntu 20.04.

itictactoe No winner if win at the last turn

Hi,

In chapter 22 Tic-Tac-Toe redux: An interactive version with type hints, the solution doesn't declare a winner if they win at the last turn. Here's the output from tiny_python_projects/22_itictactoe/solution1.py

-------------
| X | O | O |
-------------
| X | O | X |
-------------
| 7 | X | O |
-------------
Player X, what is your move? [q to quit]: 7
All right, we'll call it a draw.

The program should check for a draw after displaying a new board and finding a winner.

The term 'python3' is not recognized as the name of a cmdlet

I am running python 3.11.0 and when I run "pytest -xv test.py" I get this red error under the "test_runnable" FAILURES:
E assert "'python3' is...r batch file." == 'Hello, World!'
E - Hello, World!
E + 'python3' is not recognized as an internal or external command,
E + operable program or batch file.

I try to run the command "python3 hello.py" and I get this error
python3 : The term 'python3' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1

  • python3 hello.py
  •   + CategoryInfo          : ObjectNotFound: (python3:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException
    
    

Any help on how I can fix this would be great.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.