31 Floating point to whole number conversion 34 Whole number to floating point conversion 35 Text strings fail in int and float 35 Creating our first calculator file 36 New functions – s
Trang 2Python Projects for Kids
Unleash Python and take your small readers on an adventurous ride through the world of programming
Jessica Ingrassellino
BIRMINGHAM - MUMBAI
Trang 3Python Projects for Kids
Copyright © 2016 Packt Publishing
All rights reserved No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews
Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented However, the information contained in this book is sold without warranty, either express or implied Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals However, Packt Publishing cannot guarantee the accuracy of this information.First published: April 2016
Trang 5About the Author
Jessica Ingrassellino is a multi-talented educator, business leader, and technologist She received her EdD from Teachers College, Columbia University for music education with an emphasis on assessment
Jessica is currently employed as the lead software engineer in testing at Bitly, New York City She transitioned from a teaching career of 10 years to a technology career through a balance of freelance work and social media exposure Jessica's current work focuses on using Python to develop automated testing tools She is an ASTQB certified quality assurance engineer with experience in testing web, mobile, and backend applications
In addition to working at Bitly, Jessica remains committed to education and
has founded http://www.teachcode.org/, a nonprofit that teaches computer programming skills to teachers and students in urban or underserved populations through Python and 2D game programming This new initiative will give teachers the support they need through a standards-referenced curriculum, student-engaging activities, and access to experts in the field of technology
I would like to thank my students for allowing me to have such
fun teaching them Python and learning from their experiences as
new programmers I would also like to thank Cathy Kross and
Alice McGowan for being willing to have me in their classes and
school and interrupting their daily lives with my code-teaching
experiments Finally, I would like to thank my husband, Nick, for
believing in me and helping me through some major writer's block
He never loses faith in me, and for that, I am eternally grateful
Trang 6About the Reviewer
David Whale is a software developer who lives in Essex, UK He started coding
as a schoolboy aged 11, inspired by his school's science technician to build his own computer from a kit These early experiments lead to some of his code being used in
a saleable educational word game when he was only 13
David has been developing software professionally ever since, mainly writing
embedded software that provides intelligence inside electronic products, including automated machinery, electric cars, mobile phones, energy meters, and wireless doorbells
These days, David runs his own software consultancy called Thinking Binaries, and he spends about half of his time helping customers design software for new electronic products, many of which use Python The rest of the time, he volunteers for The Institution of Engineering and Technology, running training courses for teachers, designing and running workshops and clubs for school children, running workshops and talks at meet-up events all round the UK, and generally being busy with his Raspberry Pi, BBC micro:bit, and Arduino
David was the technical editor of Adventures in Raspberry Pi, John Wiley & Sons, the coauthor of Adventures in Minecraft, and he is a regular reviewer and editor
of technical books for a number of book publishers
I was really pleased to be asked to review this exciting new coding
book for children Python is an excellent language for children to
learn from a young age, and Jessica has done a great job at helping
readers take their first few steps in coding with Python I hope you
will be inspired by the code and ideas in this book and come up
with your own ideas to enhance and develop all of the programs
further—this is just the start of your exciting new creative journey
into coding with Python!
Trang 7eBooks, discount offers, and more
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy Get in touch with us at customercare@packtpub.com for more details
At www.PacktPub.com, you can also read a collection of free technical articles, sign
up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library Here, you can search, access, and read Packt's entire library of books
Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser
Trang 8Table of Contents
Preface vii Chapter 1: Welcome! Let's Get Started 1
Write and run your first program in the command line 7
Summary 11
Chapter 2: Variables, Functions, and Users 13
Variables 13
Strings 15 Integers 16
Functions 19
Trang 9Table of Contents
[ ii ]
Summary 29
Chapter 3: Calculate This! 31
Floating point to whole number conversion 34 Whole number to floating point conversion 35 Text strings fail in int() and float() 35 Creating our first calculator file 36
New functions – subtraction, multiplication, and division 37
Subtraction 37
Division 39
Summary 42
Chapter 4: Making Decisions – Python Control Flows 43
if 46elif 47else 49
Loops 50
while 50Global variables and the quit() function 50
Using the while loop to control the program 52for 53
Trang 10Comparing numbers – the hard version 72
Chapter 6: Working with Data – Lists and Dictionaries 79
Dictionaries 86
Removing items from the dictionary 90
Summary 93
Chapter 7: What's in Your Backpack? 95
Trang 11Table of Contents
[ iv ]
Summary 110
pygame 120
while loop – viewing the screen 125
Moving objects with the keyboard 128
Summary 129
Trang 12Table of Contents
Collision of the ball with the top and the bottom of the screen 146 Collision of the paddle with the top and the bottom of screen 147 Collision of the ball with the paddles 148
Summary 154
Trang 13Table of Contents
[ vi ]
Trang 14As you can guess from the title, this book is designed to teach the basic concepts of Python to kids This book uses several mini projects so that kids can learn how to solve problems using Python
Python has grown to become a very popular language for programming web apps, analyzing data, and teaching people how to write code Python is known for being a simple language to use because it is read much like natural languages, yet it is able
to do data analysis very quickly, making it a great language to create websites that handle a lot of data Another nice thing about Python that makes it fun to use is that people have been working on game libraries, such as pygame, so that people can create graphics programs with Python The use of simple graphics to make short games is a fun way to learn programming constructs and is especially good for visual learners
What this book covers
Chapter 1, Welcome! Let's Get Started, discusses Python and setting up a Python
development environment on Windows, Mac, and Linux operating systems
Chapter 2, Variables, Functions, and Users, covers Python data types and functions,
as well as how to program Python to get information from the user, store that
information, and use it later
Chapter 3, Calculate This!, uses Python to make a calculator that has multiple
mathematical functions We also learn about working in our file structure and the proper way to save code files
Chapter 4, Making Decisions – Python Control Flows, covers the use of if, elif, and
else, as well as the use of for and while loops, in order to help create programs that make decisions based on user actions
Trang 15[ viii ]
Chapter 5, Loops and Logic, builds upon what we have learned in the previous chapters
and allows us to build a number guessing game We will build easy and difficult versions of the game
Chapter 6, Working with Data – Lists and Dictionaries, explains how to use lists
and dictionaries to store data The differences between lists and dictionaries are explained, and we spend time building small lists and dictionaries as well
Chapter 7, What's in Your Backpack?, allows us to use functions, loops, logic, lists and
dictionaries to build a different kind of guessing game We will also learn about nesting dictionaries and lists
Chapter 8, pygame, talks about a popular graphical library that is used in Python
to make small games We will learn the fundamental aspects of this library and experiment with some code
Chapter 9, Tiny Tennis, this game is a clone of a popular game We will re-create the
game using all of the skills that we have learned throughout the book This is the major project of the book
Chapter 10, Keep Coding!, shows you all the opportunities that will arise once you read
this book
Appendix, Quick Task Answers, has the answers to all the quick task questions within
the chapters
What you need for this book
This book can be used with Windows 10, Mac OS X, or Ubuntu Linux operating systems Other versions of these operating systems may work; however, this book has been written specifically to address these systems Additionally, you will need the Internet to download some tools, such as recommended text editors, for your operating system All recommended downloads are open source
Who this book is for
This book is for kids who are ready to move from graphically-based programming environments, such as Scratch, and into text-based environments Kids who are ready to create their own projects will engage with this book, especially those who have played games No prior programming experience is needed to complete the projects in this book; this book is for kids aged 10 years and above, who are ready to learn about Python programming
Trang 16Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information Here are some examples of these styles and an explanation of their meaning
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"Why don't you try giving the computer the name variable with your name and then the height variable with your height?"
A block of code is set as follows:
def name():
first_name = input('What is your first name?')
print('So nice to meet you, ' + first_name)
name()
Any command-line input or output is written as follows:
python
>>>print("Hello, world!")
Warnings or important notes appear in a box like this
Tips and tricks appear like this
Reader feedback
Feedback from our readers is always welcome Let us know what you think about this book—what you liked or disliked Reader feedback is important for us as it helps
us develop titles that you will really get the most out of
To send us general feedback, simply e-mail feedback@packtpub.com, and mention the book's title in the subject of your message
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide at www.packtpub.com/authors
Trang 17Downloading the example code
You can download the example code files for this book from your account at
http://www.packtpub.com If you purchased this book elsewhere, you can visit
http://www.packtpub.com/support and register to have the files e-mailed directly
to you
You can download the code files by following these steps:
1 Log in or register to our website using your e-mail address and password
2 Hover the mouse pointer on the SUPPORT tab at the top.
3 Click on Code Downloads & Errata.
4 Enter the name of the book in the Search box.
5 Select the book for which you're looking to download the code files
6 Choose from the drop-down menu where you purchased this book from
7 Click on Code Download.
You can also download the code files by clicking on the Code Files button on the
book's webpage at the Packt Publishing website This page can be accessed by entering
the book's name in the Search box Please note that you need to be logged in to your
Packt account
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
• WinRAR / 7-Zip for Windows
• Zipeg / iZip / UnRarX for Mac
• 7-Zip / PeaZip for Linux
Downloading the color images of this book
We also provide you with a PDF file that has color images of the screenshots/
diagrams used in this book The color images will help you better understand the changes in the output You can download this file from http://www.packtpub.com/sites/default/files/downloads/PythonProjectsforKids_ColorImages.pdf
Trang 18Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us By doing so, you can save other readers from frustration and help us improve subsequent versions of this book If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form
link, and entering the details of your errata Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added
to any list of existing errata under the Errata section of that title
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field The required
information will appear under the Errata section.
Please contact us at copyright@packtpub.com with a link to the suspected
pirated material
We appreciate your help in protecting our authors and our ability to bring you valuable content
Questions
If you have a problem with any aspect of this book, you can contact us at
questions@packtpub.com, and we will do our best to address the problem
Trang 20Welcome! Let's Get Started
If you've picked up this book, then you are taking your first step toward building amazing projects using code Some of you might want to make games, while others might want to learn more about how all of your favorite websites and apps actually work If you follow the exercises in this book, you'll be able to do the following:
• Create fun games to play with your family and friends
• Learn about the inner workings of your apps
• Learn how to take charge of your computer
Python projects for you
In this book, you will learn Python code Specifically, you will learn how to design
a computer program from the very beginning It doesn't matter if you have never coded before because each exercise in this book is designed to get you ready to code If you have coded before, you will find that this book has some really helpful exercises that can help make your code even better Additionally, there are some more advanced projects toward the end of the book, which you should definitely take a look at!
What can you do with Python?
If you take a look at the Web and search for Python jobs, you will find that many of the highest paying jobs are in Python Why?
Python is a very flexible and powerful language in the following ways:
• It can be used in order to go through millions of lines of data
• Python can search for information on a website without having to go to the website itself
• It is even used to host and design websites
Trang 21Welcome! Let's Get Started
[ 2 ]
So, what will it take to learn Python? If you have never programmed, you will probably want to follow each lesson in order so that you can build the skills you need to make a game or another kind of computer program The final project in this book will be a game If you have some other programming experience, such as making modifications to your computer games, using programs such as Scratch or Logo or trying some of the free programming classes on the Internet, then you might decide to skim this book first to see what you already know It is still recommended that you follow the contents of this book in the order they are presented, as each project builds on the projects that were explained in the previous chapter
Why you should learn Python
Python teaches all of the basics of an object-oriented programming language, and it
is still very powerful In fact, many Internet companies, most notably Mozilla Firefox and Google, use Python in part or all of their products! Python has also been used to build Django, a free framework to make websites
It has also been used to build many small video games by people learning about
it as well as more advanced programmers Finally, Python can be used to quickly read and analyze millions of lines of data very quickly! By learning Python, you will
be prepared to build a variety of interesting projects, and you will gain the skills necessary to learn other programming languages if you choose to do so
The prerequisites of Python
Before you get started, you need the following basic materials:
• A computer that can run Windows 7 or higher, Mac OS X 10.6 or higher,
or Ubuntu 12.4 or higher You may also use a Raspberry Pi as it comes
preinstalled with Python, pygame, and the other software needed to
complete the projects in this book
• An Internet connection is necessary as some of the software you need to install on your computer might not be installed already For example,
Windows operating systems do not come with Python preinstalled, so
an Internet connection will be needed; pygame is also not preinstalled on Windows, Mac, or Linux systems
• Along with an Internet connection, you will also need a web browser, such as Firefox, Safari, Chrome, or Internet Explorer, which will allow you to visit the Python documentation pages
Trang 22Chapter 1
All of the code samples in this book are available for download on the Packt Publishing website
Setting up your computer
There are many different computer operating systems, but the most common
operating systems are Macintosh (Mac), Windows, and Linux You should follow the installation steps that go with your operating system There are some subtle but important differences between the systems
For the projects in this book, we will be using Python 2.7 While there are higher versions than this (3.x), these versions do not work dependably with pygame on Windows, Mac, or Ubuntu Linux as yet However, this book will be written to use conventions that work in both versions of Python so that projects are easily completed on Raspberry Pi (which uses Python 3.x that's been specially configured with pygame) with just a few modifications These modifications will be duly noted
For Mac and Ubuntu Linux users
Mac and Linux systems share enough similarities that people who use either Mac
or Linux can follow the same set of instructions These instructions will make note
of any differences between Mac and Ubuntu Linux
Python 2.7
At the time of writing, Mac OS X El Capitan comes with Python 2.7 preinstalled,
so nothing extra needs to be done at this point
Ubuntu Linux 15.10 has Python 2.7.10 installed by default, so users of this latest (as of writing this) version of Linux also need to do nothing extra at this point
Terminal – the command line and the Python shell
Mac and Ubuntu Linux users have Python by default, but finding Python is tricky if
you don't know where to look There is a program called Terminal on both Mac and
Linux operating systems This program allows you to exercise a lot of control over your computer in these ways:
• On a Mac, go to Finder | Applications | Utilities and click on Terminal
The terminal application will open up, and you should see a small, white window on your screen
Trang 23Welcome! Let's Get Started
[ 4 ]
• Ubuntu users can search for terminal on their desktops, and the program
will show up in their Start menu When you click on the terminal, you will
see a small, black window on your screen
• The terminal also functions as a Python shell when a command is given to run Python We will learn about this later
Text editor
A text editor is a helpful tool for writing and editing Python programs The terminal
is a nice place to test snippets of Python code, but when we want to edit and save the code in order to use it over again, we will need a text editor Although both Mac and Linux systems come with a text editor, there are some very nice, free editors
that have good features jEdit is one of these editors.
For Mac and Linux, go to http://www.jedit.org/ and download jEdit Follow the installation instructions
To successfully complete all of the exercises in this book, you will often need to keep both the terminal and text editor open at the same time on your screen
Trang 24Chapter 1
This is what the text editor application, jEdit, looks like in Mac and Linux:
For Windows users
Windows users, this setup might require help from your parents Since Python is not installed by default on Windows, some system adjustments need to be made
to successfully run Python on your computer If you are feeling uncertain about performing these system changes yourself, make sure to ask for help:
1 First, you will need to download version 2.7.11 of Python
Use the official Python website for the latest releases for Windows
at https://www.python.org/downloads/release/
python-2711/
With Windows, you need to figure out if you are running 32-bit or 64-bit so that you can download the correct version of Python To help you to determine which one is correct, visit
and-64-bit-windows#1TC=windows-7
http://windows.microsoft.com/en-gb/windows/32-bit-Download x86only if your computer is running 32-bit Windows
Most users will download the x86-64 version of Python
Trang 25Welcome! Let's Get Started
[ 6 ]
2 Choose the executable installer, and you will see the download progress
3 When the download is complete, you will see a prompt to run Python
Click on Run.
4 An install prompt will come up, and when it does, look at the bottom of the
window and click on the box next to Add Python 2.x to Path Then, select
Install Now.
5 Follow the installation instructions Each step may take a few minutes Once the installation is done, you will have an icon for Python 2.7.11, which you can find by searching for Python in the Windows search bar This will open a special Python shell from where you can run and test the Python code
Command prompt
In Windows 10, you will see a terminal called the command prompt The command
prompt is significantly different in Windows than it is on Mac or Linux
To find the command prompt in Windows 10, perform these steps:
1 Go to the search bar at the bottom of the screen and search for cmd
Trang 26Chapter 1
To get Notepad++, perform these steps:
1 Go to https://notepad-plus-plus.org/and download the latest version
2 Once the program has been downloaded, click on Run.
Notepad++ looks like this:
Write and run your first program in the command line
Now that you are set up, it is time to write your first line of code in Python!
This line of code is almost a tradition for people who are programming for the first time, and it allows us to use one of the most basic, but most useful, functions
in the Python language
First, you need to start running a Python shell On Mac or Linux, open your terminal and type this:
python
In the Mac or Ubuntu terminal, your resulting Python shell will look like this:
>>>
In Windows, type Python in the search bar at the bottom of the page Then,
select Python 2.7.11 from your apps You will also have a Python shell open:
>>>
Once you see this symbol, your computer is now ready to work with the Python code In your terminal or IDLE, type the following:
>>>print("Hello, world!")
Trang 27Welcome! Let's Get Started
[ 8 ]
Once you have typed this, double-check to make sure that all of the spaces are
exactly as they've been written In Python, every space actually matters Every
punctuation mark matters Once you have checked your code, hit Enter.
What is your result or the output of your code? If the output looks like the
following image, then great! You typed all of your code properly so the computer will understand what you want it to do The expected output will be similar to what
is shown here:
For Windows users, the output window will look like this:
So, if your output does not look like the preceding code, you need to figure out what's wrong with it Here are some of the reasons for this:
• Did you make a typing error?
• Did you forget to use parenthesis or round brackets () for the words 'Hello, world!'?
• Did you forget to use the ''single quotation marks for Hello, world!?
If you still have a problem, compare your code to the sample input code and fix any mistakes Then, try to run the code again
Trang 28Chapter 1
Python is what is called a case-sensitive language Python cares about
uppercase, lowercase, and whitespace You need to watch what you type You might get some strange messages from your computer if you make a typing mistake or a syntax error
Make yourself a work folder
Before we get started on any large projects, we need to make a work folder In the next chapter, you will start writing whole files of code that need to be run; therefore, we will need a place to put those files Since you are setting up now, let's make a folder
If you are very good at getting around your computer, you can put your folder wherever you want to
If you are not too good at getting around your computer, you will probably want to put your folder on your desktop
On both Mac and Windows machines, you can right-click somewhere on your desktop wallpaper, and a box will pop up with several options One of the options
will say New, and when you hover over New, you will get several other options Choose New Folder, and a new folder icon will appear on your desktop It will be
named untitled, so you should give it a better name
To find your folder in the Mac or Linux terminals, respectively, open one of them and perform these steps:
1 Run the cd command until you are at the root, which is often the name you have given to your computer You may need to run the command three
Trang 29Welcome! Let's Get Started
[ 10 ]
A quick task for you
Now that you have finished this chapter, can you answer these questions?
Q1 What is a terminal (Mac/Linux) or command prompt (Windows)?
1 A terminal is used to put data into or get data out of a computer without using the icons on the desktop
2 A terminal can be used to write computer programs
3 A terminal can be used to do complex work, such as giving hints on
Python code
4 A terminal can do all of the above
Q2 When you first open the terminal/command prompt, what do you need to do so that you can start reading and writing the Python code?
1 Start typing the code
2 Type the word python
3 Wait for Python to start
4 None of the above; do something different
Q3 How is the Python shell different from the command line?
1 They are exactly the same
2 The command line cannot run Python commands
3 The Python shell is started by typing the word python into the
command line
4 The Python shell can be used to test lines of Python code
Compare your answers with those you find at the back of the book
Trang 30Chapter 1
Summary
If you are reading this, it is because you have made it through some of the tricky work of getting ready to learn to program projects with Python Congratulations! Setting it up is always tough Hopefully, you learned a bit more about the tools on your computer, such as the text editor and terminal that every programmer uses
to do their daily work Also, you learned about the Python print() function, and you should now be able to print out messages in your Python shell The fun is just beginning as we have so much more to learn!
In the next chapter, you will learn about the building blocks of Python programs We'll start with variables and learn about all the different kinds of information we can put in them Then, we will build some functions that put these variables together and help us make blocks of code that have special jobs Finally, we will even learn how to make a computer ask a user questions and store their answers so that our programs can become interactive!
Trang 32Variables, Functions,
and Users
In the previous chapter, you learned how to install Python on your computer
You also learned how to use the print statement in Python and printed some
messages using your Python shell We are now going to jump into a lot of details
so that we can build our first project together It will include the following:
A variable is when one letter or word is used to represent a different letter,
word, number, or value One way to think of a variable is to imagine that you are programming a computer so that it can make memories For example, my name is Jessica If I am writing a computer program and I want that program to remember
my name, I will assign my name to a variable This will look like name = 'Jessica' The variable is name Jessica in the memory
Perhaps I would like the computer to remember something else about me as well Maybe I want the computer program to remember that I am 64 inches, or roughly
128 cm, tall I will say height_inches = 64 or height_centimeters = 128 The variables here are height_inches and height_centimeters The memories are my height in inches and my height in centimeters
Why don't you try giving a computer the name variable with your name and then a
height variable with your height?
Trang 33Variables, Functions, and Users
[ 14 ]
First, open your Python shell and type the following code:
name = 'yourname'
height = 'your height'
Now that the variables are stored, you can type print(name) or print(height) Since you created a memory for the computer with your name and your height, the computer will print the memory that you gave it If you take a look at the screenshot from my Python shell, you will see that the computer printed the memories that I assigned it Notice that we do not use single quotes around the variable names:
If the values, or memories, that you assigned to the variables are printed in your Python terminal, then it is perfect If not, you may have an error There are a lot of reasons due to which an error can occur You may have typed your variable name or your information in a way that breaks the Python convention Some common errors include using capital letters
Naming variables – conventions to follow
There are some conventions that are used to name variables in Python It might seem silly to have guidelines about naming things, but following the conventions is really important because it helps other people read your code Also, the Python shell is designed to work with the conventions
To avoid errors, your variable names should use lowercase letters If your variable uses more than one word, such as the height_inches variable, then it should have underscores to connect the words together
Trang 34Chapter 2
If you use two words to name your variable and do not connect them with an
underscore, you will get an error Take a look at the following screenshot and see where it says SyntaxError: invalid syntax Notice this error occurred because the height centimeters variable did not have an underscore to connect the words:
What can variables remember?
Python variables can be programmed to remember all kinds of information! You will notice in our original example that we stored a word and then a number There are three different kinds of information that we will be using to build our calculator in
Chapter 3, Calculate This!, strings, integers, and floats Each bit of information is input
and output a little differently
Strings
In Python, a string is any piece of data that's captured between two single quote marks, that is, these symbols '' Sometimes, double quotation marks are used For example, I can have a string variable that looks like this:
sentence = 'This is a sentence about Python.'
This string variable contains letters and words Most string variables do However, you can store a number as a string also as long as that number is in single quotes:
number_string = '40'
If we can store all kinds of information as strings, why do we need other data types? Well, when we store numbers as strings, we cannot do math with the numbers! Type this problem into your Python shell, and then you will see why we need data types besides strings:
first_number = '10'
second_number = '20'
print(first_number + second_number)
Trang 35Variables, Functions, and Users
[ 16 ]
What happened in your Python shell? You might have expected the printed output
to be 30 since 10 plus 20 is equal to 30 However, Python saw each number as a text string and simply put the two text strings next to each other So, your result was probably 1020 Here is how this looks in the Python shell:
Integers
Computers are really great at math, and math will allow us to execute more
complicated programs, such as games Python stores whole number data as integers.Let's start with integers:
• An integer is simply a plain whole number If we want to make our variables store integers, we would take away the quotes
• Then, when we add the two variables and print the output, we will get a mathematical result
Try it out! Let's do some math with these variables:
1 Type the following two variables in your Python shell:
Trang 36Chapter 2
Floating point numbers (floats)
Hopefully, you now better understand how Python works with integers
(whole numbers) However, people and computers often need to work in
fractional numbers In Python, these numbers are called floating point numbers,
but many people call them floats as a shortcut:
• Floats are actually a really fancy way of saying numbers using decimals
• Floats are called this because the decimal point can be anywhere among the numbers, allowing for decimals of many different sizes
• Setting numbers as floats allows us to do more complicated math using fractional numbers
• To set a variable to a float, you don't have to do anything special or different from what you did to set the integers
• Python knows that a number input (a variable, for example) with a decimal point is a float, and Python will output the answers as a float if the problem
Trang 37Variables, Functions, and Users
[ 18 ]
This time, in your Python shell, you should notice that Python recognized the variable input as floating point numbers and was able to output the complete and correct answer without us having to use additional instructions The output from your print
statement should be 30.6, as you can see in this screenshot of the Python shell:
Combining strings, integers, and floats
So far, we have only attempted to combine items that share a data type We have added two strings, two integers, or two floats What happens when you try to add two different types of information, such as a string and an integer? In your Python shell, type the following lines of code and pay attention to the output:
first_number = '10'
second_number = 20
print(first_number + second_number)
You are likely to notice the error that you receive The important line to pay attention
to is TypeError: cannot concatenate 'str' and 'int' objects Python is telling us that it cannot work with these two different data types and that makes sense So, if you do make a mistake in your typing or try to execute an operation in two different data types, you may get an error like this:
Trang 38Before we begin building functions of our own, we need to also know that Python has a lot of amazing functions that are built in Some of Python's functions are things
we will use all the time Others we won't talk about in this book, but as you become a more skilled programmer, you will learn more about Python's built-in functions
Built-in functions
Here's something about some built-in functions and what they do:
• int(): This converts a string or a float into an integer
• float(): This converts a string or an integer into a float
• raw_input(): This gets information from a user and stores it in the computer
to use later
• str(): This converts an integer, float, or other information into a string
• help(): This provides access to Python's help
Trang 39Variables, Functions, and Users
[ 20 ]
We will be using these functions to help us build our first project in the next chapter
If you are curious about what other functions are built in or if
you want to know more, you can go to the Python documents at
The first line of this code is new, so we need to understand what it means:
• The first thing to notice is the word def In Python, this is short for define, and it is used to define a new function
• The next thing to notice is the name of the function The name of the function has the same guidelines as the names of variables A function needs to use lowercase letters, and when it has many words, there need to be underscores between each word
• After the name of the addition() function, you will notice the parentheses
() These are empty in this function, but sometimes they are not empty
Even if they are, the parentheses must ALWAYS be a part of the function
that you create
• Finally, the first line of the function ends with a colon The colon (:), ends the first line of the function
A function can be short, such as this addition() function, which is only four lines in total, or it can be really long Every line after the first line in a Python function needs
to be indented using spaces When we work on building our own functions in the next section of this chapter, you will learn how to make indents in your Python shell
We will also discuss proper spacing in the text editor
Trang 40Chapter 2
There are a lot of new details to remember in order to write a function What
happens if you forget a detail? If you forget to indent a line, Python will let you know and output an error Your function will not run, and your code will not work
Python's use of indentation is known as whitespace, and there are rules about
whitespace use in Python
By now, you are very familiar with doing additions in Python, so we will keep working with the addition code There are special considerations in order to write functions in the Python shell Because a function is a block of code, we want to follow these guidelines when we are trying to perform functions in the shell:
• After you type the first line and press Enter, make sure you press Tab before
you type each line
• When you have completed typing all the lines, hit Enter twice so that the
Python shell knows that you are done creating the function
In your Python shell, type the addition() function exactly as it appears here:
def addition():
first_number = 30
second_number = 60
print(first_number + second_number)
Notice how the function looks in the Python shell:
Now that you have typed your function, you need to learn how to use the function
To use the function in the Python shell, type the name of the function and the
parentheses:
addition()