人造的智力課程_第1頁(yè)
人造的智力課程_第2頁(yè)
人造的智力課程_第3頁(yè)
人造的智力課程_第4頁(yè)
人造的智力課程_第5頁(yè)
已閱讀5頁(yè),還剩90頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

PYTHONCONTENTMANUAL

PAGE

10

CURRICULUM

ARTIFICIALINTELLIGENCE

CuratedwithsupportfromIntel?

Acknowledgements

Patrons:

Sh.RameshPokhriyal'Nishank',MinisterofHumanResourceDevelopment,GovernmentofIndia

Sh.DhotreSanjayShamrao,MinisterofStateforHumanResourceDevelopment,GovernmentofIndia

HumanResourceDevelopment,GovernmentofIndiaAdvisory,EditorialandCreativeInputs:

Ms.AnitaKarwal,IAS,Chairperson,CentralBoardofSecondaryEducation

Ms.ShwetaKhurana,Director,Programs,PartnershipsandPolicyGroup,IntelIndia

GuidanceandSupport:

Sh.AnuragTripathi,IRPS,Secretary,CentralBoardofSecondaryEducation

Dr.JosephEmmanuel,Director(Academics),CentralBoardofSecondaryEducation

Dr.BiswajitSaha,Director(SkillEducation&Training),CentralBoardofSecondaryEducation

EducationValueadder,CuratorandCoordinator:

Sh.RavinderPalSingh,JointSecretary,DepartmentofSkillEducation,CentralBoardofSecondaryEducation

ContentCurationTeam:

Mr.MukeshKumar,HOD–ComputerScience,DPS-RKPuram,NewDelhi

Ms.SharonE.Kumar,InnovationandEducationConsultant,IntelAI4YouthProgram

Mr.BhavikKhurana,IntelAIForYouthCoach

Ms.AmbikaSaxena,IntelAIForYouthCoach

Mr.AkshayChawla,IntelAIForYouthCoach

Mr.ShivamAgrawal,IntelAIForYouthCoach

FeedbackBy:

Ms.NeelamRoy,ITLPublicSchool,Delhi

Ms.MehreenShamim,TGT,DelhiPublicSchool–BangaloreEast,Bengaluru

Ms.SaswatiSarangi,PGTComputerScience,RCISKalyanNagar,Bengaluru

Ms.Isha,HODComputerScience,SalwanPublicSchool,Delhi

Ms.AayushiAgrawal,SalwanGirlsSchool,Delhi

ContentReviewCommittee

Ms.MadhuSingh,DPSGhaziabad,Ghaziabad

Ms.RituRanjan,IndraprasthaWorldSchool,PaschimVihar,Delhi

Ms.DivyaJyoti,SLSDAVPublicSchool,MausamVihar,Delhi

Ms.SwatiGanguly,Freelancer,Delhi

Ms.NitiDwivedi,Freelancer,Delhi

SpecialThanksTo:

Ms.InduKhetrapal,Principal,SalwanPublicSchool,Delhi

Ms.RekhaVinod,Principal,RCISKalyanNagar,Delhi

Ms.ManillaCarvalho,Principal,DelhiPublicSchool–BangaloreEast,Bengaluru

Ms.SudhaAcharya,Principal,ITLPublicSchool,Delhi

Ms.PuneetSardana,VicePrincipal,SalwanGirlsSchool,Delhi

AbouttheBook

ArtificialIntelligence(AI)isbeingwidelyrecognizedtobethepowerthatwillfuelthefutureglobaldigitaleconomy.AIinthepastfewyearshasgainedgeo-strategicimportanceandalargenumberofcountriesarestrivinghardtostayaheadwiththeirpolicyinitiativestogettheircountryready.

India'sownAIStrategyidentifiesAIasanopportunityandsolutionproviderforinclusiveeconomicgrowthandsocialdevelopment.Thereportalsoidentifiestheimportanceofskills-basededucation(asopposedtoknowledgeintensiveeducation),andthevalueofprojectrelatedworkinorderto“effectivelyharnessthepotentialofAIinasustainablemanner”andtomakeIndia'snextgeneration'AIready'.

Asabeginninginthisdirection,CBSEhasintroducedArtificialIntelligenceasanoptionalsubjectatClassIXfromtheSession2019-2020onwards.Toenhancethemultidisciplinaryapproachinteachinglearningandalsotosensitizethenewgeneration,itwasdecidedthatSchoolsmaystartAI“Inspiremodule”of12hoursatClassVIIIitself.

