Python Workout
eBook - ePub

Python Workout

50 ten-minute exercises

Reuven M. Lerner

Share book
  1. 248 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Python Workout

50 ten-minute exercises

Reuven M. Lerner

Book details
Book preview
Table of contents
Citations

About This Book

The only way to master a skill is to practice. In Python Workout, author Reuven M. Lerner guides you through 50 carefully selected exercises that invite you to flex your programming muscles. As you take on each new challenge, you'll build programming skill and confidence.Summary
The only way to master a skill is to practice. In Python Workout, author Reuven M. Lerner guides you through 50 carefully selected exercises that invite you to flex your programming muscles. As you take on each new challenge, you'll build programming skill and confidence. The thorough explanations help you lock in what you've learned and apply it to your own projects. Along the way, Python Workout provides over four hours of video instruction walking you through the solutions to each exercise and dozens of additional exercises for you to try on your own. Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications. About the technology
To become a champion Python programmer you need to work out, building mental muscle with your hands on the keyboard. Each carefully selected exercise in this unique book adds to your Python prowess—one important skill at a time. About the book
Python Workout presents 50 exercises that focus on key Python 3 features. In it, expert Python coach Reuven Lerner guides you through a series of small projects, practicing the skills you need to tackle everyday tasks. You'll appreciate the clear explanations of each technique, and you can watch Reuven solve each exercise in the accompanying videos. What's inside 50 hands-on exercises and solutions
Coverage of all Python data types
Dozens more bonus exercises for extra practiceAbout the reader
For readers with basic Python knowledge. About the author
Reuven M. Lerner teaches Python and data science to companies around the world. Table of Contents1 Numeric types2 Strings3 Lists and tuples4 Dictionaries and sets5 Files6 Functions7 Functional programming with comprehensions8 Modules and packages9 Objects10 Iterators and generators

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Python Workout an online PDF/ePUB?
Yes, you can access Python Workout by Reuven M. Lerner in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in Python. We have over one million books available in our catalogue for you to explore.

Information

Publisher
Manning
Year
2020
ISBN
9781638357223

1 Numeric types

Whether you’re calculating salaries, bank interest, or cellular frequencies, it’s hard to imagine a program that doesn’t use numbers in one way or another. Python has three different numeric types: int, float, and complex. For most of us, it’s enough to know about (and work with) int (for whole numbers) and float (for numbers with a fractional component).
Numbers are not only fundamental to programming, but also give us a good introduction to how a programming language operates. Understanding how variable assignment and function arguments work with integers and floats will help you to reason about more complex types, such as strings, tuples, and dicts.
This chapter contains exercises that work with numbers, as inputs and as outputs. Although working with numbers can be fairly basic and straightforward, converting between them, and integrating them with other data types, can sometimes take time to get used to.

Useful references

Table 1.1 What you need to know
Concept
What is it?
Example
To learn more
random
Module for generating random numbers and selecting random elements
number = random.randint(1, 100)
http://mng.bz/Z2wj
Comparisons
Operators for comparing values
x < y
http://mng.bz/oPJj
f-strings
Strings into which expressions can be interpolated
f'It is currently {datetime.datetime .now()}'
http://mng.bz/1z6Z and http://mng.bz/PAm2
for loops
Iterates over the elements of an iterable
for i in range(10): print(i*i)
http://mng.bz/Jymp
input
Prompts the user to enter a string, and returns a string
input('Enter your name: ')
http://mng.bz/wB27
enumerate
Helps us to number elements of iterables
for index, item in enumerate('abc'): print(f'{index}: {item}')
http://mng.bz/qM1K
reversed
Returns an iterator with the reversed elements of an iterable
r = reversed('abcd')
http://mng.bz/7XYx

Exercise 1 ■ Number guessing game

This first exercise is designed to get your fingers warmed up for the rest of the book. It also introduces a number of topics that will repeat themselves over your Python career: loops, user input, converting types, and comparing values.
More specifically, programs all have to get input to do something interesting, and that input often comes from the user. Knowing how to ask the user for input not only is useful, but allows us to think about the type of data we’re getting, how to convert it into a format we can use, and what the format would be.
As you might know, Python only provides two kinds of loops: for and while. Knowing how to write and use them will serve you well throughout your Python career. The fact that nearly every type of data knows how to work inside of a for loop makes such loops common and useful. If you’re working with database records, elements in an XML file, or the results from searching for text using regular expressions, you’ll be using for loops quite a bit.
For this exercise
  • Write a function (guessing_game) that takes no arguments.
  • When run, the function chooses a random integer between 0 and 100 (inclusive).
  • Then ask the user to guess what number has been chosen.
  • Each time the user enters a guess, the program indicates one of the following:
    • Too high
    • Too low
    • Just right
  • If the user guesses correctly, the program exits. Otherwise, the user is asked to try again.
  • The program only exits after the user guesses correctly.
We’ll use the randint (http://mng.bz/mBEn) function in the random module to generate a random number. Thus, you can say
import random number = random.randint(10, 30)
and number will contain an integer from 10 to (and including) 30. We can then do whatever we want with number--print it, store it, pass it to a function, or use it in a calculation.
We’ll also be prompting the user to enter text with the input function. We’ll actually be using input quite a bit in this book to ask the user to tell us something. The function takes a single string as an argument, which is displayed to the user. The function then returns the string containing whatever the user entered; for example:
name = input('Enter your name: ') print(f'Hello, {name}!')
Note If the user simply presses Enter when presented with the input prompt, the value returned by input is an empty string, not None. Indeed, the return value from input will always be a string, regardless of what the user entered.
Note In Python 2, you would ask the user for input using the raw_input function. Python 2’s input function was considered dangerous, since it would ask the user for input and then evaluate the resulting string using the eval function. (If you’re interested, see http://mng.bz/6QGG.) In Python 3, the dangerous function has gone away, and the safe one has been renamed input.

Working it out

At its heart, this program is a simple application of the comparison operators (==, <, and >) to a number, such that a user can guess the random integer that the computer has chosen. However, several aspects of this program merit discussion.
First and foremost...

Table of contents