Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
255 views

How To Start Programming in Python - 15 Steps - WikiHow

The document provides a 15-step guide to starting programming in Python. It begins by explaining how to install Python on Windows, OS X, and Linux systems. It then covers learning basic Python concepts like variables and objects. Further sections explain how to use the Python interpreter as a calculator, create a "Hello World" program, and build more advanced programs using flow control statements. The guide is intended to help new programmers get started with Python quickly and easily in a few short steps.

Uploaded by

Leo Zhang
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
255 views

How To Start Programming in Python - 15 Steps - WikiHow

The document provides a 15-step guide to starting programming in Python. It begins by explaining how to install Python on Windows, OS X, and Linux systems. It then covers learning basic Python concepts like variables and objects. Further sections explain how to use the Python interpreter as a calculator, create a "Hello World" program, and build more advanced programs using flow control statements. The guide is intended to help new programmers get started with Python quickly and easily in a few short steps.

Uploaded by

Leo Zhang
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

11/21/2014

HowtoStartProgramminginPython:15StepswikiHow

HowtoStartProgramminginPython
298,599views

SixParts:

Edited7daysago

InstallingPython(Windows)

LearningBasicConcepts

UsingthePythonInterpreterasaCalculator

CreatingYourFirstProgram

BuildingAdvancedPrograms

SamplePrograms

Doyouwanttostartlearninghowtoprogram?Gettingintocomputer
programmingcanbedaunting,andyoumaythinkthatyouneedtotake
classesinordertolearn.Whilethatmaybetrueforsomelanguages,thereare
avarietyofprogramminglanguagesthatwillonlytakeadayortwotograsp
thebasics.Pythoninoneofthoselanguages.YoucanhaveabasicPython
programupandrunninginjustafewminutes.SeeStep1belowtolearnhow.

Part1of5:InstallingPython(Windows)

DownloadPythonforWindowssystems.TheWindowsPythoninterpretercan
bedownloadedforfreefromthePythonwebsite.Makesuretodownloadthe

correctversionforyouroperatingsystem.
Youshoulddownloadthelatestversionavailable,whichwas3.4atthetimeof
thiswriting.
OSXandLinuxcomewithPythonalreadyinstalled.Youwillnotneedtoinstall
anyPythonrelatedsoftware,butyoumaywanttoinstallatexteditor.
MostLinuxdistributionsandOSXversionsstillusePython2.X.Thereareafew
minordifferencesbetween2&3,mostnotablythechangestothe"print"
statement.IfyouwanttoinstallanewerversionofPythononOSXorLinux,
youcandownloadthefilesfromthePythonwebsite.

InstallthePythoninterpreter.Mostuserscaninstalltheinterpreterwithout
changinganysettings.YoucanintegratePythonintotheCommandPromptby

enablingthelastoptioninthelistofavailablemodules.[1]

Installatexteditor.WhileyoucancreatePythonprogramsinNotepador
TextEdit,youwillfinditmucheasiertoreadandwritethecodeusingaspecialized

texteditor.ThereareavarietyoffreeeditorstochoosefromsuchasNotepad++
(Windows),TextWrangler(Mac),orJEdit(Anysystem).

Testyourinstallation.OpenCommandPrompt(Windows)ofyourTerminal
(Mac/Linux)andtype p y t h on .Pythonwillloadandtheversionnumberwillbe

displayed.YouwillbetakentothePythoninterpretercommandprompt,shownas >>>.
Type p r i nt ( " H e ll o , Wo r l d! ") andpress Enter .Youshouldsee
thetext Hello,World!displayedbeneaththePythoncommandline.

http://www.wikihow.com/StartProgramminginPython

1/8

11/21/2014

HowtoStartProgramminginPython:15StepswikiHow

Part2of5:LearningBasicConcepts

UnderstandthatPythondoesn'tneedtocompile.Pythonisaninterpreted
language,whichmeansyoucanruntheprogramassoonasyoumakechangesto

thefile.Thismakesiterating,revising,andtroubleshootingprogramsismuchquicker
thanmanyotherlanguages.
Pythonisoneoftheeasierlanguagestolearn,andyoucanhaveabasic
programupandrunninginjustafewminutes.

