Python Workout
eBook - ePub

Python Workout

50 ten-minute exercises

Reuven M. Lerner

Condividi libro
  1. 248 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Python Workout

50 ten-minute exercises

Reuven M. Lerner

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

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

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Python Workout è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Python Workout di Reuven M. Lerner in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Computer Science e Programming in Python. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Editore
Manning
Anno
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...

Indice dei contenuti