Вы находитесь на странице: 1из 23

BDM's Definitive Guide Series

Discover more of our complete


manuals on Readly today ...
J":The~...---
Complete_.,._

~thon
~<,; The Complete

Ubuntu Linux
The Complete

&C++ Manual
,_ _ ~(j
Ma ual
Manual 10 - ·• 001
001

1 1011 0
• 01 001 1000[10 1
1 10000 1 1011 11
1 10 JOI 110. 1
110 1110 0100
0 01 0 1


1 1 00 1
il 001 1 00
1 1 JO 10
10 110

~ The Complete

Google
~.....---
~<,;

Word Press
The Complete

Manual
Manual """
t!~~~..
youi skills
~

eComplete
k&White
o r
~
d-W//~Q~~~~~r$~,~ ~-
Discover liow to turn your ideas mtt ode ~
■■■■
Programming is everywhere. From clicking an icon on your desktop
~~ a we b browser to ca '/lcu lating
an d opening . t he vast d'1staQ.ces
between the stars or flying t hf6ug~ them in the latest video game.
It's one of the most important digital skills yg'u can have in the
modern world and it's only going to get bigger as we move into a
new generation of interconnected devices and mediums?'
,~ ~ ~
Starting to learn to~code isn't ea '!!I but we're here to help you get
going. In the pages of this book you can learn how to start coding
~using Python, C++, Linux scripting, FUZE B~ SIC with t ~e Raspberry
Pi, Windows batch Fitts' and Scratch. We ~lso cover the common
pitfalls and mistai&'s every coder Falls into and w~ft.o avoid them
in the Future; also where you can find help and how to experiment
with your code.
We've put together a great collection of tutorials a~ step-by-
step guides to help you understand how to start coding and what
you need t~ turn your ideas into ones and zeros t t lt will help you
become a better coder.
Learning_how to code is an on-going experienfe, wp,ere you learn
■ something l}e'N,,;every day and every time you run your cod~ · , .

~~~
~~ ~
Come with us and let's star~coding! ~
Coding and Programming

Say Hello to Python Coding on Linux

How to Set UQ Pytnon on a Mac

• Say Hello to C++


Comma no l!1ne QuicK Reference Programming with Scratch and Python
• • I
Getting Starteo witti Scratcti
Creating Scripts in Scratcn

lntrooucing ttie F.UZE P.roject l!Jsing SRrites in Scratcti

Cooing witti F.UZE


Cooing witti F.UZE BASI~ •

Working with Code

F.l'JZE BASIC Examples •


Beginner. l!inux ScriRting MistaKes

fl-i+iM·MAGl-ld=ffil&ND
Wnat is a Batcn

P.laying witn ).!aria oles


Coding and Programming )

So you want to start coding? It's not


going to be an easy road, and there are
many pitfalls along the way, but learning
to program is an amazing skill and one
that will stand you in good stead for
the future.
One of the hardest steps in learning to
code is the first: which programming
language to learn. Then, where do you
go to find the tools you need and what
do all those terms mean? Don't worry,
we're here to help you on your way.

In this section we look at what you need


to take those first tentative steps into
the world of coding.

8 Choosing a Programming Language


10 Learning to Code -Study Tips
12 Coding Tools and Resources
14 Being a Programmer

BDM's Definitive Guide Series I 3rd Edition


Index

www.bdmpublications.com BDM's Definitive Guide Series I 3rd Edition


Coding and Programming )

Learning to Code
Study Tips
Programming is one of the most valuable skills you can pick up these days,
particularly for your career prospects; and greatjust to test your brain and get to
create something cool too. When you're new to coding, it can be hard to know where
to start and it's easy to get sucked down paths that could waste a whole lot of your
time and money. If you're just getting started on your coding journey, here are some
tips to set you off in the right direction.

CHOOSE YOUR LANGUAGE LEARN WHAT BEING A CODER MEANS

It may sound obvious but • Take some time to look at the things coding languages are used for; so if you
choosing the are interested in web design, look at how JavaScript is being used on the sites
right coding or you use every day; if you are in to mobile apps, look into Java or Swift and see
programming language to
starr leamicg is impoctact
if you want the creative
!!!I
F
how they make apps work. It can also be useful and encouraging to check out
what qualified coders can expect to get paid by looking at local job sites. We
are not saying that if you learn to code Python you are immediately going to
process to be successful. If be offered a £70,000 a year job but it can help spur you on to study harder.
you need learn to code for a specific reason,
finding a job for example, then you obviously
need to learn the language that's relevant. If
you simply want to learn coding, then picking
Talent
a language like Python, that is both powerful
and relatively easy to learn, can make success
more likely.

-
• • • • • • • • • • • • • • • • • • • • • I" ••••••••••••••••••••••

~-

-----·-. ----
·-- --
·----
·------ .
•. . .='=
................................... ......................................

......................J.................................................................[.................................... .
PUT THEORY INTO PRACTICE

If you are completely new to coding, learning any programming


language can seem like a huge task. Getting completely bogged
down in pages and pages of code examples and explanations
is not likely to make the learning process much fun. In our
experience it is often better to learn through practice, or to ________
·~------ -~----
... ___
choose a task you want to perform with code, and then work
backwards to learn how to complete that task. By learning small ....
__--·--·---·
----------~
_.._ ____ ---~.
-._____________
......._ __

--·-·-·----·--·
....
,.

chunks and repeating what you have already learned at differing


intervals is called Spaced Repetition.

BDM's Definitive Guide Series I 3rd Edition


( Learning to Code - Study Tips

SET UP YOUR ENVIRONMENT STUDY IN DIFFERENT WAYS

Take some time to look at the things coding Sometimes, though admittedly not always, it's a good idea to get a more
languages are used for; so if you are interested rounded view of computer science before you dig down into more specific
in web design, look at how JavaScript is being programming language study. There are several free "Introduction to
used on the sites you use every day; if you are Computer Science" courses available online, including a great one from
in to mobile apps, look into Java or Swift and see Harvard University (via the www.edx.org website). Another study tool that can
how they make apps work. It can also be useful be useful is to play coding games. Two of the best of these types of learning
and encouraging to check out what qualified games are CodeCombat and CodinGame. Search on line to find them.
coders can expect to get paid by looking at
local job sites. We are not saying that if you : ::i::-.·~t~:=.-:1:.::·~:.~-
learn to code Python you are immediately • ....,.... ll, • •
,,., .....,
going to be offered a £70,000 a year job but it "! 1" ,.,..,.,_.,_,utc,,,o

.._,,..<OMI
can help spur you on to study harder.
f~ f;~~::;:~•::l:)•lt~ ,.,_ told
t;J. Debug ~ = El (II) = Variables l
2,1~?~-~:1,:..:;i.1...
~-----------<, f-.:..,..,.,11 .,
O► ■ N [ ~- ~ . f. ;= ~ ...:..-- . , ...... _ _ _ _ built ,

• ~ NewAptanaCom (Ruby Application)


T ii! Ruby
0
v Name

:::" ::: .::..~. ~~~,,. _,,,..,.)


►r,;, Ruby Th read - 1 (sleep) ~.::..c-:;1~: 7! :.:zt:r? Z:,.lj·
t,<11 Ruby Th read - 3 (sleep)
T r/fa Ruby Th re ad - 34 (Breakpoint at downloa ♦ 's1
: /Users/basil/Projects/Aptana/ NewApt ► ♦ @_re1
: / Users/ basil/ Projects/Aptana/ NewApt ► ♦ @_re !
:=
~
/Users/ basil/ Projects/Aptana / NewApt
:=
:=
/ Users/ basil/ Projects/Aptana/ NewApt
/ Users/ basil/ Projects / Aptana / NewApt
"4nGsbHN+pO: ...........................................................................
l := / Users/ basil/ Projects/Aptana/NewApt 1

:= / Users/ basil/ Projects / Aptana / NewApt ,.
~ ◄ ►
~ Bas il Notes .ext downl~s_conuoller .rb ~

LEARN FROM OTHER CODERS

,
........................ ....................................
The fantastic Stack Overflow is one of the best places to find
answers to problems and to ask your own questions to other
coders around the world. There are many other language-
specific forums on line but whichever site you pick, don't be

2 3 afraid to ask questions. You might find that others are a bit
snappy if you don't follow the questioning rules of that forum
but just figure out what you did wrong and learn to ask better
questions. Don't worry though, ask your questions, listen to

9 t he answers and remember to thank people for their help,


remembering to come back when you are more experienced
and answer a few questions yourself if you can.

~ stackoverflow

DON'T SET YOURSELF DEADLINES


17 TopOue-sllons -- a- . . -- __ __
--- ....,
,

___
,,,,

.....,...,_,
=...:-..,..._ ...
""TCMUU,._(OIO f'

o o ,!. Fn.icrodprtl<OO.nfNml'.«""'2,:m;VBA

If at all possible, that is. Deadlines, although a part of a 0 0 • MySOL ._oM;IIKI

professional programmers life, can definitely hurt your


progress when in the process of learning to code. This is
especially true of self-imposed deadlines, and at this point l. - . , 1)5 Kllll ln,. Xl18) No - - •
·----
·-·----
. ___ ... ___
.......
._ ., .. ...
they almost certainly will be, as they can damage your
progress when not reached. Trying to rush through any stage
........................... ·1· .............................. .
of learning to code will not do you any good, and may make
later stages harder if you do not fully understand the basics.

www.bdmpublications.com BDM's Definitive Guide Series I 3rd Editio n


Coding and Programming )

Coding Tools and


Resources
Learning to code isn't just about studying the syntax of a language and memorising
commands. If you don't have the tools and resources needed to test and express that
language, you won't be able to challenge and refine your skills.

M f' A mbmtock/dl ..
GITHUB 0 • TNo..........., · -, 0t'Y1»•- I!> ExploN Glat Blog tt.ip

You can use GitHub to create a persona l project,


g mboslock / d3
w he ther you want to experiment with a new A Jav,Scnpl visualization ~t>rary for HTML 80d SVG. hltp:fld3JS,Ol'g

programming language or host you r life's work.


Any kind of file can be uploaded to GitHub but it's
.. .....
El v- -lt< • CS3 / 8 nP\,11...- •
designed particularly fo r code files an d is hugely
popular. It provides access control an d severa l •---11.,...,.
.... Acld__,IOugllly)s..~1119!>. , ..... .,.
collaboration features such as bug tracking, feature
requests, task managemen t and w iki s for every
possible project. GitHub reports having more
than 14 million users an d more t han 35 milli on
Add06_Sllnl0""""""9 _______ _....,
l>tt!Os:/1tt~.,-, ~

repositories, making it the largest host of source


code in the world .
·- ·

BDM's Definitive Guide Series I 3rd Edition


( Coding Tools and Resources

HEROKU
o - EID ;;
If you are developing a web app, you will need to host it before
people can access it. GitHub can hostyourcode bu t that doesn't
mean that end-users w ill be able to use t he working app. This
is where a service like Heroku comes into its own. Heroku is a
cloud platform that lets you build, deliver, monitor and scale
apps, the fastest way to go from idea to URL, bypassing all those
infrastructure headaches. It makes the processes of deploying, lli:ll:Cll
configuring, scaling, tuning, and managing apps as simple and
, _ _ .. " _ _ _ _ _ _ ., _ _ Do,,loro _ _ . , .. _ _ _ _ 4

straightforward as possible, so that you can focus on what's most


important: building great apps that delight and engage customers.

INTEGRATED DEVELOPMENT
ENVIRONMENT
Integrated Development Environments, unlike text
editors, offer a complete coding environment. This
makes it easier for some programming beginners to get
to grips with a new language. Integrated Development
Environments, also known as Code Editors, are software
applications that provides comprehensive facilities to
computer programmers for softwa re development.
An IDE normally consists of a so urce code editor, build
automation tools and a debugger. Most modern IDEs
have intelligent code completion.

One of our favourite IDE's is Aptana Studio 3. Aptana


allows you to develop and test your entire we b
application using a single environment. There's
support for the latest browser technology specs
such as HTMLS, CSS3, JavaScript, Ruby, Rails,
PHP and Python.

STACK OVERFLOW SNIPPETS


l stackoverflow lll!!IIE:ilcmlm=II m=m
Stack Overflow
is a question
Snippet is a programming term for a small region of reusab le source
code, machine code or text. Snippets are often use d to clarify the
.-
Add • nurnbef lo N>Othtr number In Jo, 5,;ript

.-
0 ,_.,.,_M_, _ _ _ __

*...... ____ . __...___


and answer site
for professional
meaning of an otherwise "cluttered" function or to minimise the
use of repeated code that is common to other functions. Snippets
and amateur is a powerful application for Mac and Windows that stores the most
22
programmers. valuable pieces of code that you can reuse in different projects
;:;;. ·--·-·-·----- It's built and many times. The main idea is to make the process of reusing as easy
• ,__,.__________ --·--·-- run by use rs as as possible to avoid wasting your va luable time on writing the same
• ■ ;;---=:,-- ~f~==:
part of the Stack code again. You can download the Snippets manager free from
::'::.~~-
Exchange network http://snippets.me/.
:.:-.:.-=.-::.=· of Q&A sites. With
~ :::t~. its users help,
the site is building a library of detailed answers to every question
about programming. This site is all about getting answers; it's not a
discussion forum so there's no chit-chat. Good answers are vo ted up
and rise to the top and the best answers show up first so that they
are always easy to find.

The key to getting the most from Stack Overflow is to focus on


questions concerning actual problems you have faced. Include
details about what you have tried and exactly what you're trying to Code Snippet... What is Snippets? Why Snippets?

do. Tag s make it easy to find interesting questions. All questions are s.,1~1S•p,og,•mrnnigt,.,.,ro,,
.m.1,,g1onotrtuwbl<IM>U1c,coda,
m,-;hl,,.<00.orttxt.Snlpptts~
~:=:,:~•:.. ~lo,
monv•lu•bl<t pi.(n of<od•)'Oll"n
S<imtttmn.wsp<tr>d111r,~
'°""'thlngUHful wllhlnlhe~
proJt(tlto,lvoiClrC'Wflllng1t.g,1nor
tagged with their subject areas. Each can have up to Stags, since a llhnus.-d1oc1M1!yrt,eme,a.....,olAn ,euwlndfle~~mMl)'~m6- using'IOIN!pl.-cesafcode.,,...eofrtn.

question might be related to several subjects.

www.bdmpublications.com
Coding and Programming

Bei g a Programmer
( Being a Programmer

MORE THAN CODE


For those of you old enough to remember the ·sos, the golden era of home
computing, the world of computing was a very different scene to how it is
today. S-bit computers that you could purchase as a whole, as opposed to
being in kit form and you having to solder the parts together, were the stuff
of dreams; and getting your hands on one was sheer bliss contained within
a large plastic box. However, it wasn't so much the new technology that
computers then offered, moreover it was the fact that for the first time
ever, you could control what was being viewed on the 'television'.

Instead of simply playing one of the thousands of games available at the


Times have changed since programming in the ·sos, time, many users decided they wanted to create their own content, their
but the core values still remain. own games; or simply something that could help them with their homework
or home finances. The simplicity of the S-bit home computer meant that
#include<stdio. h>
#include<dos . h>
creating something from a few lines of BASIC code was achievable and so
#include<stdlib. h> the first generation of home-bred programmer was born.
4 #include<conio.h >
void ietup ()
6 {
textcolor ( BLACK) ;
text bac k.ground ( lS );
From that point on, programming expanded exponentially. It wasn't long
9
.1.d
clrscr();
window( l0, 2, 70,3);
before the bedroom coder was a thing of the past and huge teams of
cprintf( "Press X to Exit, Press Space to Jump" ); designers, coders, artists and musicians were involved in making a single
.1.2 window (62, 2,80,3 );
.d
14
cprintf( "SCORE : " ) ;
wi ndow(l , 25,80, 25 );
game. This of course led to the programmer becoming more than simply
,._5 for (int X"0 ;x< 79; x - ) someone who could fashion a sprite on the screen and make it move at the
.1.6 c printf ( "n" );
.1.7 textcolor(8); press of a key .
.b }

2P int t,speed•40;
void ds( int jump .. 0) Naturally, time has moved on and with it the technology that we use.
"
2j { static int a=l; However, the fundamentals of programming remain the same; but what
'
25 if (j umpu0 ) exactly does it take to be a programmer?
26 tz0j
27 e l s e if (jumpu 2)
28 t- - ;
29 else t"+-+; The single most common trait of any programmer, regardless of what
,."'
32
wi ndow(2 , 15-t, 18, 25);
cprintf( "
cprintf ( "
");
M/1n11J111J1M" );
they're doing, is the ability to see a logical pattern. By this we mean
,.
33 cprintf( " nn1U11111nn" ) ; someone who can logically follow something from start to finish and
cprintf( " I1JV1.nnnnn" );

,.
35

l7
cpri ntf ( " 11 MJ111nnnn " );
cprintf( " 1111"' M/IMJVIJ'JMMM " ) ;
cpri ntf ( " n11.llJIJ111111111111111 n ");
envisage the intended outcome. While you may not feel you're such a
person, it is possible to train your brain into this way of thinking. Yes, it
38 cpr intf ( " nnn1u111nnn " );
39 if ( jump.,,. 1 11 jump.,,.2 ){ takes time but once you start to think in this particular way you will be able
40 c printf ( " ") ;
41 cprintf( " 11M J\M "); to construct and follow code.
42 } else: if ( a==l )
43 {
44 cprintf( " ");
45 cprintf( " " ); Second to logic is an understanding of mathematics. You don't have to be
46 a .. 2;
47 } at a genius level but you do need to understand the rudiments of maths.
48 el s e if ( a=.,2 )
49 { Maths is all about being able to solve a problem and code mostly falls under
50 cprintf( " n11M rui " );
51 cprintf( " "); the umbrella of mathematics.
52 azl;
53 }
54 c printf ( " " );
55 delay( speed ); Being able to see the big picture is certainly beneficial for the modern
5 }
57 void obj() programmer. Undoubtedly, as a programmer, you will be part of a team
{
stati c i nt X"'B , scr•B; of other programmers, and more than likely part of an even bigger team
if (x--56 && t <4 )
{ of designers, all of whom are creating a final product. While you may only
scr•0:
be expected to create a small element of that final product, being able to
Being able to follow a logical pattern and see an end
understand what everyone else is doing will help you create something
result is one of the most valued skills of a programmer.
that's ultimately better than simply being locked in your own coding cubicle.

Finally, there's also a level of creativity needed to be a good programmer.


Again though, you don't need to be a creative genius, just have the
imagination to be able to see the end product and how the user will interact
with it.

There is of course a lot more involved in being a programmer, including


learning the actual code itself. However, with time, patience and the
determination to learn, anyone can become a programmer. Whether
you want to be part of a triple-A video game team or simply create an
automated routine to make your computing life easier, it's up to you how
far to take your coding adventure!

BDM's Definitive Guide Series I 3rd Edition


Say Hello to Python )

Python is one of the most popular


modern programming languages
available today. Not only is it easy
to learn and understand but also
remarkably powerful; and with just
a few lines of code you can create
something spectacular.
This section covers what you need
to get up and running with Python,
which version to install and use and
how to set everything up in Windows,
macOS and Linux. There's a lot you
can do with Python and this is just
the beginning.

18 Why Python?
20 Equipment You Will Need
22 Getting to Know Python
24 How to Set Up Python in Windows
26 How to Set Up Python on a Mac
28 How to Set Up Python in Linu x
30 Installing a Text Editor

BDM's Definitive Guide Series I 3rd Edition


Index

www.bdmpublications.com BDM's Definitive Guide Series I 3rd Edition


Say Hello to Python )

Why Python?
There are many different programming languages available For the modern
computer, and some still available For older 8 and 16-bit computers too. Some of
these languages are designed For scientific work, others For mobile platforms and
such. So why choose Python out of all the rest?

PYTHON POWER
Ever since the earliest home computers were available, enthusiasts, users and professionals have toiled away until the wee
hours, slaving over an overheating heap of circuitry to create something akin to magic.

These pioneers of programming carved their way into a new Regardless of whether you use an Android device, iOS device, PC,
frontier, forging small routines that enabled the letter 'A' to scroll Mac, Linux, Smart TV, games console, MP3 player, GPS device built-in
across the screen. It may not sound terribly exciting to a generation to a car, set-top box or a thousand other connected and 'smart'
that's use d to ultra high-definition graphics and open world, multi- appliances, behind them all is programming.
player on line gaming. However, forty-something years ago it was
blindingly brilliant. All those aforementioned digital devices need instructions to tell
them what to do, and allow them to be interacted with. These
Naturally these bedroom coders helped form the foundations for instructions form the programming core of the device and that core
every piece of digital technology we use today. Some went on to can be built using a variety of programming languages.
become chief deve lopers for top software companies, w hereas
others pushed the available hardwa re to its limits and founded the The languages in use today differ depending on the situation, the
billion pound gaming empire that continually amazes us. platform, the device's use and how the device will interact with its

@Bombs ® plugin/bmp Se t Cursor(p . y);


@ctrlUb ijlpiugin\z Ctrl : : c hi l dGot Focus();
@ ctr1Core ® plugin\png
@ RichText Cl <prj-aux>
@PdfDraw e <ide-aux> void Arrayctr l : : c hi ldLos tFocus ()
{
@Draw Cl <temp-aux>
@ core
if (cursor >= 0 )
Ref reshRow(c ursor ) ;
Ctrl :: Chi l dLostFocus();
# EditCtrl. h C AKeys .cpp "
C Editfield .cpp # Richl ext. h
# TextEdit. h C RichTextView. cpp void ArrayCtr l : : Paint(Draw& w)
e Text .cpp C Prompt .cpp LTIMING( "Paint • ) ;
C LineEdit .cpp C Help .cpp Si ze size = GetSi ze();
C DocEdit. cpp # OateTimeCtrl. h Rect r;
# ScrollBar.h C DateTimeCtrl.cpp r . bottom = 0 ;
C ScrollBar. cpp (3>, Bar
bool hasfocus = HasFocusDeep ();
int i = Ge tLine At(sb);
# HeaderCtrl .h # Bar. h int xs = - header . Ge t Scroll();
C HeaderCtrl. cpp C Bar .cpp int j s;
# ArrayCtrl. h C Menu6ar ,cpp for (js = 0 ; js < co lumn . Ge t Count () ; js++ ) {
e ArrayCtrl. cpp C ToolBar .cpp i nt cw = header.GetTabwi dt h ( js);
# DropChoice.h C To~Tip, cpp if ( ( xs + cw - vertgr i d + ( js == column . GetCount () - 1) ) >= 0 )
C DropBox. cpp # StatusBar .h break ;
e Droplist. cpp C StatusBar .cpp xs +== cw;
C DropPusher. cpp [,> TabCtrl }
C DropChoice. cpp # TabCtrl, h Co l or fc = Ble nd (SColorDi sab l ed, SCo l o rPaper) ;
# Stab:Ctrl. h C TabCtrl. cpp if ( !I s Null (i ) )
C Statk. cpp (;> TreeCtrl while (i < GetCount () ) {
# Splitter. h # Treectrl .h r. t op = Ge tLineY( i ) · sb;
C Splitter. cpp C TreeCtrl. cpp
if ( r . top > s i ze . cy) break ;
C FrameSplitter.cpp [;> olgColor r.bottom = r . top + Ge t Li necy( i ) ;
# SliderCtrl. h # DlgColor .h int x == xs;
for ( in t j = js; j < column . Ge tCount () ; j ++ ) {
C SliderCtrl. cpp C DlgColor .cpp int cw = header . Ge tTa bwidth ( j);
# Columnlist. h C ColorPopup. cpp int c m = column [ j] . margin;
C Columnlist. cpp C ColorPusher .cpp if (cm < 0 )
# ProQress. h (;> File5el cm = header . Tab ( j) . Ge tMargin () ;
C Progress. cpp # FileSel.h if (x > size . ex) break ;
#.. AKeys. h C
-
Filelist .cpp r . lef t = x;

BDM's Definitive Guide Series I 3rd Edition


Why Python?

environment or use rs. Operating syste ms, such as Windows, macOS Python was created over twenty six yea rs ago and has evolved to
and such are usually a combination of C++, C#, asse mbly and so me become an ideal beginner's language for learning how to program a
form of visual-based lang uage. Games generally use C++ w hi lst web co mputer. It's perfect for the hobbyist, enth usiast, stu dent, teac her
pages can use a plethora of avai lab le languages such as HTML, Java, and those who simply need to create t heir own uniqu e in teraction
Python and so on. between either themselves or a piece of external hardware and the
computer itself.
More general-purpose programming is used to create programs,
apps, software or whateve r else you wa nt to call them. Th ey're Python is free to download, install an d use and is ava ilable for Linux,
w id ely used across all hard wa re platforms an d suit virtually every Win dows, macOS, MS-DOS, OS/2, BeOS, IBM i-se ri es machines, and
conceivable app lication. Some operate faster than others and some even RI SC OS. It has been voted one of the top fi ve programming
are easier to learn and use than others. Python is one such general- languages in t he wo rld and is continually evolving ahead of the
purpose language. hardware an d Interne t development curve.

Python is what's known as a High-Leve l Language, in that it 'talks' So to answer the question: why Python? Simply put, it's free, easy to
to t he hard ware and operating syste m using a variety of arrays, learn, exceptionally powerful, universally accepted, effective and a
va riable s, objects, arithmetic, subroutin es, loops and countless supe rb learning and educational tool.
more in teractions. Whilst it's not as st reamlined as a Low-Level
Language, whic h ca n deal directly with memory ad dresses, call
stacks an d reg iste rs, its benefit is that it's universally accessible 40 LET P':1=15
70 FOR w=1 TO 10
and easy to learn. 71 CLS
75 LET b':l=XNT CRND*26)
60 LET bX=0
7l 1 e: Invo e.Java 90 FOR d=1 TO 20
import java. lang.reflect . * ; 100 PRXNT AT PX,P':li" U"
110 PR XNT AT bx , b':I ; "o "
class In voke { 120 XF XNKEYS="P" THEN LET P':I =P
public static void main ( String [] args ) { ':1+1
try { 130 XF XNKEYS="o" THEN LET P':I =P
class c = class . fo rName ( args [O] ) ; ':1-1 u
135 FOR n=1 TO 100: NEXT n
Method m = c .get Method ( args [l ] , new class 140 XF P':1<2 THEN LET P':1=2
[] { } ) ; 150 XF P':1>27 THEN LET P':1=27
object ret = m.invoke ( null , null ) ; 160 LET bx=bx +1
system .out .printl n( 165 PRXNT AT bx -1 , b':I;"
"Invoked static method : " + args [1] 190 NEXT d
+ " of class : " + args [O] 200 XF Cb':1 -1>=P':I THEN LET s=s+1
+ " with no args \ nResults: " + ret ) ; 210 PRXNT AT 10, 10; "Score="; s
} catch ( classNotFoundException e ) { 220 FOR v=1 TO 1000: NEXT V
II class .forName( ) can't find the class 300 NEXT w
} catch ( NosuchMethodException e2 ) { 0 OK, 0:1
II that method doesn't exist
} catch ( IllegalAccessException e3 ) {
II we don't have permission to invoke that • BASIC was once the starter language that early
method 8-bit home computer users learned.
} catch ( InvocationTargetException e4 ) {
II an exception ocurred while invoking that
method
system .out .println ( print( HANGMAN[ 0 ))
"Method threw an : " + e4. attempts • len(HANGMAN) - 1

getTargetException ( ) ) ;
} while (atte11pt s !• 0 and "-" in word_guessed):
} print( (· \nYou have {} attempts rema i ni ng") . fonaat(attempts))
joined_word • "". join (word _guessed)


print (joined_word)

try:
Java is a powerful language player _guess • str(input( "\nPlease select a lettu between A-Z" + "\n> " )),
except : # check valid input
that's used in web pages, set- print ("That is not valid input. Please try again.")
continue
top boxes, TVs and even cars. else :
if not player_guess.isalpha(): # check the input is a letter. Also checks a
print( "That is not a letter. Please try again.·)
continue
elif len(player_guess) > 1 : # check the input is only one letter
print( "That is aore than one letter. Pl ease try again.")
continue
elif player_guess in gue ssed_letters: # check it letter hasn't been guessed
print( "You have already guessed that letter. Please try again." )
continue
else :
pass

guessed_letters. append(player _guess)

for letter in range(len(chosen_word)):


if player_guess •• chosen_word[letter]:
word_guessed (letter] • player _guess # replace all letters in the chosen

if player_guess not in chosen_word:

www.bdmpublications.com
• Python is a more modern take on BASIC, it's easy to learn
and makes for an ideal beginner's programming language.

BDM's Definitive Guide Series I 3rd Edition


Say Hello to Python )

Equipment You
Will Need
You can learn Python with very little hardware or initial financial investment. You
don't need an incredibly powerful computer and any software that's required is
freely available.

WHAT WE'RE USING


Thankfully, Python is a multi-platform programming language available for Windows, macOS, Linux, Raspberry Pi and more. If
you have one of those systems, then you can easily start using Python.

0 COMPUTER
Obviously you're going to need a computer in order to learn how to program in
Python and to test your code . You can use Windows (from XP onward) on either a 32
or 64-bit processor, an Apple Mac or Linux installed PC.

0 AN IDE
An IDE (Integrated Developer Environment) is used to enter and execute Python
code. It enables you to inspect you r program code and the values within the code, as
well as offering advanced features. There are many different IDEs available, so find
the one that works for you and gives the best results.

0 PYTHON SOFTWARE
macOS and Linux already come with Python preinstalled as part of the operating
system, as does the Raspberry Pi. However, you need to ensure that you're running
the latest version of Python. Windows users need to download and install Python,
which we'll cover shortly.

0 TEXT EDITOR
Whilst a text editor is an ideal environment to enter code into, it's not an absolute
necessity. You can enter and execute code directly from the IDLE but a text editor,
such as Sublime Text or Notepad++, offers more advanced features and colour coding
when entering code .

0 INTERNET ACCESS
Python is an ever evolving environment and as such new versions often introduce

--·-·· -1 new concepts or change existing commands and code structure to make it a more

__~ --
[-~$,o,c0 .... ~~ ...... - ..........
. Ac •• ~ r, >, c • ~ _. , , '!-i l (B
.......... efficient language. Having access to the Internet will keep you up-to-date, help you
:_:-~ -..
_.. _ . .-.,., .
____.,_,_............. .. _. ,,_ _..,,
,,._.............""'"°-··- · --. .............
,......... out when you get stuck and give access to Python's immense number of modules.
........ -
I i i -......- - .. ,... ..,.._,.,._..,..,......_,,_.. .....,. '' ,_.,..,,_ ......_....,... .,

·-5=-=
<11 ... .. , , • n y l - · • , _ _ ,,,__, _. - ••H• "/AH / M ' .. -, ... '/>

0
.,,.,.. ,o1• • o<y1u-•• • -• •«u•; oo• """-' "" -•JcH/,_, _ . , _ ou •f•
..... ..,. --...... ,_. ..... ...... ,,_......., __ , ___ ,.. _,,.., __ ...,,_tt,.i,
••••·"<••-·• ~.,,..,
TIME AND PATIENCE
,, Id,., tP•i•<>•• • ,.,.,_.,,,,,_,.,. ,,.....•~• • • .,•
...... .. ,...,__ ,,.,, ___ ,, __,,.,,,»..•-••»•-· .. ---··-·· ,.
~

liil1WAI< ~a,;

~ r=;F;·=-~;::"".~·:;•.,-._ ..,. Despite what other books may lead you to believe, you won't become a programmer
· 1•·.........
•~---. '". ""'"·''
········~·•··•·"··· '"' .,..,,,,--.,.
..~, - - , ...u,_......,,._, .. .,,- 111,
-·"'"" · in 24-hours. Learning to code in Python takes time, and patience. You may become
,. " " ' -
stuck at times and other times the code will flow like water. Understand you're learning
._,:. -~--- ...:.~ . .. P' .... ' , _ ' : : ~ · : ·::: . -~' ..,
something entirely new, and you will get there.

BDM·s Definitive Guide Series I 3rd Edition


( Equipment You Will Need

THE RASPBERRY Pl
Why use a Raspberry Pi? The Raspberry Pi is a tiny computer that's very cheap to purchase but offers the user a fantastic learning
platform. Its main operating system, Raspbian, comes preinstalled with the latest Python along with many Modules and extras.

,,,,
RASPBERRY Pl ,, ,,
,,,,
,,,,
The Raspberry Pi 3 is the latest version, incorporating a more
powerful CPU, more memory, Wi-Fi and Bluetooth support.
,,
You can pick up a Pi for around £32 or as a part of kit for £50+,
depending on the kit you're interested in.

FUZE PROJECT

The FUZE is a learning environment built on the latest model


of the Raspberry Pi. You can purchase the workstations that
come with an electronics kit and even a robot arm for you
to build and program. You can find more information on the
FUZE at www.fuze.co.uk.

We have several great Raspberry Pi titles available via www.


bdmpublications.com. Our Pi books cover how to buy your
RASPBIAN first Raspberry Pi,
set it up and use
it; there are some great step-
~ · ••11·1:fPt
JP· -::1n,1A#i41L~
The Raspberry Pi's main operating system is a Debian-based
by-step project examples and
l The ~ rg •~

iPython
Linux distribution that comes with everything you need in
guides to get the most from
a simple to use package. It's streamlined for the Pi and is an
the Raspberry Pi too.
ideal platform for hardware and software projects, Python
programming and even as a desktop computer.
Manual
'.,:w

''''"::..;:-:.~ ·"i'•"--··..·"
. •-•-11J, ..... o•·• .. •""'-

www.bdmpublications.com BDM's Definitive Guide Series I 3rd Edition


Say Hello to Python )

Getting to
Know Python
Python is the greatest computer programming language ever created. It enables
you to fully harness the power of a computer, in a language that's clean and easy
to understand.

WHAT IS PROGRAMMING?
It helps to understand what a programming language is before you try to learn one, and Python is no different. Let's take a
look at how Python came about and how it relates to other languages.

1¥ii=Mil
JI C:\U•=\lucyh\ Oropbm\O_Action\ ri,c ipe.txt - S.,blime Tm (UNREGISTERED)
PROGRAMMING RECIPES File Edit Selection Find View Goto Tools Project P,eferentes Help

. ,ecipt.txl
Programs are like recipes for computers. A 1 IPut 100 grams of self-raising flour in a bowl .
A programming language recipe to bake a cake could go like this: 2 Add 100 g r ams of butter to the bowl.
is a list of instructions that 3 Add 100 millilitres of mil k .
4 Ba ke for half an hour .
a computer follows. These Put 100 grams of self-raising flour in a bowl.
instructions can be as simple Add 100 grams of butter to the bowl.
as displaying your name Add 100 millilitres of milk.
or playing a music file, or Bake for half an hour.
as complex as building a
whole virtual world. Python
li<ol<c-P)' C , ~ ~ o _ -\ ,okc.py(l.7.11)
is a programming language CODE n, [ dil.f<>ffl'IOI

cla3s Cake (object ) :


Run()pojc,,,ow..dowU.,lp

conceived in the late 1980s det ini t (::,elt) :


Just like a recipe, a program consists of instructions that you follow ;;1r . .i;;qr wd.i wn b = []
by Guido van Rossum def c oo k (::,el f, ingredient::,) :
in order. A program that describes a cake might run like this: f->l 111 "B<ik.iny <..; dk.~ . . . 11

at Centrum Wiskunde &


Informatica (CWI) in the I bowl = 0
Netherlands as a successor to I flour= 100
h o wl - II
flour = 1 00

the ABC language. I butter= 50


butt e r - t:1 0
milk = 100

I mi.lk = 100
bowl .append ( ltlo ur , butter,mil k J)

Guido van Rossum, the I bowl.append([flour,butter,milk]) I


c a ke . c ook (b owl)

father of Python. I cake.cook(bowl)

PROGRAM COMMANDS
You might not understand some of the Python commands, like bowl.append and cake.cook(bowl).
The first is a list, the second an object; we'll look at both in this book. The main thing to know is
that it's easy to read commands in Python. Once you learn what the commands do, it's easy to
figure out how a program works.

Python 3 4 2 Shej cake py - /home/p1/DOC\Jments/cake py (3 4 2)


f lle .Edit SMJ .t!tbug J2ptlons ytlndows Jjtlp fNe .Ed~ F.Qrmal Sun gptlOl'IS W(r'ldOWS jjtlp
Python 3 .4 .2 (default, Oct HI 20U . 13:3 1:11 ) class Cake ( obJ•ct ) :
[GCC 4.9.1] on hnux d@f _ mit_ ( s@lf ) :
Type "copyright" . "critd i ts" or "license() " for ■o r e i nfora~ tion . n lf.ingrediel'lts • [I
»> - - - ' - - - - - RESTART - - - - - - - df'f cook(sdf . mgr@di@nt s) :
prrnt ( "Bakrng cake .. ," )

uke•Cake()

I bow l • [I
flour • 100
butur • SO
a ilk • 100
bowl.append( ( flour . butter , , ulk])

cake.cook( bowl )

BDM's Definitive Guide Series I 3rd Edition


( Getting to Know Python

HIGH-LEVEL LANGUAGES ZEN OF PYTHON


Computer languages that are easy to read are known as "high-level". Python lets you access all the power of a computer in a language
This is because they fly high above the hardware (also referred to as that humans can understand. Behind all this is an ethos called "The
"the metal"). Languages that "fly close to the metal," like Assembly, Zen of Python." This is a collection of 20 software principles that
are known as "low-level". Low-level languages commands read a bit influences the design of the language. Principles include "Beautiful
like this: msg db ,0xa len equ $ - msg. is better than ugly" and "Simple is better than complex." Type
import this into Python and it will display all the principles .

___
·--·---· ___·--·-----•--!<•-----"-·----
High-level programming lnnguage

-_________
- . -·-· ____________
·------ .~
- -·. -·-·----··---
,..._ ..
.Elle ,;.dit Shell Q.ebug .Qptions ~ndows J:!.elp
Python 3.4.2 ( default . Oct 19 20 14 , 13:31 : 11 )

----__--_
.,,
...
__ _________________
[GCC 4.9.1) on linux

___......_________
,------·- ---
-----·-------·----,... ·-·---- -_____
--"'
_,______
Type "copyrigh t ", "credits" or "license () " for more information .
....
_
___
__ _______
~ ~ - - - - - .. - - -
.,.
___ _
, _
. ,_.,.-
..... ., .. _ . , , _ _ _ _ _ _
. ...
.. --- -■--- .... - ...... _ _ _ _ ..., _ _ _ " _

) _ _ _ _ _ c.d _ _ _ .._ _ _
.._,
,
cop_,..., _
>» 1111port this
The Zen of Python . by Tim Peters

Beautiful is better than ugly .

·-- ,, ____ Explicit is better than implicit .


Simple is better than complex .
Complex is better than complicated .
Flat 1s better than nested.
Sparse is better than dense .
Readability counts.
Special cases aren· t special enough to break the rules .
Although practicality beat~ ,,,purity .

PYTHON 3 VS PYTHON 2
In a typical computing scenario, Python is complicated somewhat by the existence of two active versions of the language:
Python 2 and Python 3.

WORLD OF PYTHON When you visit the Python PYTHON 3.X In 2008 Python 3 arrived with several new
Download page you'll notice that and enhanced features. These featu res
there are two buttons available: one for Python 3.6.2 and the other provide a more stable, effective and efficient programming
for Python 2.7.13; correct at the time of writing (remember Python is environment but sadly, most (if not all) of these new features are
frequently updated so you may see different version numbers). not compatible with Python 2 scripts, modules and tutorials. Whilst
not popular at first, Python 3 has since become the cutting edge of
Python programming.
Download the latest version for Windows
Download Python 3 6 2 Download Python 2 7 13

on enngw 1c version ouse . eresmorea ou e I erence


"credits" o r "license ( ) " ! o r more informatio n .
between Python 2 and 3.

Looking for Python wit h a different OS? Python for Windows,


Linux/UN IX, Mac OS X, Other

Want to help test development versions of Python? Pre-releases

So why two? Well, Python 2 was originally Python 3's growing popularity has meant that
PYTHON 2.X 3.XWINS
launched in 2000 and has since then it's now prudent to start learning to develop
adopted quite a large collection of modules, scripts, users, tutorials with the new features and begin to phase out the previous version.
and so on. Over the years Python 2 has fast become one of the first Many development companies, such as SpaceX and NASA use
go to programming languages for beginners and experts to code Python 3 for snippets of important code.
in, which makes it an extremely valuable resource.
Python 3 4 2 Shell - o x
file fdrt Shell Qebug Qptions ytindows tfelp
Python 3 . 4 .2 (default , Oct 19 2014, 13:31 : 11)
[GCC 4.9 . 1) on linux
Type "copyright" . "cr edits " or "license()" for more i nformation.
"credits " o r "l i c ense()" ! o r mo re info rmatio n . »> print ( "Python 3. x l.S AWESOME!" )
Python 3 . X 1S AWES<ME !
»>

www.bdmpublications.com BDM's Definitive Guide Series I 3rd Editio n

Вам также может понравиться