Messaroundintheinterpreter.Youcanusetheinterpretertotestoutcode
withouthavingtoadditityourprogramfirst.Thisisgreatforlearninghowspecific

commandswork,orwritingathrowawayprogram.

LearnhowPythonhandlesobjectsandvariables.Pythonisanobjectoriented
language,meaningeverythingintheprogramistreatedasanobject.Thismeans

thatyouwillnotneedtodeclarevariablesatthebeginningofyourprogram(youcando
itatanytime),andyoudonotneedtospecifythetypeofvariable(integer,string,etc.).

Part3of5:UsingthePythonInterpreterasaCalculator
Performingsomebasiccalculatorfunctionswillhelpgetyoufamiliarwith
Pythonsyntaxandthewaynumbersandstringsarehandled.

Starttheinterpreter.OpenyourCommandPromptorTerminal.Type py th on
atthepromptandpress Enter .ThiswillloadthePythoninterpreterandyouwill

betakentothePythoncommandprompt( >>>).
Ifyoudidn'tintegratePythonintoyourcommandprompt,youwillneedto
navigatetothePythondirectoryinordertoruntheinterpreter.

Performbasicarithmetic.YoucanusePythontoperformbasicarithmeticwith
ease.Seetheboxbelowforsomeexamplesonhowtousethecalculator

functions.Note: #designatescommentsinPythoncode,andtheyarenotpassed
throughtheinterpreter.
>>>3+7
10
>>>10010*3
70
>>>(10010*3)/2#Divisionwillalwaysreturnafloatingpoint(decimal)number
35.0
>>>(10010*3)//2#Floordivision(twoslashes)willdiscardanydecimalresults
http://www.wikihow.com/StartProgramminginPython

2/8

11/21/2014

HowtoStartProgramminginPython:15StepswikiHow

35
>>>23%4#Thiscalculatestheremainderofthedivision
3
>>>17.53*2.67/4.1
11.41587804878049

Calculatepowers.Youcanusethe * * operatortosignifypowers.Pythoncan
quicklycalculatelargenumbers.Seetheboxbelowforexamples.

>>>7**2#7squared
49
>>>5**7#5tothepowerof7
78125

Createandmanipulatevariables.YoucanassignvariablesinPythontoperform
basicalgebra.ThisisagoodintroductiontohowtoassignvariableswithinPython

programs.Variablesareassignedbyusingthe = sign.Seetheboxbelowfor
examples.
>>>a=5
>>>b=4
>>>a*b
20
>>>20*a//b
25
>>>b**2
16
>>>width=10#Variablescanbeanystring
>>>height=5
>>>width*height
50

Closetheinterpreter.Onceyouarefinishedusingtheinterpreter,youcancloseit
andreturntoyourcommandpromptbypressing ^Ctrl + Z (Windows)or

^Ctrl + D (Linux/Mac)andthenpressing Enter .Youcanalsotype qu it () and

press Enter .

Part4of5:CreatingYourFirstProgram

Openyourtexteditor.Youcanquicklycreateatestprogramthatwillgetyou
familiarwiththebasicsofcreatingandsavingprogramsandthenrunningthem

throughtheinterpreter.Thiswillalsohelpyoutestthatyourinterpreterwasinstalled
correctly.

Createa"print"statement."Print"isoneofthebasicfunctionsofPython,andis
usedtodisplayinformationintheterminalduringaprogram.Note:"print"isoneof

thebiggestchangesfromPython2toPython3.InPython2,youonlyneededtotype
http://www.wikihow.com/StartProgramminginPython

3/8

11/21/2014

HowtoStartProgramminginPython:15StepswikiHow

"print"followedbywhatyouwanteddisplayed.InPython3,"print"hasbecomea
function,soyouwillneedtotype"print()",withwhatyouwantdisplayedinsidethe
parentheses.

Addyourstatement.Oneofthemostcommonwaystotestaprogramming
languageistodisplaythetext"Hello,World!"Placethistextinsideofthe"print()"

statement,includingthequotationmarks:
print("Hello,World!")
Unlikemanyotherlanguages,youdonotneedtodesignatetheendofaline
witha ; .Youalsowillnotneedtousecurlybraces( { } )todesignate
blocks.Instead,indentingwillsignifywhatisincludedinablock.