CBSEisalreadyofferingvariousSkillsubjectsatSecondaryandSeniorSecondaryleveltoupgradetheskillsandproficiencyoftheyounggenerationandalsotoprovidethemawarenesstoexplorevariouscareeroptions.AtSecondaryLevel,aSkillsubjectmaybeofferedasadditionalsixthsubjectalongwiththeexistingfivecompulsorysubjects.

CBSEacknowledgestheinitiativebyIntelIndiaincuratingthisPythonContentManual,theAItrainingvideoandmanagingthesubsequenttrainingsoftrainersontheArtificialIntelligenceCurriculum.

TheaimistostrivetogethertomakeourstudentsfuturereadyandhelpthemworkonincorporatingArtificialIntelligencetoimprovetheirlearningexperience.

Contents

Acknowledgements 3

AbouttheBook 6

Chapter1:AlgorithmsandFlowcharts 10

Recap 10

QuizTime! 10

Introduction 14

WhatisanAlgorithm? 15

Activity 15

ChallengeTime 16

Whatisaflowchart? 18

HowtoUseFlowchartstoRepresentAlgorithms 19

Challengetime! 20

TestYourKnowledge 20

Chapter2:IntroductiontoPython 21

Whatisaprogram? 21

WhatisPython? 21

WhyPythonforAI? 22

ApplicationsofPython 22

GettingstartedwithPython 23

DownloadingandSettingupPythonforuse 23

PythonIDLEinstallation 23

RunintheIntegratedDevelopmentEnvironment(IDE) 29

InteractiveMode 29

ScriptMode 30

PythonStatementandComments 32

PythonStatement 32

PythonComments 32

PythonKeywordsandIdentifiers 33

VariablesandDatatypes 35

PythonOperatorsI 41

ArithmeticOperators 41

PythonInputandOutput 41

PythonOutputUsingprint()function 41

Userinput 42

TypeConversion 42

ImplicitTypeConversion 42

ExplicitTypeConversion 44

PythonOperatorsII 47

Comparisonoperators 47

Logicaloperators 47

Assignmentoperators 48

Let’sPractice 48

TestYourKnowledge 49

Chapter3-IntroductiontotoolsforAI 50

Recap 50

IntroductiontoAnaconda 50

HowtoinstallAnaconda? 50

JupyterNotebook 56

Introduction 56

WhatisaNotebook? 56

InstallingJupyterNotebook 57

WorkingwithJupyterNotebook 57

NotebookInterface-Explained! 58

TestYourKnowledge 64

Chapter4-MoreAboutListsandTuples 65

IntroductiontoLists 65

Howtocreatealist? 65

Howtoaccesselementsofalist? 65

ListIndex 66

NegativeIndexing 66

AddingElementtoaList 67

Usingappend()method 67

Usinginsert()Method 68

Usingextend()method 68

RemovingElementsfromaList 68

Usingremove()method 69

Usingpop()method 69

SlicingofaList 70

ListMethods 72

Let’sPractice 72

IntroductiontoTuples 72

HowtoCreateatuple? 73

AccessingofTuples 73

DeletingaTuple 73

TestYourKnowledge 74

Chapter5-FlowofControlandConditions 75

IfStatement 75

IfStatement 77

Pythonif...elseStatement 78

Pythonif...elif...elseStatement 79

Syntaxofif...elif...else 79

PythonNestedifstatements 81

Let’sPractice 81

TheForLoop 82

SyntaxofforLoop 82

FlowchartofforLoop 82

Example:PythonforLoop 82

ThewhileStatement 83

SyntaxofwhileLoopinPython 83

FlowchartofwhileLoop 84

Example:PythonwhileLoop 84

Let’sPractice 85

TestYourKnowledge 85

Chapter6:IntroductiontoPackages 86

Recap 86

CHALLENGETIME! 86

Introduction 87

Whatisapackage? 90

PackageInstallation 91

Workingwithapackage 91

WhatisNumPy? 92

ExploringNumPy! 93

Let’sPractice! 94

TASK1 94

TASK2 94

TestYourKnowledge 94

AdditionalResources 95

Chapter1:AlgorithmsandFlowcharts

