Académique Documents
Professionnel Documents
Culture Documents
SixParts:
InstallingPython(Windows)
LearningBasicConcepts
UsingthePythonInterpreterasaCalculator
CreatingYourFirstProgram
BuildingAdvancedPrograms
SamplePrograms
Doyouwanttostartlearninghowtoprogram?Gettingintocomputer
programmingcanbedaunting,andyoumaythinkthatyouneedtotake
classesinordertolearn.Whilethatmaybetrueforsomelanguages,thereare
avarietyofprogramminglanguagesthatwillonlytakeadayortwotograsp
thebasics.Python[1]inoneofthoselanguages.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.[2]
Installatexteditor.WhileyoucancreatePythonprogramsinNotepador
TextEdit,youwillfinditmucheasiertoreadandwritethecodeusingaspecialized
texteditor.ThereareavarietyoffreeeditorstochoosefromsuchasNotepad++
(Windows),TextWrangler(Mac),orJEdit(Anysystem).
Testyourinstallation.OpenCommandPrompt(Windows)ofyourTerminal
(Mac/Linux)andtype python.Pythonwillloadandtheversionnumberwillbe
displayed.YouwillbetakentothePythoninterpretercommandprompt,shownas>>>.
Type print("Hello, World!")andpress Enter .Youshouldsee
thetextHello, World!displayedbeneaththePythoncommandline.
Part2of5:LearningBasicConcepts
UnderstandthatPythondoesn'tneedtocompile.Pythonisaninterpreted
language,whichmeansyoucanruntheprogramassoonasyoumakechangesto
thefile.Thismakesiterating,revising,andtroubleshootingprogramsismuchquicker
thanmanyotherlanguages.
Pythonisoneoftheeasierlanguagestolearn,andyoucanhaveabasic
programupandrunninginjustafewminutes.
Messaroundintheinterpreter.Youcanusetheinterpretertotestoutcode
withouthavingtoaddittoyourprogramfirst.Thisisgreatforlearninghowspecific
commandswork,orwritingathrowawayprogram.
LearnhowPythonhandlesobjectsandvariables.Pythonisanobjectoriented
language,meaningeverythingintheprogramistreatedasanobject.Also,youwill
notneedtodeclarevariablesatthebeginningofyourprogram(youcandoitatany
time),andyoudonotneedtospecifythetypeofvariable(integer,string,etc.).
Part3of5:UsingthePythonInterpreterasaCalculator
Performingsomebasiccalculatorfunctionswillhelpgetyoufamiliarwith
Pythonsyntaxandthewaynumbersandstringsarehandled.
Starttheinterpreter.OpenyourCommandPromptorTerminal.Type python
atthepromptandpress Enter .ThiswillloadthePythoninterpreterandyouwill
betakentothePythoncommandprompt(>>>).
Ifyoudidn'tintegratePythonintoyourcommandprompt,youwillneedto
navigatetothePythondirectoryinordertoruntheinterpreter.
Performbasicarithmetic.YoucanusePythontoperformbasicarithmeticwith
ease.Seetheboxbelowforsomeexamplesonhowtousethecalculator
functions.Note:#designatescommentsinPythoncode,andtheyarenotpassed
throughtheinterpreter.
>>> 3 + 7
10
>>> 100 - 10*3
70
>>> (100 - 10*3) / 2 # Division will always return a floating point (decimal) number
35.0
>>> (100 - 10*3) // 2 # Floor division (two slashes) will discard any decimal results
35
>>> 23 % 4 # This calculates the remainder of the division
3
>>> 17.53 * 2.67 / 4.1
11.41587804878049
Calculatepowers.Youcanusethe **operatortosignifypowers.Pythoncan
quicklycalculatelargenumbers.Seetheboxbelowforexamples.
>>> 7 ** 2
49
>>> 5 ** 7
78125
# 7 squared
# 5 to the power of 7
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 # Variables can be any string
>>> height = 5
>>> width * height
50
Closetheinterpreter.Onceyouarefinishedusingtheinterpreter,youcancloseit
andreturntoyourcommandpromptbypressing Ctrl + Z (Windows)or Ctrl + D
Part4of5:CreatingYourFirstProgram
Openyourtexteditor.Youcanquicklycreateatestprogramthatwillgetyou
familiarwiththebasicsofcreatingandsavingprogramsandthenrunningthem
throughtheinterpreter.Thiswillalsohelpyoutestthatyourinterpreterwasinstalled
correctly.
Createa"print"statement."Print"isoneofthebasicfunctionsofPython,andis
usedtodisplayinformationintheterminalduringaprogram.Note:"print"isoneof
thebiggestchangesfromPython2toPython3.InPython2,youonlyneededtotype
"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
Testoften.OneofthegreatthingsaboutPythonisthatyoucantestoutyournew
programsimmediately.Agoodpracticeistohaveyourcommandpromptopenat
thesametimethatyouhaveyoureditoropen.Whenyousaveyourchangesinyour
editor,youcanimmediatelyruntheprogramfromthecommandline,allowingyouto
quicklytestchanges.
Part5of5:BuildingAdvancedPrograms
Experimentwithabasicflowcontrolstatement.Flowcontrolstatementsallow
youtocontrolwhattheprogramdoesbasedonspecificconditions.[3]These
statementsaretheheartofPythonprogramming,andallowyoutocreateprogramsthat
dodifferentthingsdependingoninputandconditions.The whilestatementisa
goodonetostartwith.Inthisexample,youcanusethe whilestatementtocalculate
theFibonaccisequenceupto100:
# Each number in the Fibonacci sequence is
# the sum of the previous two numbers
a, b = 0, 1
while b < 100:
print(b, end=' ')
a, b = b, a+b
Thesequencewillrunaslongas(while)bislessthan(<)100.
Theoutputwillbe1 1 2 3 5 8 13 21 34 55 89
The end=' 'commandwilldisplaytheoutputonthesamelineinsteadof
puttingeachvalueonaseparateline.
Thereareacouplethingstonoteinthissimpleprogramthatarecriticalto
creatingcomplexprogramsinPython:
Makenoteoftheindentation.A :indicatesthatthefollowinglines
willbeindentedandarepartoftheblock.Intheaboveexample,the
print(b)and a, b = b, a+barepartofthe while
block.Properlyindentingisessentialinorderforyourprogramtowork.
Multiplevariablescanbedefinedonthesameline.Intheabove
example,aandbarebothdefinedonthefirstline.
Ifyouareenteringthisprogramdirectlyintotheinterpreter,youmust
addablanklinetotheendsothattheinterpreterknowsthatthe
programisfinished.
Buildfunctionswithinprograms.Youcandefinefunctionsthatyoucanthencall
onlaterintheprogram.Thisisespeciallyusefulifyouneedtousemultiple
functionswithintheconfinesofalargerprogram.Inthefollowingexample,youcan
createafunctiontocallaFibonaccisequencesimilartotheoneyouwroteearlier:[4]
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
# Later in the program, you can call your Fibonacci
# function for any value you specify
fib(1000)
Thiswillreturn0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
987
Buildamorecomplicatedflowcontrolprogram.Flowcontrolstatementsallow
youtosetspecificconditionsthatchangehowtheprogramisrun.Thisis
especiallyimportantwhenyouaredealingwithuserinput.Thefollowingexamplewill
usethe if, elif(elseif),and elsetocreateasimpleprogramthatevaluates
theuser'sage.[5]
age = int(input("Enter your age: "))
if age <= 12:
print("It's great to be a kid!")
elif age in range(13, 20):
print("You're a teenager!")
else:
print("Time to grow up")
# If any of these statements are true
# the corresponding message will be displayed.
# If neither statement is true, the "else"
# message is displayed.
Thisprogramalsointroducesafewotherveryimportantstatementsthatwillbe
invaluableforavarietyofdifferentapplications:
input()Thisinvokesuserinputfromthekeyboard.Theuserwill
seethemessagewrittenintheparentheses.Inthisexample,the
input()issurroundedbyan int()function,whichmeansall
inputwillbetreatedasaninteger.
range()Thisfunctioncanbeusedinavarietyofways.Inthis
program,itischeckingtoseeifthenumberinarangebetween13and
20.Theendoftherangeisnotcountedinthecalculation.
Learntheotherconditionalexpressions.Thepreviousexampleusedthe"less
thanorequal"(<=)symboltodetermineiftheinputagemetthecondition.Youcan
usethesameconditionalexpressionsthatyouwouldinmath,buttypingthemisalittle
different:
ConditionalExpressions.[6]
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.
SamplePrograms
SamplePython
InterpreterStartup
Code
SamplePython
CalculatorCode
SampleEasyPython
Program
Giveus3minutesofknowledge!
Canyoutellusabout
Canyoutellusabout
Canyoutellusabout
Canyoutellusabout
Coordinate
geometry?
Removing
paint?
Puttydough
andslime?
Fitbit?
Yes
No
Yes
No
Yes
No
Yes
No
Tips
Pythonisoneofthesimplercomputerlanguages,butitstilltakesa
littlededicationtolearn.Italsohelpstohavesomebasicalgebra
understanding,asPythonisverymathematicsfocused.
SourcesandCitations
1. http://python.org
2. https://developers.google.com/edu/python/setup
3. http://www.stavros.io/tutorials/python/
4. http://docs.python.org/3/tutorial/controlflow.html
5. http://learnpythonthehardway.org/book/ex30.html
6. http://anh.cs.luc.edu/python/hands
on/3.1/handsonHtml/ifstatements.html
ArticleInfo
Categories:FeaturedArticles|Python
Inotherlanguages:
Featured
Article
Espaol:comenzaraprogramarenPython,Italiano:IniziareaProgrammarein
Python,Portugus:ComearaProgramaremPython,:
Python,Franais:commencerprogrammeren
Python,Deutsch:MitProgrammierunginPythonbeginnen,Bahasa
Indonesia:MemulaiPemrogramanPython,Nederlands:Lerenprogrammerenin
Python
Thankstoallauthorsforcreatingapagethathasbeenread435,454times.