Tiny Python Projects
eBook - ePub

Tiny Python Projects

Learn coding and testing with puzzles and games

Ken Youens-Clark

Partager le livre
  1. 440 pages
  2. English
  3. ePUB (adapté aux mobiles)
  4. Disponible sur iOS et Android
eBook - ePub

Tiny Python Projects

Learn coding and testing with puzzles and games

Ken Youens-Clark

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres
Citations

À propos de ce livre

"Tiny Python Projects is a gentle and amusing introduction to Python that will firm up key programming concepts while also making you giggle."—Amanda Debler, Schaeffler Key Features
Learn new programming concepts through 21-bitesize programs
Build an insult generator, a Tic-Tac-Toe AI, a talk-like-a-pirate program, and more
Discover testing techniques that will make you a better programmer
Code-along with free accompanying videos on YouTube Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications. About The Book
The 21 fun-but-powerful activities in Tiny Python Projects teach Python fundamentals through puzzles and games. You'll be engaged and entertained with every exercise, as you learn about text manipulation, basic algorithms, and lists and dictionaries, and other foundational programming skills. Gain confidence and experience while you create each satisfying project. Instead of going quickly through a wide range of concepts, this book concentrates on the most useful skills, like text manipulation, data structures, collections, and program logic with projects that include a password creator, a word rhymer, and a Shakespearean insult generator. Author Ken Youens-Clark also teaches you good programming practice, including writing tests for your code as you go. What You Will Learn
Write command-line Python programs
Manipulate Python data structures
Use and control randomness
Write and run tests for programs and functions
Download testing suites for each project This Book Is Written For
For readers familiar with the basics of Python programming. About The Author
Ken Youens-Clark is a Senior Scientific Programmer at the University of Arizona. He has an MS in Biosystems Engineering and has been programming for over 20 years. Table of Contents 1 How to write and test a Python program
2 The crow's nest: Working with strings
3 Going on a picnic: Working with lists
4 Jump the Five: Working with dictionaries
5 Howler: Working with files and STDOUT
6 Words count: Reading files and STDIN, iterating lists, formatting strings
7 Gashlycrumb: Looking items up in a dictionary
8 Apples and Bananas: Find and replace
9 Dial-a-Curse: Generating random insults from lists of words
10 Telephone: Randomly mutating strings
11 Bottles of Beer Song: Writing and testing functions
12 Ransom: Randomly capitalizing text
13 Twelve Days of Christmas: Algorithm design
14 Rhymer: Using regular expressions to create rhyming words
15 The Kentucky Friar: More regular expressions
16 The Scrambler: Randomly reordering the middles of words
17 Mad Libs: Using regular expressions
18 Gematria: Numeric encoding of text using ASCII values
19 Workout of the Day: Parsing CSV files, creating text table output
20 Password strength: Generating a secure and memorable password
21 Tic-Tac-Toe: Exploring state
22 Tic-Tac-Toe redux: An interactive version with type hints

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que Tiny Python Projects est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  Tiny Python Projects par Ken Youens-Clark en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Informatica et Programmazione in Python. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.

Informations

Éditeur
Manning
Année
2020
ISBN
9781638350835

1 How to write and test a Python program

Before you start working on the exercises, I want to discuss how to write programs that are documented and tested. Specifically, we’re going to
  • Write a Python program to say “Hello, World!”
  • Handle command-line arguments using argparse
  • Run tests for the code with Pytest.
  • Learn about $PATH
  • Use tools like YAPF and Black to format the code
  • Use tools like Flake8 and Pylint to find problems in the code
  • Use the new.py program to create new programs

1.1 Creating your first program

It’s pretty common to write “Hello, World!” as your first program in any language, so let’s start there. We’re going to work toward making a version that will greet whichever name is passed as an argument. It will also print a helpful message when we ask for it, and we’ll use tests to make sure it does everything correctly.
In the 01_hello directory, you’ll see several versions of the hello program we’ll write. There is also a program called test.py that we’ll use to test the program.
Start off by creating a text file called hello.py in that directory. If you are working in VS Code or PyCharm, you can use File > Open to open the 01_hello directory as a project. Both tools have something like a File > New menu option that will allow you to create a new file in that directory. It’s very important to create the hello.py file inside the 01_hello directory so that the test.py program can find it.
Once you’ve started a new file, add this line:
print('Hello, World!')
It’s time to run your new program! Open a terminal window in VS Code or PyCharm or in some other terminal, and navigate to the directory where your hello.py program is located. You can run it with the command python3 hello.py--this causes Python version 3 to execute the commands in the file named hello.py. You should see this:
$ python3 hello.py Hello, World!
Figure 1.1 shows how it looks in the Repl.it interface.
Figure 1.1 Writing and running our first program using Repl.it
If that was your first Python program, congratulations!

1.2 Comment lines

In Python, the # character and anything following it is ignored by Python. This is useful for adding comments to your code or temporarily disabling lines of code when testing and debugging. It’s always a good idea to document your programs, indicating the purpose of the program or the author’s name and email address, or both. We can use a comment for that:
# Purpose: Say hello print('Hello, World!')
If you run this program again, you should see the same output as before because the “Purpose” line is ignored. Note that any text to the left of the # is executed, so you can add a comment to the end of a line if you like.

1.3 Testing your program

The most fundamental idea I want to teach you is how to test your programs. I’ve written a test.py program in the 01_hello directory that we can use to test our new hello.py program.
We will use pytest to execute all the commands and tell us how many tests we passed. We’ll include the -v option, which tells pytest to create “verbose” output. If you run it like this, you should see the following output as the first several lines. After that will follow many more lines showing you more information about the tests that didn’t pass.
Note If you get the error “pytest: command not found,” you need to install the pytest module. Refer to the “Installing modules” section in the book’s introduction.
$ pytest -v test.py ============================= test session starts ============================== ... collected 5 items test.py::test_exists PASSED [ 20%] ① test.py::test_runnable PASSED [ 40%] ② test.py::test_executable FAILED [ 60%] ⑱ test.py::test_usage FAILED [ 80%] ④ test.py::test_input FAILED [100%] â‘€ =================================== FAILURES ===================================
① The first test always checks that the expected file exists. Here the test looks for hello.py.
② The second test tries to run the program with python3 hello.py and then checks if the program printed “Hello, World!” If you miss even one character, like forgetting a comma, the test will point out the error, so read carefully!
⑱ The third test checks that the program is “executable.” This test fails, so next we’ll talk about how to make that pass.
④ The fourth test asks the program for help and doesn’t get anything. We’re going to add the ability to print a “usage” statement that describes how to use our program.
â‘€ The last test checks that the program can greet a name that we’ll pass as an argument. Since our program doesn’t yet accept arguments, we’ll need to add that, too.
I’ve written the tests in an order that I hope will help you write the program in a logical fashion. If the program doesn’t pass one of the tests, there’s no reason t...

Table des matiĂšres