Recap

TillnowwehavegonethroughanexperientiallearningaroundArtificialIntelligenceinwhichwegottoknowaboutsomanynewconceptslikewhatisArtificialIntelligence,MachineLearning,Deeplearning,Rule-basedapproach,learningbasedapproach,neuralnetworks,etc.Now,itistimetomoveaheadinthisjourneytowardsAIReadinessandworkaroundtheconceptsweareintroducedtothroughhands-onlearningsessions.

Butbeforewestartgettingourhandsdirty,letusrecallwhathasbeendonesofar.Hereisaquizthroughwhichyoucanchallengeyourselfandseehowwelldoyourememberthings.

QuizTime!

WhichstageismissinginAIProjectCycle?

WhichoneofthefollowingisnotanSDG?

Whatwillbetheoutputforthisprogram?

LargeNeuralNetworksaretimeconsumingandcomputationallyexpensive.

WhichoneofthefollowingisnotanAIapplication?

Whatisthisflowchartfor?

GoogleDeepMindAIisbasedonreinforcementlearning.

WikipediacanbeanappropriateDataSourceforwhichdomain?

Whatisthecorrectsteptoreachfinishfromfirst?

PixelItisanexampleofmachinelearningAIapproach.

AIcanbeimplementedinwhichofthefollowingfield?

Problemstatementtemplatedoesnottalkaboutgoaloftheproject?

SnapchatisanexampleofNaturalLanguageProcessingdomain?

Whichofthefollowingiscommonlyusedforimageprocessinginpython?

Boxplotshelpinfindingout ?

TheAIdomainwhichcanbeusedtopredicttheAirQualityIndexis?

Whereisdecisiontreeused?

Whichprocessisdepictedbythesesteps?

Whichofthefollowingisusedtoplotgraphsinpython?

Howwastheoverallexperienceoftheworkshop?

Howwelldidyouscoreinthequiz? Analyzeyourthoughtshere:

WhatyouKnow?

WhatyouWanttoKnow?

WhathaveyouLearned?HowhaveyourLearned?

Introduction

Everymachine,whetherAIenabledornot,followsaparticularpathofaction.Itgoesthroughexactspecificstepswhichhavebeenprogrammedintoittoaccomplishthegiventask.Forexample,awashingmachinecanwashclothesforusandnotdoanythingelsebecauseitisdesignedexplicitlyforthistask.Itfollowsthestepsprogrammedintoitandcompletesthework.

Canyouthinkofpossiblestepstowashclothesinawashingmachine?

Everwonderedhowdopeoplecreatesuchprograms?Writeyourthoughtsbelow.

Todevelopaprogram,theveryfirststepthatcomesintothepictureistospecifythetaskwhichthemachineneedstodo.Oncethetaskorthemainobjectiveoftheprogramisfinalized,thetaskisbrokenintosmallertaskswhichaltogethercontributetowardsachievingthemaingoal.Tomakesurethattheflowoftheprocessisproper,algorithmsandflowchartsareusedwhichhelpusintodevelopingastepwiseframeworktoachievethemaingoal.

WhatisanAlgorithm?

Towritealogicalstep-by-stepmethodtosolvetheidentifiedproblemiscalledalgorithm,inotherwords,analgorithmisaprocedureforsolvingproblems.Inordertosolveamathematicalorcomputerproblem,thisisthefirststepoftheprocedure.Analgorithmincludescalculations,reasoninganddataprocessing.Algorithmscanbepresentedbynaturallanguages,pseudocodeandflowcharts,etc.

Activity

Goal:Togiveaglimpseofhowtowriteastepbystepalgorithmforanyproblem/processinabidirectionalmanner.

Tounderstandalgorithmsbetter,letustakeanexampleoftheprocessofmakinginstantnoodles.

Basicstepstomakeanyinstantnoodlesare:

Step1

Step2

Step3

Step4

ServeHot.

Stirconstantlyandcookintheopenpantillthewaterissoakedbythenoodles.

Addnoodlesandtastemakertotheboilingwater.

Takeapanandboilapprox.200mlofwater.

Canyouthinkofotherwaystomakeinstantnoodles?Writethemdown.

ChallengeTime

Beforewejumpintochallengingourselves,letusgothroughsomegroundrulesforthisactivity:

Writealgorithmsforthechallengesgiven.