Savethefile.ClicktheFilemenuinyourtexteditorandselectSaveAs.Inthe
dropdownmenubeneaththenamebox,choosethePythonfiletype.Ifyouare

usingNotepad(notrecommended),select"AllFiles"andthenadd".py"totheendofthe
filename.
Makesuretosavethefilesomewhereeasytoaccess,asyouwillneedto
navigatetoitinthecommandprompt.
Forthisexample,savethefileas"hello.py".

Runtheprogram.OpenyourCommandPromptorTerminalandnavigatetothe
locationwhereyousavedyourfile.Onceyouarethere,runthefilebytyping

h e ll o . p y andpressing Enter .Youshouldseethetext Hello,World!


displayedbeneaththecommandprompt.
DependingonhowyouinstalledPython,youmayneedtotype py th on
h e ll o . p y toruntheprogram.

Testoften.OneofthegreatthingsaboutPythonisthatyoucantestoutyournew
programsimmediately.Agoodpracticeistohaveyourcommandpromptopenat

thesametimethatyouhaveyoureditoropen.Whenyousaveyourchangesinyour
editor,youcanimmediatelyruntheprogramfromthecommandline,allowingyouto
quicklytestchanges.

Part5of5:BuildingAdvancedPrograms

Experimentwithabasicflowcontrolstatement.Flowcontrolstatementsallow
youtocontrolwhattheprogramdoesbasedonspecificconditions.[2]These

statementsaretheheartofPythonprogramming,andallowyoutocreateprogramsthat
dodifferentthingsdependingoninputandconditions.The wh il e statementisagood
onetostartwith.Inthisexample,youcanusethe w hi le statementtocalculatethe
http://www.wikihow.com/StartProgramminginPython

4/8

11/21/2014

HowtoStartProgramminginPython:15StepswikiHow

Fibonaccisequenceupto100:
#EachnumberintheFibonaccisequenceis
#thesumoftheprevioustwonumbers
a,b=0,1
whileb<100:
print(b,end='')
a,b=b,a+b
Thesequencewillrunaslongas(while)bislessthan(<)100.
Theoutputwillbe 1123581321345589
The e n d =' ' commandwilldisplaytheoutputonthesamelineinsteadof
puttingeachvalueonaseparateline.
Thereareacouplethingstonoteinthissimpleprogramthatarecriticalto
creatingcomplexprogramsinPython:
Makenoteoftheindentation.A : indicatesthatthefollowinglineswill
beindentedandarepartoftheblock.Intheaboveexample,the
p r in t ( b ) and a , b = b , a+ b arepartofthe w hi le block.
Properlyindentingisessentialinorderforyourprogramtowork.
Multiplevariablescanbedefinedonthesameline.Intheabove
example,aandbarebothdefinedonthefirstline.
Ifyouareenteringthisprogramdirectlyintotheinterpreter,youmust
addablanklinetotheendsothattheinterpreterknowsthatthe
programisfinished.

Buildfunctionswithinprograms.Youcandefinefunctionsthatyoucanthencall
onlaterintheprogram.Thisisespeciallyusefulifyouneedtousemultiple

functionswithintheconfinesofalargerprogram.Inthefollowingexample,youcan
createafunctiontocallaFibonaccisequencesimilartotheoneyouwroteearlier:[3]
deffib(n):
a,b=0,1
whilea<n:
print(a,end='')
a,b=b,a+b
print()

#Laterintheprogram,youcancallyourFibonacci
#functionforanyvalueyouspecify
fib(1000)
Thiswillreturn 01123581321345589144233377610987

Buildamorecomplicatedflowcontrolprogram.Flowcontrolstatementsallow
youtosetspecificconditionsthatchangehowtheprogramisrun.Thisis

especiallyimportantwhenyouaredealingwithuserinput.Thefollowingexamplewill
usethe i f , e li f (elseif),and el se tocreateasimpleprogramthatevaluates
theuser'sage.[4]
age=int(input("Enteryourage:"))

ifage<=12:
print("It'sgreattobeakid!")
elifageinrange(13,20):
print("You'reateenager!")
http://www.wikihow.com/StartProgramminginPython

5/8

11/21/2014

