Final Report
Final Report
ON
PYTHON
AT
SOLITAIRE INFOSYS
Mohali: C-110, Industrial Area Phase-VII, Mohali, India
Submitted in partial fulfillment of the requirements
for the award of
DIPLOMA
IN
Computer Engineering
With every project that they deliver, they deliver their respect, creativity, quality,
transparency, and teamwork to their clients. They have the experience, expertise, and
capabilities to enable organizations to accelerate their service processes in every possible
way. They are known for their excellent customer satisfaction, costeffectiveness, and
innovative skills that are unparalleled.
VISION
They visualize becoming the most trusted and respected IT service provider across the
globe with their vibrant, dynamic, and value-based IT solutions that revolve around their
clients, team, and international standards. Solitaire Infosys Pvt. Ltd. envisions becoming
a reliable partner to all its clients and focusing on doing everything ethically and rightly.
They are always open to accept their mistakes and have the nerve to do the necessary changes.
Table Of Contents
Introduction
Python 1-2
ScriptingLanguage 2-3
ObjectOrientedProgramming 3-3
Historyofpython 3-4
BehindtheSceneofPython 5-5
Downloading&InstallingPython
DownloadingPython 6-7
InstallingPython 8-10
Setuppathofvariable 10-11
PythoncodeExecution 13-13
DataTypes&Operator
DataType
14-15
Variables
15-15
String 15-16
PythonOperator 16-17
ArithmeticOperator 17-17
ComparisonOperator 17-18
Tuple&List
Tuple 18-20
AccessingTupleValues 18-18
BuiltinOperation 18-19
BuiltinToupleFunctions 19-19
List 20-23
AccessingListValues 20-21
BuiltinOperation 21-21
BuiltinFunctions 21-21
Loops&ConditionalStatements
Loops 21-26
LoopsDefinition 21-22
LoopsExample 22-23
ConditionalStatement 23-23
5.21ConditionalStatementDefinition 23-23
5.2.2ConditionalStatementExample 24-25
Function 25-25
Syntax&Examples 25-26
Uses&Scopeofpython.
WhatcanwedoWithPython? 26-26
WhoUsesPythonToday? 27-27
WhydoPeopleusepython? 27-27
Python
Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its
design philosophy emphasizes code readability, and its syntax allows programmers to express
concepts in fewer lines of code than would be possible in languages such as C++ or Java. The
language provides constructs intended to enable clear programs on both a small and large scale.
Scripting Language
Ascriptingorscriptlanguageisaprogramminglanguagethatsupportsscripts,programs
writtenforaspecialrun-timeenvironmentthatautomatetheexecutionoftasksthatcould alternatively be
executed one-by-one by a human operator.
Scripting languages are often interpreted (rather than compiled). Primitives are usually the elementary
tasks orAPI calls, and the language allows them to be combined into more
complexprograms.Environmentsthatcanbeautomatedthroughscriptingincludesoftware applications,
web pages within a web browser, the shells of operating systems (OS), embedded systems, as well as
numerous games.
History
Python was conceived in the late 1980s, and its implementation was started in December 1989 by
Guido van Rossum at CWI in the Netherland sasa successor to the ABC language (itself inspired by
SETL) capable of exception handling and interfacing with the Amoeba operating system. Van Rossum
is Python's principal author, and his continuing centra lrole in deciding the
directionofPythonisreflectedinthetitlegiventohimbythePythoncommunity, benevolent dictator for life
(BDFL).
“Python is an experiment in how much freedom programmers need.
Too much freedom and nobody can read another's code; too little and
expressiveness is endangered.”
AbouttheoriginofPython,VanRossumwrotein1996:
Over six years ago, in December 1989, I was looking for a "hobby" programming project that would
keep me occupied during the week around Christmas. My office ... would be closed, but I had a home
Computer, and not much else on my hands. I decided to write an
interpreterforthenewscriptinglanguageIhadbeenthinkingaboutlately:adescendantofABCthat would
appeal to Unix/C hackers. I chose Python as a working title for the project, being in a slightly
irreverent mood (and a big fan of Monty Python's Flying Circus).
Downloadingpython
Now that you are on the download page, select which of the software builds you would
liketodownload.Forthepurposesofthisarticlewewillusethemostuptodateversion available (Python
3.4.1).
Once you have clicked on that, you will be taken to a page with a description ofallthenew updates and
features of 3.4.1, however, you can always read that while the download is in process. Scroll to the
bottom of the page till you find the“Download”section and click on the link that says “download
page.”
Now you will scroll all the way to the bottom of the page and find the “Windows x86
MSI installer.” If you want to download the 86-64 bit MSI, feel free to do so. We believe
that even if you have a 64-bit operating system installed on your computer, the 86-bit
MSI is preferable. We say this because it will still run well and sometimes, with the 64-
bit architectures, someofthecompiledbinariesand Python libraries don’t work well.
InstallingPython
OnceyouhavedownloadedthePythonMSI,simplynavigatetothedownloadlocation on your
computer, double clicking the file and pressing Run when the dialog box pops up.
If you are the only person who uses your computer, simply leave the “Install for all users”
option selected. If you have multiple accounts on your PC anddon’twantto install it across
all accounts, select the “Install just for me” option then press “Next.”
fyouwanttochangetheinstalllocation,feelfreetodoso;however,itisbesttoleave it as is and simply
select next, Otherwise...
Scrolldowninthewindowandfindthe“AddPython.exetoPath”andclickonthesmall red “x.” Choose
the “Will be installed on local hard drive” option then press “Next.”
Now that you have completed the installation process, click on “Finish.
SetupthePathVariable
Once you have the “Environment Variables” window open, direct your focustothe bottom
half. You will notice that it controls all the “System Variables” rather than just this
associated with your user. Click on “New…” to create a new variable for Python.
Simply enter a name for your Path and the code shown below. For thepurposes of this
example we have installed Python 2.7.3, so we will call the path: “Pythonpath.” The
Now that we have successfully completed the installation process and added our
“Environment Variable,” you are ready to create your first basic Python script. Let’s begin
byopeningPython’sGUIbypressing“Start”andtyping“Python”andselecting the “IDLE (Python
GUI).”
Sourcecodeextensionis .py
Bytecodeextensionis.pyc(compiledpythoncode)
DataType
(thisis called dynamic typing). Data types determine whether an object can do something, or whether
it just would not make sense. Other programming languages often determine whether an operation
makes sense for an object by making sure the object can never be stored somewhere where the
operation will be performed on the object (this type systemis called static typing). Python does not do
that. Instead it storesthetypeofanobjectwiththe object, and checks
whentheoperationisperformedwhetherthatoperationmakessensefor that object
Pythonhasmanynativedatatypes.Herearetheimportantones:
Boolean sareeitherTrueorFalse.
Numberscanbeintegers(1and2),floats(1.1and1.2),fractions(1/2and2/3),orevencomplex numbers.
String saresequencesofUnicodecharacters,e.g.anHTMLdocument.
Bytesandbytearrays ,e.g.aJPEGimagefile.
Tuples areordered,immutablesequencesofvalues.
Variablesarenothingbutreservedmemorylocationstostorevalues.Thismeansthatwhen you
create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides whatcan
be stored in the reserved memory. Therefore, by assigning different data types to variables,
you can store integers, decimals or characters in these variables.
String
Inprogrammingterms,weusuallycalltextastring.Whenyouthinkofastringasa collection of
letters, the term makes sense.
CreatingStrings
• len("hello") 5 # size
• "hello"<"jello" 1 #
comparison
• "e" in "hello" 1 # search
PythonOperator
ArithmeticOperator
Operator
Meaning Example
// Floordivision-divisionthatresultsintowholenumber x // y
adjusted to the left in the number line
ComparisonOperator
Cha
Tuples
Atuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The
differencesbetweentuplesandlistsare,thetuplescannotbechangedunlikelistsandtuplesuse parentheses.
AccessingValuesinTuples:
To access values in tuple, use the square brackets for slicing along with the index or indices to
obtain value available at that index. For example −tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 ); print "tup1[0]: ", tup1[0] print "tup2[1:5]: ", tup2[1:5]
When the above code is executed, it produces the following result − tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
BasicTuplesOperations
Tuples respond to the + and * operators much like strings; they meanconcatenationand repetition
here too, except that the result is a new tuple, not a string. In fact, tuples respond to all of the
general sequence operations we usedonstringsinthepriorchapter
–
Pythonincludesthefollowingtuplefunctions−
S FunctionwithDescription
N
1 cmp(tuple1,tuple2)Compareselementsofbothtuples.
2 len(tuple)Givesthetotallengthofthetuple.
3 max(tuple)Returnsitemfromthetuplewithmaxvalue.
4 min(tuple)Returnsitemfromthetuplewithminvalue.
5 tuple(seq)Convertsalistintotuple.
List
The list is a most versatile datatype available in Python which can be written as a list of comma-
separated values (items) between square brackets. Important thing about a list is that items in a list
need not be of the same type.
Creating a list is as simple as putting different comma-separated values between square
brackets. Forexample−list1=['physics','chemistry',1997,2000];list2=[1, 2, 3, 4, 5 ]; list3 =
["a", "b", "c", "d"];
Similartostringindices,listindicesstartat0,andlistscanbesliced,concatenatedandsoon.
AccessingValuesinLists:
To access values in lists, use the square brackets for slicing along with the index orindicesto obtain
value available at that index. For example − list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3,
4, 5, 6, 7 ]; print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1:5]
Output:list1[0]:physics
list2[1:5]:[2,3,4,5]
Output:Valueavailableatindex2:
1997Newvalueavailableatindex2:
2001
Output:Afterdeletingvalueatindex2:
['physics', 'chemistry', 2000]
BasicListOperation
Python Expression Results Description
Loopdefinition
Programminglanguagesprovidevariouscontrolstructuresthatallowformorecomplicated execution paths.
Aloopstatementallowsustoexecuteastatementorgroupofstatementsmultipletimes.The following diagram
illustrates a loop statement −
= Equalto-Trueifbothoperandsareequal x=
= =y
!= Notequalto-Trueifoperandsarenotequal x !=
y
Pythonprogramminglanguageprovidesfollowingtypesofloopstohandleloopingrequirements.
Loop Type Description
whileloop Repeats a statement or group of statements while a given
conditionisTRUE.Itteststheconditionbeforeexecutingthe loop body.
LoopExample:
ForLoop:
>>>formynumin[1,2,3,4,5]: print
("Hello", mynum )
Hello1
Hello2
Hello3
Hello4
Hello5
WhileLoop:
>>>count=0>>while(count<4):
print'Thecountis:',countcount= count +
1
Thecountis:0
Statement Description
print(“b”)
If...ElseStatement:
a=200
b=33
if b>a:
print(“bisgreaterthana”) else:
print(“aisgreaterthan b”)
Function
Functionblocksbeginwiththekeyworddeffollowedbythefunctionnameandparentheses(()
).
Anyinputparametersorargumentsshouldbeplacedwithintheseparentheses.Youcan also define
parameters inside these parentheses.
Thefirststatementofafunctioncanbeanoptionalstatement-thedocumentationstringofthe function.
Thecodeblockwithineveryfunctionstartswithacolon(:)andisindented.
Thestatementreturn[expression]exitsafunction,optionallypassingbackanexpressiontothe caller.Areturn
statement with no arguments is the same as return None.
Syntex:
Deffunctionname(parameters):
“function_docstring”
Function_suite
Return[expression]
Example:
Defprintme(str):
“thisprintapassedstringintothis function” print
str
return
1.#Functiondefinitionisheredef
printme( str ):
"Thisprintsapassedstringintothisfunction"print str
return;
SCOPEOFPYTHON
1 -Science
- Bioinformatics
2 -SystemAdministration
- Unix
- Weblogic
- Websphere
3 -WebApplicationDevelopment
WhatCanWedoWithPython?
1 -Systemprogramming
2 - Graphical User Interface
Programming3-InternetScripting
4 -ComponentIntegration
5 -DatabaseProgramming
6 -Gaming,Images,XML,Robotandmore
WHOUSESPYTHONTODAY?
• Pythonisbeingappliedinrealrevenue-generatingproductsbyrealcompanies.
• GooglemakesextensiveuseofPythoninitswebsearchsystem,andemploysPython’s creator.
• Intel,Cisco,Hewlett-Packard,Seagate,Qualcomm,andIBMusePythonforhardwaretesting.
• ESRIusesPythonasanend-usercustomizationtoolforitspopularGISmappingproducts.
WHYDOPEOPLEUSEPYTHON?
• TheYouTubevideosharingserviceislargelywritteninPython.
o ItisFree(asinbothcostandsourcecode).
o It is trivial to install on a Windows PC allowing students to take their interest further.
For many the hurdleofinstallingaPascalorCcompileronaWindows machine is either too
expensive or too complicated;
o It is a flexible tool that allows both the teaching of traditional procedural programming
and modern OOP; It can be used to teach a large number of transferable skills;
o It is a real-world programming language that can be and is used in academia and the
commercial world;
o It appears to be quicker to learn and, in combination with its many libraries, this offers
the possibility of more rapid student development allowing the course to be made
more challenging and varied;
and most importantly, its clean syntax offersincreasedunderstandingandenjoymentfor students