Level

1

MakingTea/Coffee/Hotchocolate

Level

2

MakeChapati/Rice

Level

3

MakeSamosa/MasalaDosa

Now,exchangeyourattemptswithyourfriendandseewhatprocedurehavetheyfollowedforthesametasks.

Didyounoticeanydifference?

Yes!Writethedifferencesbelow.

No!Howaretheysosimilar?

Re-lookatyourownalgorithmsnow.Doyouwishtomakeanychangestoit?Isthereaneedtoadd/subtractstep(s)init?Takeyourtimeandmakethenecessarychangesifrequired.

Conclusion:Throughthisactivity,weunderstood:

Howtodivideataskintoseveralsub-tasksandtheadvantageofdoingso.

Therecanbemultipleapproachesintermsofthenumberofsub-tasksorthemethodsusedinsub-taskstosolveaproblemandtheonewhichisthesimplestandthemostefficientshouldbechosenaboveall.

Whatisaflowchart?

Aflowchartisthegraphicalorpictorialrepresentationofanalgorithmwiththehelpofdifferentsymbols,shapesandarrowsinordertodemonstrateaprocessoraprogram.Whilecomputersworkwithnumbersatease,humansneedvisualrepresentationstounderstandtheinformationwellandcommunicateiteffectively.Thus,flowchartsareusedtobreakaprocessintosmallerpartsandelaborateitusingvisualrepresentations.

Severalstandardgraphicsareappliedinaflowchart:

TerminalBox

(Start/End)

Input/Output

Process/

Instruction

Decision

Connector/

Arrow

Thegraphicsaboverepresentdifferentpartsofaflowchart.Theprocessinaflowchartcanbeexpressedthroughboxesandarrowswithdifferentsizesandcolors.Inaflowchart,wecaneasilyhighlightacertainelementandtherelationshipsbetweeneachpart.Letustakealookastohowcanweuseflowchartstorepresentalgorithms.

HowtoUseFlowchartstoRepresentAlgorithms

Nowthatwehavethedefinitionsofalgorithmandflowchart,howdoweuseaflowcharttorepresentanalgorithm?Letustakealookatgivenexamplesandseehowtheywork.

Example1:Print1to20:

Algorithm:

Step1:InitializeXas0,

Step2:IncrementXby1,

Step3:PrintX,

Step4:IfXislessthan20thengobacktostep2.

Flowchart:

Example2:ConvertTemperaturefromFahrenheit(℉)toCelsius(℃)

ALGORITHM

FLOWCHART

Step1:ReadtemperatureinFahrenheit

Step2:CalculatetemperaturewithformulaC=5/9*(F-32)

Step3:PrintC

Challengetime!

Letuspracticewhatwehavelearntsofar.Writealgorithmsanddrawflowchartsforthetasksgivenbelow.

TASK1:Howtocheckwhethertheinputnumberisprimeornot?TASK2:Howdoesatrafficsignalwork?

TASK3:HowtomakeanATMtransaction?

TASK4:Howtocheckifalightbulbisworkingornot?

TASK5:HowtowinaRock,Paper,ScissorsGame–Toknowmoreaboutthisgame,goto

/Play-Rock,-Paper,-Scissors

TestYourKnowledge

Q1)Whatisanalgorithm?Q2)Whatisaflowchart?

Q3)Listdownallthestandardgraphicsformakingaflowchart.

Chapter2:IntroductiontoPython

Intheprevioussection,youlearntaboutthedifferentmethodologiesforprogramming.Aprogramminglanguageisaformallanguagethatspecifiesasetofinstructionsthatcanbeusedtoproducevariouskindsofoutput.

InsimpleWords,aprogramminglanguageisavocabularyandsetofgrammaticalrulesforinstructingacomputertoperformspecifictasks.ThoughtherearemanydifferentprogramminglanguagessuchasBASIC,Pascal,C,C++,Java,Haskell,Ruby,Python,etc.wewillstudyPythoninthiscourse.

Whatisaprogram?

Acomputerprogramisacollectionofinstructionsthatperformaspecifictaskwhenexecutedbyacomputer.Itisusuallywrittenbyacomputerprograminaprogramminglanguage.

BeforegettingintounderstandingmoreaboutPython,weneedtofirstunderstandwhatisPythonandwhyweneedtousePython?