HowtoStartProgramminginPython:15StepswikiHow

else:
print("Timetogrowup")

#Ifanyofthesestatementsaretrue
#thecorrespondingmessagewillbedisplayed.
#Ifneitherstatementistrue,the"else"
#messageisdisplayed.
Thisprogramalsointroducesafewotherveryimportantstatementsthatwillbe
invaluableforavarietyofdifferentapplications:
i n pu t ( ) Thisinvokesuserinputfromthekeyboard.Theuserwill
seethemessagewrittenintheparentheses.Inthisexample,the
i n pu t ( ) issurroundedbyan i nt () function,whichmeansall
inputwillbetreatedasaninteger.
r a ng e ( ) Thisfunctioncanbeusedinavarietyofways.Inthis
program,itischeckingtoseeifthenumberinarangebetween13and
20.Theendoftherangeisnotcountedinthecalculation.

Learntheotherconditionalexpressions.Thepreviousexampleusedthe"less
thanorequal"(<=)symboltodetermineiftheinputtedagemetthecondition.You

canusethesameconditionalexpressionsthatyouwouldinmath,buttypingthemisa
littledifferent:
ConditionalExpressions.[5]
Meaning

Symbol PythonSymbol

Lessthan

<

<

Greaterthan

>

>

Lessthanorequal

<=

Greaterthanorequal

>=

Equals

==

Notequal

!=

Continuelearning.ThesearejustthebasicswhenitcomestoPython.Although
it'soneofthesimplestlanguagestolearn,thereisquiteabitofdepthifyouare

interestedindigging.Thebestwaytokeeplearningistokeepcreatingprograms!
Rememberthatyoucanquicklywritescratchprogramsdirectlyintheinterpreter,and
testingyourchangesisassimpleasrunningtheprogramfromthecommandlineagain.
TherearelotsofgoodbooksavailableforPythonprogramming,including,
"PythonforBeginners","PythonCookbook",and"PythonProgramming:An
IntroductiontoComputerScience".
Thereareavarietyofsourcesavailableonline,butmanyarestillgeared
towardsPython2.X.Youmayneedtomakeadjustmentstoanyexamplesthat
theyprovide.
ManylocalschoolsofferclassesonPython.OftentimesPythonistaughtin
introductoryclassesasitisoneoftheeasierlanguagestolearn.

http://www.wikihow.com/StartProgramminginPython

6/8

11/21/2014

HowtoStartProgramminginPython:15StepswikiHow

SamplePrograms

SamplePython
InterpreterStartup
Code

SamplePython
CalculatorCode

SampleEasyPython
Program

Wecouldreallyuseyourhelp!
Canyoutellusabout

Canyoutellusabout

Canyoutellusabout

Canyoutellusabout

Adobe
Photoshop?

PChacks?

accounting?

managing
employees?

YesIcan

YesIcan

YesIcan

YesIcan

Tips
Pythonisoneofthesimplercomputerlanguages,butitstilltakesa
littlededicationtolearn.Italsohelpstohavesomebasicalgebra
understanding,asPythonisverymathematicsfocused.

SourcesandCitations
1. https://developers.google.com/edu/python/setup
2. http://www.stavros.io/tutorials/python/
3. http://docs.python.org/3/tutorial/controlflow.html
4. http://learnpythonthehardway.org/book/ex30.html
5. http://anh.cs.luc.edu/python/hands
on/3.1/handsonHtml/ifstatements.html

http://www.wikihow.com/StartProgramminginPython

7/8

11/21/2014

HowtoStartProgramminginPython:15StepswikiHow

ArticleInfo
Categories:FeaturedArticles|Python
Recenteditsby:MaulanaMuldan,Sprinklesthegummywummybearywear,
HaileyGirges

Featured
Article

Inotherlanguages:
Espaol:CmocomenzaraprogramarenPython,Italiano:ComeIniziarea
ProgrammareinPython,Portugus:ComoIniciaraProgramaoem
Python,:Python,Franais:Comment
commencerprogrammerenPython,Deutsch:MitProgrammierunginPython
beginnen

Thankstoallauthorsforcreatingapagethathasbeenread298,599times.

http://www.wikihow.com/StartProgramminginPython

8/8

You might also like