WhatisPython?

WhyPythonforAI?

Artificialintelligenceisthetrendingtechnologyofthefuture.Youcanseesomanyapplicationsaroundyou.IfyouasanindividualcanalsodevelopanAIapplication,youwillrequiretoknowaprogramminglanguage.TherearevariousprogramminglanguageslikeLisp,Prolog,C++,JavaandPython,whichcanbeusedfordevelopingapplicationsofAI.Outofthese,Pythongainsamaximumpopularitybecauseofthefollowingreasons:

ApplicationsofPython

Pythonisusedforalargenumberofapplications.Someofthemarementionedbelow:

WebandInternetDevelopment

Desktop

GUI

App

licatio

ns

BusinessApplications

ApplicationofPython

SoftwareDevelopment

Gamesand3D

Graphics

DatabaseAccess

GettingstartedwithPython

Pythonisacross-platformprogramminglanguage,meaning,itrunsonmultipleplatformslikeWindows,MacOS,LinuxandhasevenbeenportedtotheJavaand.NETvirtualmachines.

TowriteandrunPythonprogram,weneedtohavePythoninterpreterinstalledinourcomputer.

DownloadingandSettingupPythonforuse

DownloadPythonfromusinglink/downloads

SelectappropriatedownloadlinkasperOperatingSystem[Windows32Bit/64Bit,AppleiOS]

FOREXAMPLE,forWindows64BitOS

Selectthefollowinglink

PythonIDLEinstallation

CLICKON

Browse

CLICKON

Next

CLICKON

C:Drive

CLICKON

MakeNewFolder

ABC1ABC2ABC3

ABC4

NametheFolderasPython37

NametheFolderasPython37

CLICKONOK

CLICKON

Install

RunintheIntegratedDevelopmentEnvironment(IDE)

WhenweinstallPython,anIDEnamedIDLEisalsoinstalled.WecanuseittorunPythononourcomputer.

IDLE(GUIintegrated)isthestandard,mostpopularPythondevelopmentenvironment.IDLEisanacronymofIntegratedDevelopmentEnvironment.Itletsoneedit,run,browseanddebugPythonProgramsfromasingleinterface.Thisenvironmentmakesiteasytowriteprograms.

Pythonshellcanbeusedintwoways,viz.,interactivemodeandscriptmode.WhereInteractiveMode,asthenamesuggests,allowsustointeractwithOS;scriptmodeletsuscreateandeditPythonsourcefile.

InteractiveMode

Youcanseetheaboveexample,PythonIDLEShellaccounthas>>>asPythonprompt,wheresimplemathematicalexpressionsandsinglelinePythoncommandscanbewrittenandcanbeexecutedsimplybypressingenter.

Thefirstexpression3+10writtenonthefirstPythonpromptshows13asoutputinthenextline.

Thesecondexpression2+4*10writtenonthesecondPythonpromptshows42asoutputinthenextline.

Thethirdstatementprint("HelloLearner")writtenonthethirdPythonpromptshowsHelloLearnerasoutputinthenextline.

Thethirdstatementprint("Result:",40+5*100)writtenonthefourthPythonpromptshowsResult:asoutputinthenextline.

TryYourself

Findtheresultof(75+85+65)/3i.e.theaverageofthreemarks

Findtheresultof22/7*5*5i.e.theareaofcirclehavingradiusas5

Findtheresultof"RAVI"+"Kant"

Findtheresultof"###"*3

ScriptMode

Inscriptmode,wetypePythonprograminafileandthenusetheinterpretertoexecutethecontentfromthefile.Workingininteractivemodeisconvenientforbeginnersandfortestingsmallpiecesofcode,aswecantestthemimmediately.Butforcodingmorethanfewlines,weshouldalwayssaveourcodesothatwemaymodifyandreusethecode.

Note:ResultproducedbyInterpreterinboththemodes,viz.,Interactiveandscriptmodeisexactlythesame.

PythonScript/Program:PythonstatementswritteninaparticularsequencetosolveaproblemisknownasPythonScript/Program.

InshellMode,

ClickFile>>NewFile

TowriteaPythonscript/program,weneedtoopenanewfile-File>>NewFile,typeasequenceofPythonstatementsforsolvingaproblem,saveitwithameaningfulname-File

>> Save, and finally Run the program to view the output of the program.

Now,typeyourfirstPythonProgram

CodeExplanation:

Line1intheabovecodestartingwith#isacommentline,whichmeansthelineisnon-executableanditisonlyfortheprogrammer’sreference.

Line2willsimplydisplay

Hello

Line3willassignastringvalue"Sam"toavariableName

Line4willdisplayLearnerandwillallowthenextoutputtogetdisplayedinthesamelineLine5willdisplaySaminthesamelineasLearner

Line6willassignaninteger50toavariableALine7willassignaninteger300toavariableBLine8willdisplay50times300is15000

So,thecompleteoutputofthePythonCodewillbe

HelloLearnerSam

50times300is15000

PythonStatementandComments

InthissectionwewilllearnaboutPythonstatements,whyindentationisimportantandhowtousecommentsinprogramming.

PythonStatement

Instructionswritteninthesourcecodeforexecutionarecalledstatements.TherearedifferenttypesofstatementsinthePythonprogramminglanguagelikeAssignmentstatement,Conditionalstatement,Loopingstatementsetc.Thesehelptheusertogettherequiredoutput.Forexample,n=50isanassignmentstatement.

Multi-linestatement

InPython,endofastatementismarkedbyanewlinecharacter.

However,StatementsinPythoncanbeextendedtooneormorelinesusingparentheses(),braces{},squarebrackets[],semi-colon(;),continuationcharacterslash(\).Whenweneedtodolongcalculationsandcannotfitthesestatementsintooneline,wecanmakeuseofthesecharacters.

Examples:

TypeofMulti-line

Statement

Usage

UsingContinuationCharacter(/)

s=1+2+3+\

4+5+6+\

7+8+9

UsingParentheses()

n=(1*2*3+4–5)

UsingSquareBrackets[]

footballer=['MESSI',

'NEYMAR',

'SUAREZ']

Usingbraces{}

x={1+2+3+4+5+6+

7+8+9}

UsingSemicolons(;)

flag=2;ropes=3;pole=4

PythonComments

Acommentistextthatdoesn'taffecttheoutcomeofacode,itisjustapieceoftexttoletsomeoneknowwhatyouhavedoneinaprogramorwhatisbeingdoneinablockofcode.

InPython,weusethehash(#)symboltostartwritingacomment.

PythonKeywordsandIdentifiers

Inthissection,wewilllearnaboutkeywords(reservedwordsinPython)andidentifiers(namesgiventovariables,functions,etc.).

Keywords

KeywordsarethereservedwordsinPythonusedbyPythoninterpretertorecognizethestructureoftheprogram.

Thelistofallthekeywordsisgivenbelow.

Note:

Pythonisacase-sensitivelanguage.Thismeans,Variableandvariablearenotthesame.Alwaysnameidentifiersthatmakesense.

While,c=10isvalid.Writingcount=10wouldmakemoresenseanditwouldbeeasiertofigureoutwhatitdoesevenwhenyoulookatyourcodeafteralonggap.

Multiplewordscanbeseparatedusinganunderscore,forexamplethis_is_a_long_variable

VariablesandDatatypes

Variables

Avariableisanamedlocationusedtostoredatainthememory.Itishelpfultothinkofvariablesasacontainerthatholdsdatawhichcanbechangedlaterthroughoutprogramming.Forexample,

x=42

y=42

Thesedeclarationsmakesurethattheprogramreservesmemoryfortwovariableswiththenamesxandy.Thevariablenamesstandforthememorylocation.It'slikethetwoshoeboxes,whichyoucanseeinthepicture.Theseshoeboxesarelabelledwithxandyandthecorrespondingvaluesarestoredintheshoeboxes.Likethetwoshoeboxes,thememoryisemptyaswellatthebeginning.

Note:

AssignmentoperatorisusedinPythontoassignvaluestovariables.Forexample,a=5isasimpleassignmentoperatorthatassignsthevalue5ontherighttothevariableaontheleft.

ExamplesonVariables:

Task

SampleCode

Output

Assigningavaluetoavariable

Website=""print(Website)

Changingvalueofavariable

Website=""print(Website)Website=""

print(Website)

Assigningdifferentvaluestodifferentvariables

a,b,c=5,3.2,

"Hello"print(a)

print(b)

5

3.2

Hello

print(c)

Assigningsamevaluetodifferentvariable

x=y=z="Same"print(x)print(y)

print(z)

SameSameSame

Constants:

Aconstantisatypeofvariablewhosevaluecannotbechanged.Itishelpfultothinkofconstantsascontainersthatholdinformationwhichcannotbechangedlater.

Nontechnically,youcanthinkofconstantasashoeboxwithafixedsizeofshoekeptinsidewhichcannotbechangedafterthat.

AssigningValuetoaconstantinPython

InPython,constantsareusuallydeclaredandassignedonamodule.Here,themodulemeansanewfilecontainingvariables,functionsetc.whichisimportedtothemainfile.Insidethemodule,constantsarewritteninallcapitallettersandunderscoresseparatingthewords.

Example:Declaringandassigningvaluetoaconstant

Createainfo.py

NAME="Ajay"AGE=24

Createamain.py

importinfo

print(info.NAME)print(info.AGE)

Whenyouruntheprogramtheoutputwillbe,

Ajay24

Intheaboveprogram,wecreateaconstant.pymodulefile.Then,weassigntheconstantvaluetoPIandGRAVITY.Afterthat,wecreateamain.pyfileandimporttheconstantmodule.Finally,weprinttheconstantvalue.

Note:Inreality,wedon'tuseconstantsinPython.TheglobalorconstantsmoduleisusedthroughoutthePythonprograms.

RulesandNamingconventionforvariablesandconstants

Createanamethatmakessense.

Suppose,vowelmakes

moresensethanv.

UsecamelCasenotationtodeclareavariable.Itstartswithlowercaseletter.Forexample:myName

Usecapitalletterswherepossibletodeclareaconstant.Forexample:PI

Neverusespecialsymbolslike!,@,#,$,

%,etc.

Constantandvariablenamesshouldhavecombinationoflettersinlowercaseoruppercaseordigitsoranunderscore(_).

Datatypes

EveryvalueinPythonhasadatatype.SinceeverythingisanobjectinPythonprogramming,datatypesareactuallyclassesandvariablesareinstance(object)oftheseclasses.

TherearevariousdatatypesinPython.Someoftheimportanttypesarementionedbelowintheimage

PythonNumbers

NumberdatatypestoresNumericalValues.Theseareofthreedifferenttypes:

Integer&Long

Float/floatingpoint

Integer&LongInteger

RangeofanintegerinPythoncanbefrom-2147483648to2147483647,andlongintegerhasunlimitedrangesubjecttoavailablememory.

Integersarethewholenumbersconsistingof+or–signwithdecimaldigitslike100000,-99,0,17.Whilewritingalargeintegervalue,don’tusecommastoseparatedigits.Also,integersshouldnothaveleadingzeros.

FloatingPoint:

Numberswithfractionsordecimalpointarecalledfloatingpointnumbers.

Afloating-pointnumberwillconsistofsign(+,-)sequenceofdecimalsdigitsandadotsuchas0.0,-21.9,0.98333328,15.2963.Thesenumberscanalsobeusedtorepresentanumberinengineering/scientificnotation.

-2.0x105willberepresentedas-2.0e52.0X10-5willbe2.0E-5

None

Thisisspecialdatatypewithsinglevalue.Itisusedtosignifytheabsenceofvalue/falseinasituation.ItisrepresentedbyNone.

Sequence

Asequenceisanorderedcollectionofitems,indexedbypositiveintegers.Itisacombinationofmutableandnon-mutabledatatypes.Threetypesofsequencedata

typeavailableinPythonare:

Strings

Lists

Tuples

String

Stringisanorderedsequenceofletters/characters.Theyareenclosedinsinglequotes

(‘‘)ordouble(““).Thequotesarenotpartofstring.Theyonlytellthecomputerwherethestringconstantbeginsandends.Theycanhaveanycharacterorsign,includingspaceinthem.

Lists

Listisalsoasequenceofvaluesofanytype.Valuesinthelistarecalledelements/items.Theseareindexed/ordered.Listisenclosedinsquarebrackets.

Example:

dob=[19,"January",1990]

Tuples:

Tuplesareasequenceofvaluesofanytype,andareindexedbyintegers.Theyareimmutable.Tuplesareenclosedin().

Example:

t=(5,'program',2.5)

Sets

Setisanunorderedcollectionofvalues,ofanytype,withnoduplic

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論