Basics of Python and Numpy_583aab2b47e30ad9647bc4aaf13b884d.pdf

RudysBeats1 29 views 95 slides Aug 16, 2024
Slide 1
Slide 1 of 95
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95

About This Presentation

An introductory peresentation which teaches about Python commands and Numpy


Slide Content

Basics of Python
and
Numpy

Introduction
➢Pythonisaninterpreted,interactive,object-
oriented,andhigh-levelprogramminglanguage.
➢PythonFeatures
➢Easy-to-learn
➢Easy-to-read
➢Abroadstandardlibrary
➢Databases
➢GUIProgramming

Introduction
➢PythonComments:#
➢HelpinPython:help(topic)
➢Ifnoargumentisgiven,theinteractivehelpsystem
startsontheinterpreterconsole.Iftheargumentisa
string,thenthestringislookedupasthenameofa
module,function,class,method,keyword,or
documentationtopic,andahelppageisprintedonthe
console.

Printing in Python
➢Syntax:print(value,...,sep='',end='\n',file=sys.stdout,flush=False)
➢print("HelloWorld")#HelloWorld
➢a=5
➢b=2
➢print(a) #5
➢print(a,b) #52
➢print(a) #5
print(b) #2
➢print(“Valueofa=“,a)
➢print(“Valueofb=“,b)

Standard Data Types
➢Pythonhasfivestandarddatatypes−
➢Numbers
➢String
➢List
➢Tuple
➢Dictionary

Standard Data Types
➢Numbers
➢int
➢AllintegersinPython3arerepresentedaslongintegers.Hence
thereisnoseparatenumbertypeaslong.
➢IntegersinPython3areofunlimitedsize.
➢float
➢complex
➢Acomplexnumberconsistsofanorderedpairofrealfloating-
pointnumbersdenotedbyx+yj,wherexandyarethereal
numbersandjistheimaginaryunit.

Standard Data Types
➢Numbers
➢Examples
int float complex
10 0.0 3.14j
100 15.20 45.j
-786 -21.9 9.322e1-36j
0o70 32.3e18 .876j
-0o470 -90. -.6545+0J
-0x260 -32.54e100 3e1+26J
0x69 70.2E-12 4.53e1-7j

Standard Data Types
➢Strings
➢StringsinPythonareidentifiedasacontiguoussetof
charactersrepresentedinthequotationmarks.
➢Pythonallowsforeitherpairsofsingleordoublequotes.
➢Subsetsofstringscanbetakenusingthesliceoperator
([]and[:])withindexesstartingat0inthebeginningof
thestring.
➢Theplus(+)signisthestringconcatenationoperatorand
theasterisk(*)istherepetitionoperator.
➢Tryingtoaccesselementsbeyondthelengthofthe
stringresultsinanerror.

Standard Data Types
➢Strings
➢str='HelloWorld!'
➢print(str) #Printscompletestring
➢print(str[0]) #Printsfirstcharacterofthestring
➢print(str[2:5]) #Printscharactersstartingfrom3rdto5th
➢print(str[2:]) #Printsstringstartingfrom3rdcharacter
➢print(str*2) #Printsstringtwotimes
➢print(str+"TEST")#Printsconcatenatedstring
➢Thiswillproducethefollowingresult−
➢HelloWorld!
➢H
➢llo
➢lloWorld!
➢HelloWorld!HelloWorld!
➢HelloWorld!TEST

Standard Data Types
➢Strings
➢str='HelloWorld!'
➢print(str[-1])
➢print(str[-3:-1])
➢print(str[-12:])
➢Thiswillproducethefollowingresult−
➢!
➢ld
➢HelloWorld!

Standard Data Types
➢Strings
➢Pythonstringscannotbechanged—theyareimmutable.
➢Therefore,assigningtoanindexedpositioninthestring
resultsinanerror
➢I.e.str[0]=‘J’resultsinanerror.However,str=“welcome”works.

Standard Data Types
➢List
➢Alistcontainsitemsseparatedbycommasandenclosedwithin
squarebrackets([]).
➢Tosomeextent,listsaresimilartoarraysinC.One
differencebetweenthemisthatalltheitemsbelongingtoa
listcanbeofdifferentdatatype.
➢Thevaluesstoredinalistcanbeaccessedusingtheslice
operator([]and[:])withindexesstartingat0inthe
beginningofthelistandworkingtheirwayfrom-1attheend.
➢Theplus(+)signisthelistconcatenationoperator,andthe
asterisk(*)istherepetitionoperator.
➢Unlikestrings,whichareimmutable,listsareamutabletype,
i.e.itispossibletochangetheircontent.
➢Tryingtoaccess/assignelementsbeyondthelengthofthelist
resultsinanerror.

Standard Data Types
➢List
➢list=['abcd',786,2.23,'john',70.2]
➢tinylist=[123,'john']
➢print(list) #Printscompletelist
➢print(list[0])#Printsfirstelementofthelist
➢print(list[1:3])#Printselementsstartingfrom2ndtill3rd
➢print(list[2:])#Printselementsstartingfrom3rdelement
➢print(tinylist*2)#Printslisttwotimes
➢print(list+tinylist)#Printsconcatenatedlists
➢Thisproducethefollowingresult−
➢['abcd',786,2.23,'john',70.2]
➢abcd
➢[786,2.23]
➢[2.23,'john',70.2]
➢[123,'john',123,'john']
➢['abcd',786,2.23,'john',70.2,123,'john']

Standard Data Types
➢Tuples
➢Atupleisanothersequencedatatypethatissimilartothe
list.
➢Atupleconsistsofanumberofvaluesseparatedbycommas.
➢Unlikelists,however,tuplesareenclosedwithinparentheses.
➢Themaindifferencesbetweenlistsandtuplesare:Listsare
enclosedinbrackets([])andtheirelementsandsizecanbe
changed,whiletuplesareenclosedinparentheses(())and
cannotbeupdated.
➢Tuplescanbethoughtofasread-onlylists/immutablelists.

Standard Data Types
➢Tuples
➢tuple=('abcd',786,2.23,'john',70.2)
➢tinytuple=(123,'john')
➢print(tuple) #Printscompletetuple
➢print(tuple[0]) #Printsfirstelementofthetuple
➢print(tuple[1:3]) #Printselementsstartingfrom2ndtill3rd
➢print(tuple[2:]) #Printselementsstartingfrom3rdelement
➢print(tinytuple*2)#Printstupletwotimes
➢print(tuple+tinytuple)#Printsconcatenatedtuple
➢Thisproducethefollowingresult−
➢('abcd',786,2.23,'john',70.2)
➢abcd
➢(786,2.23)
➢(2.23,'john',70.2)
➢(123,'john',123,'john')
➢('abcd',786,2.23,'john',70.2,123,'john')

Standard Data Types
➢Tuples
➢tuple=('abcd',786,2.23,'john',70.2)
➢list=['abcd',786,2.23,'john',70.2]
➢tuple[2]=1000#Invalidsyntaxwithtuple
➢list[2]=1000#Validsyntaxwithlist

Standard Data Types
➢Dictionary
➢Dictionariesconsistofkey-valuepairs.
➢AdictionarykeycanbealmostanyPythontype,butareusually
numbersorstrings.
➢Values,ontheotherhand,canbeanyarbitraryPythonobject.
➢Dictionariesareenclosedbycurlybraces({})andvaluescan
beassignedandaccessedusingsquarebraces([]).
➢Dictionarieshavenoconceptoforderamongelements.
➢Itisincorrecttosaythattheelementsare"outoforder";
theyaresimplyunordered.
➢Dictionariesaremutable.

Standard Data Types
➢Dictionary
➢dict={}
➢dict['one']="Thisisone"
➢dict[2]="Thisistwo"
➢tinydict={'name':'john','code':6734,'dept':'sales'}
➢print(dict['one'])#Printsvaluefor'one'key
➢print(dict[2]) #Printsvaluefor2key
➢print(tinydict) #Printscompletedictionary
➢print(tinydict.keys())#Printsallthekeys
➢print(tinydict.values())#Printsallthevalues
➢Thisproducethefollowingresult−
➢Thisisone
➢Thisistwo
➢{'dept':'sales','code':6734,'name':'john'}
➢['dept','code','name']
➢['sales',6734,'john']

Input Statement
➢a=input(“Entera:”)
➢a=int(input(“Entera:”));
➢a=eval(input("Enterthreevalues:"))
➢a,b,c=eval(input(“Entera,b,c:”))

Matrices
➢a=[
[1,2,3],
[4,5,6]
]
➢a[0],a[1],a[0][0],a[0][2],a[1][2]
Note: Not Recommended as the lenwill be 2.

Basic Operators
➢TypesofOperator
➢ArithmeticOperators
➢Comparison(Relational)Operators
➢AssignmentOperators
➢LogicalOperators
➢BitwiseOperators
➢MembershipOperators
➢IdentityOperators

Basic Operators
➢ArithmeticOperators
➢Assumevariableaholds10andvariablebholds21,then−
Operator Description Example
+ Addition Adds values on either side of the operator.a + b = 31
-SubtractionSubtracts right hand operand from left hand
operand.
a –b = -11
* MultiplicationMultiplies values on either side of the
operator
a * b = 210
/ Division Divides left hand operand by right hand
operand
b / a = 2.1
% Modulus Divides left hand operand by right hand
operand and returns remainder
b % a = 1
** Exponent Performs exponential (power) calculation on
operators
a**b =10 to
the power 21
// Floor Division -The division of operands
where the result is the quotient in which the
digits after the decimal point are removed.
But if one of the operands is negative, the
result is floored, i.e., rounded away from
zero (towards negative infinity):
9//2 = 4 and
9.0//2.0 = 4.0

Basic Operators
➢ComparisonOperators
➢Assumevariableaholds10andvariablebholds20,then-
Operator Description Example
== If the values of two operands are equal,
then the condition becomes true.
(a == b) is not true.
!= If values of two operands are not equal,
then condition becomes true.
(a!= b) is true.
> If the value of left operand is greater
than the value of right operand, then
condition becomes true.
(a > b) is not true.
< If the value of left operand is less than
the value of right operand, then condition
becomes true.
(a < b) is true.
>= If the value of left operand is greater
than or equal to the value of right
operand, then condition becomes true.
(a >= b) is not true.
<= If the value of left operand is less than or
equal to the value of right operand, then
condition becomes true.
(a <= b) is true.

Basic Operators
➢AssignmentOperators
➢Assumevariableaholds10andvariablebholds20,then-
Operator Description Example
= Assigns values from right side operands to
left side operand
c = a + b assigns value
of a + b into c
+= It adds right operand to the left operand and
assign the result to left operand
c += a is equivalent to
c = c + a
-= It subtracts right operand from the left
operand and assign the result to left operand
c -= a is equivalent to
c = c -a
*= It multiplies right operand with the left
operand and assign the result to left operand
c *= a is equivalent to
c = c * a
/= It divides left operand with the right operand
and assign the result to left operand
c /= a is equivalent to
c = c / a
%= It takes modulus using two operands and
assign the result to left operand
c %= a is equivalent to
c = c % a
**= Performs exponential (power) calculation on
operators and assign value to the left operand
c **= a is equivalent
to c = c ** a
//= It performs floor division on operators and
assign value to the left operand
c //= a is equivalent
to c = c // a

Basic Operators
➢BitwiseOperators
➢Assumea=60=00111100andb=13=00001101,then-
Operator Description Example
& Operator copies a bit to the result
if it exists in both operands
(a & b) (means 0000 1100)
| It copies a bit if it exists in either
operand.
(a | b) = 61 (means 0011
1101)
^ It copies the bit if it is set in one
operand but not both.
(a ^ b) = 49 (means 0011
0001)
~ It is unary and has the effect of
'flipping' bits.
(~a ) = -61 (means 1100
0011 in 2's complement
form due to a signed
binary number.
<< The left operands value is moved
left by the number of bits
specified by the right operand.
a << = 2 (means 1111
0000)
>> The left operands value is moved
right by the number of bits
specified by the right operand.
a >> = 2 (means 0000
1111)

Basic Operators
➢LogicalOperators
➢Assumea=True(CaseSensitive)andb=False(Case
Sensitive),then-
Operator Description Example
and If both the operands are true
then condition becomes true.
(a and b) is False.
or If any of the two operands
are non-zero then condition
becomes true.
(a or b) is True.
not Used to reverse the logical
state of its operand.
Not(a and b) is True.

Basic Operators
➢MembershipOperators
➢Python’smembershipoperatorstestformembershipina
sequence,suchasstrings,lists,ortuples.
➢Therearetwomembershipoperatorsasexplainedbelow
Operator Description Example
in Evaluates to true if it finds a
variable in the specified
sequence and false otherwise.
x in y, here “in” results in a
1 if x is a member of
sequence y.
not inEvaluates to true if it does not
finds a variable in the specified
sequence and false otherwise.
x not in y, here “not in”
results in a 1 if x is not a
member of sequence y.

Basic Operators
➢IdentityOperators
➢Identityoperatorscomparethememorylocationsoftwo
objects.
➢TherearetwoIdentityoperatorsexplainedbelow:
Operator Description Example
is Evaluates to true if the
variables on either side of the
operator point to the same
object and false otherwise.
x is y, here”is”results in 1
if id(x) equals id(y).
is not Evaluates to false if the
variables on either side of the
operator point to the same
object and true otherwise.
x is not y, here”is
not”results in 1 if id(x) is
not equal to id(y).

Basic Operators
➢PythonOperatorPrecedence

Operator Description
** Exponentiation (raise to the power)
~ + - Complement, unary plus and minus
* / % // Multiply, divide, modulo and floor division
+ - Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^ | Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *=
**=
Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators

Decision Making
➢Simpleif
➢ifexpression:
statement(s)
var1=100
ifvar1:
print("1-Gotatrueexpressionvalue")
print(var1)
var2=0
ifvar2:
print("2-Gotatrueexpressionvalue")
print(var2)
print("Goodbye!")
Output:
1-Gotatrueexpressionvalue
100
Goodbye!

Decision Making
➢ifelse
➢ifexpression:
statement(s)
else:
statement(s)
amount=int(input(“Enteramount:“))
ifamount<1000:
discount=amount*0.05
print("Discount",discount)
else:
discount=amount*0.10
print("Discount",discount)
print("Netpayable:",amount-discount)

Decision Making
➢ifelse
Output:
Enteramount:600
Discount30.0
Netpayable:570.0
Enteramount:1200
Discount120.0
Netpayable:1080.0

Decision Making
➢elifStatement
ifexpression1:
statement(s)
elifexpression2:
statement(s)
elifexpression3:
statement(s)
else:
statement(s)

Decision Making
➢elifStatement
amount=int(input("Enteramount:"))
ifamount<1000:
discount=amount*0.05
print("Discount",discount)
elifamount<5000:
discount=amount*0.10
print("Discount",discount)
else:
discount=amount*0.15
print("Discount",discount)
print("Netpayable:",amount-discount)

Decision Making
➢elifStatement
Enteramount:600
Discount30.0
Netpayable:570.0
Enteramount:3000
Discount300.0
Netpayable:2700.0
Enteramount:6000
Discount900.0
Netpayable:5100.0

Decision Making
➢Nestedif
ifexpression1:
statement(s)
ifexpression2:
statement(s)
elifexpression3:
statement(s)
else:
statement(s)
elifexpression4:
statement(s)
else:
statement(s)

Decision Making
➢Nestedif
num=int(input("enternumber"))
ifnum%2==0:
ifnum%3==0:
print("Divisibleby3and2")
else:
print("divisibleby2notdivisibleby3")
else:
ifnum%3==0:
print("divisibleby3notdivisibleby2")
else:
print("notDivisibleby2notdivisibleby3")

Loops
➢WhileLoop
whileexpression:
statement(s)
count=0
whilecount<9:
print('Thecountis:',count)
count=count+1
print("Goodbye!")

Loops
➢WhileLoop
Thecountis:0
Thecountis:1
Thecountis:2
Thecountis:3
Thecountis:4
Thecountis:5
Thecountis:6
Thecountis:7
Thecountis:8
Goodbye!

Loops
➢forLoop
foriterating_varinsequence:
statements(s)
forvarinlist(range(5)):
print(var)
Output:
0
1
2
3
4

Loops
➢forLoop
forletterin'Python':#traversalofastringsequence
print('CurrentLetter:',letter)
Output:
CurrentLetter:P
CurrentLetter:y
CurrentLetter:t
CurrentLetter:h
CurrentLetter:o
CurrentLetter:n

Loops
➢forLoop
fruits=['banana','apple','mango']
forfruitinfruits: #traversalofListsequence
print('Currentfruit:',fruit)
print("Goodbye!")
Output:
Currentfruit:banana
Currentfruit:apple
Currentfruit:mango
Goodbye!

Loops
➢forLoop
➢IteratingbySequenceIndex
fruits=['banana','apple','mango']
forindexinrange(len(fruits)):
print('Currentfruit:',fruits[index])
print("Goodbye!")
Output:
Currentfruit:banana
Currentfruit:apple
Currentfruit:mango
Goodbye!

Loops
➢BreakStatement
forletterin'Python':
ifletter=='h':
break
print('CurrentLetter:',letter)
Output:
CurrentLetter:P
CurrentLetter:y
CurrentLetter:t

Loops
➢ContinueStatement
forletterin'Python':
ifletter=='h':
continue
print('CurrentLetter:',letter)
Output:
CurrentLetter:P
CurrentLetter:y
CurrentLetter:t
CurrentLetter:o
CurrentLetter:n

Loops
➢UsingelseStatementwithLoops
•Pythonsupportstohaveanelsestatementassociatedwith
aloopstatement
•Iftheelsestatementisusedwithaforloop,theelse
blockisexecutedonlyifforloopsterminatesnormally
(andnotbyencounteringbreakstatement).
•Iftheelsestatementisusedwithawhileloop,theelse
statementisexecutedwhentheconditionbecomesfalse.

Loops
➢UsingelseStatementwithLoops
numbers=[11,33,55,39,55,75,37,21,23,41,13]
fornuminnumbers:
ifnum%2==0:
print('thelistcontainsanevennumber')
break
else:
print('thelistdoesnotcontainevennumber')
Output:
thelistdoesnotcontainevennumber

Numbers -Revisited
➢Numbers
➢NumberTypeConversion
➢Typeint(x)toconvertxtoaplaininteger.
➢Typefloat(x)toconvertxtoafloating-pointnumber.
➢Typecomplex(x)toconvertxtoacomplexnumberwithrealpart
xandimaginarypartzero.
➢Typecomplex(x,y)toconvertxandytoacomplexnumberwith
realpartxandimaginaryparty.xandyarenumericexpressions.

Numbers -Revisited
➢Numbers
➢MathematicalFunctions
Function Returns ( description )
abs(x) The absolute value of x: the (positive)
distance between x and zero.
math.ceil(x)The ceiling of x: the smallest integer not
less than x
math.exp(x) The exponential of x: e
x
math.floor(x)The floor of x: the largest integer not
greater than x
math.log(x) The natural logarithm of x, for x> 0
math.log10(x) The base-10 logarithm of x for x> 0 .

Numbers -Revisited
➢Numbers
➢MathematicalFunctions
Function Returns ( description )
max(x1, x2,...)The largest of its arguments: the value
closest to positive infinity
min(x1, x2,...)The smallest of its arguments: the value
closest to negative infinity
pow(x, y) The value of x**y.
round(x [,n])xrounded to n digits from the decimal
point.
math.sqrt(x) The square root of x for x > 0

Strings -Revisited
➢Strings(Assumestrtobeastringvariable)
Sr.
No.
Methods with Description
1 str.capitalize()
Capitalizes first letter of string. Not in Place
2 str.isalnum()
Returns true if string has at least 1 character and all
characters are alphanumeric and false otherwise.
3 str.isalpha()
Returns true if string has at least 1 character and all
characters are alphabetic and false otherwise.
4 str.isdigit()
Returns true if string has at least 1 character and contains
only digits and false otherwise.
5 str.islower()
Returns true if string has at least 1 cased character and all
cased characters are in lowercase and false otherwise.
6 str.isspace()
Returns true if string contains only whitespace characters and
false otherwise.

Strings -Revisited
➢Strings
Sr.
No.
Methods with Description
7 str.isupper()
Returns true if string has at least one cased character and all
cased characters are in uppercase and false otherwise.
8 len(str)
Returns the length of the string
9 str.lower()
Converts all uppercase letters in string to lowercase. Not in
Place.
10 max(str)
Returns the max alphabetical character from the string str.
11 min(str)
Returns the min alphabetical character from the string str.
12 str.upper()
Converts lowercase letters in string to uppercase. Not in Place.

Lists -Revisited
➢DeleteListElements
list=['physics','chemistry',1997,2000]
print(list)
dellist[2]
print("Afterdeletingvalueatindex2:",list)
Output:
['physics','chemistry',1997,2000]
Afterdeletingvalueatindex2:['physics',
'chemistry',2000]

Lists -Revisited
➢BasicListOperations
Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!']Repetition
3 in [1, 2, 3] True Membership
for x in [1,2,3] : print
(x,end=' ')
1 2 3 Iteration

Lists -Revisited
➢BuiltinListFunctionsandMethods(assumelistto
benameofthevariable)
Sr. Function with Description
1 len(list)
Gives the total length of the list.
2 max(list)
Returns item from the list with max value.
3 min(list)
Returns item from the list with min value.
4 list.copy()
Returns a copy of the list

Lists -Revisited
➢ListMethods
SN Methods with Description
1 list.append(obj)
Appends object objto list. Returns None.
2 list.count(obj)
Returns count of how many times objoccurs in list
3 list.index(obj)
Returns the lowest index in list that objappears
4 list.insert(index, obj)
Inserts object objinto list at offset index
5 list.pop()
Removes and returns last object or objfrom list
6 list.remove(obj)
Removes first instance of objfrom list
7 list.reverse()
Reverses objects of list in place
8 list.sort()
Sorts objects of list in place

Python Functions
➢DefiningaFunction
deffunctionname(parameters):
"function_docstring"
function_suite
return[expression]
defprintme(str):
"Thisprintsapassedstringintothisfunction"
print(str)
return

Python Functions
➢Passbyreferencevsvalue
➢Allparameters(arguments)inthePythonlanguageare
passedbyreference.
➢Itmeansifyouchangewhataparameterreferstowithin
afunction,thechangealsoreflectsbackinthecalling
function.

Python Functions
➢Passbyreferencevsvalue
#Functiondefinitionishere
defchangeme(mylist):
"Thischangesapassedlistintothisfunction"
print("Valuesinsidethefunctionbeforechange:",mylist)
mylist[2]=50
print("Valuesinsidethefunctionafterchange:",mylist)
return
#Nowyoucancallchangemefunction
mylist=[10,20,30]
changeme(mylist)
print("Valuesoutsidethefunction:",mylist)
Output:
Valuesinsidethefunctionbeforechange:[10,20,30]
Valuesinsidethefunctionafterchange:[10,20,50]
Valuesoutsidethefunction:[10,20,50]

Python Functions
➢Passbyreferencevsvalue
#Functiondefinitionishere
defchangeme(mylist):
"Thischangesapassedlistintothisfunction"
mylist=[1,2,3,4] #Thiswouldassignnewreferenceinmylist
print("Valuesinsidethefunction:",mylist)
return
#Nowyoucancallchangemefunction
mylist=[10,20,30]
changeme(mylist)
print("Valuesoutsidethefunction:",mylist)
Output:
Valuesinsidethefunction:[1,2,3,4]
Valuesoutsidethefunction:[10,20,30]

Python Functions
➢Globalvs.LocalVariables
➢Variablesthataredefinedinsideafunctionbodyhavea
localscope,andthosedefinedoutsidehaveaglobal
scope.
➢Thismeansthatlocalvariablescanbeaccessedonly
insidethefunctioninwhichtheyaredeclared,whereas
globalvariablescanbeaccessedthroughouttheprogram
bodybyallfunctions.

Python Functions
➢Globalvs.LocalVariables
total=0#Thisisaglobalvariable.
#Functiondefinitionishere
defsum(arg1,arg2):
#Addboththeparametersandreturnthem."
total=arg1+arg2;#Heretotalislocalvariable.
print("Insidethefunctionlocaltotal:",total)
return
#Nowyoucancallsumfunction
sum(10,20)
print("Outsidethefunctionglobaltotal:",total)
Output:
Insidethefunctionlocaltotal:30
Outsidethefunctionglobaltotal:0

Python Functions
➢Globalvs.LocalVariables
total=0#Thisisglobalvariable.
#Functiondefinitionishere
defsum(arg1,arg2):
#Addboththeparametersandreturnthem."
globaltotal
total=arg1+arg2;
print("Insidethefunctionlocaltotal:",total)
return
#Nowyoucancallsumfunction
sum(10,20)
print("Outsidethefunctionglobaltotal:",total)
Output:
Insidethefunctionlocaltotal:30
Outsidethefunctionglobaltotal:30
Note:Youcanalsoreturnmultiplevalues,e.g.returnx,y

Miscellaneous
➢delvar_name
➢delvar1,var2
➢type(5)
➢type(5.6)
➢type(5+2j)
➢type(“hello”)
➢type([‘h’,’e’])
➢type((‘h’,’e’))
➢MultipleAssignments
➢a=b=c=1
➢a,b,c=1,2,"john"

Numpy
➢Numpy(Numeric/NumericalPython)
➢Numpyisanopen-sourceadd-onmodulethatprovides
commonmathematicalandnumericalroutinesaspre-
compiledfastfunctions
➢Itprovidesbasicroutinesformanipulatinglargearrays
andmatricesofnumericdata.
➢importnumpyasnp
➢C:\\Python34\scripts>pip3.4list
➢C:\\Python34\scripts>pip3.4installnumpy

Numpy
➢np.array
➢Collectionofsametypeofelements
➢Onedimensionalarray

Numpy
➢np.array
➢Twodimensionalarray

Numpy
➢np.array
➢Twodimensionalarray:reshape()&copy()
Strange -Shape is a settable property and it is a tuple and you can concatenate the dimension.

Numpy
➢np.array
➢Twodimensionalarray:reshape(),transpose()&flatten()

Numpy
➢np.array
➢Twodimensionalarray:concatenate()

Numpy
➢np.array
➢Twodimensionalarray:concatenate()

Numpy
➢np.array
➢Otherwaystocreatearray

Numpy
➢np.array
➢Arraymathematics

Numpy
➢np.array
➢Arraymathematics

Numpy
➢np.array
➢Arraymathematics-Broadcasting

Numpy
➢np.array
➢Arraymathematics-Broadcasting

Numpy
➢np.array
➢Arraymathematics

Numpy
➢np.array
➢Arraymathematics

Numpy
➢np.array
➢Arrayiteration

Numpy
➢np.array
➢Basicarrayoperations
➢np.mean(a)
➢np.var(a)
➢np.std(a)
➢np.min(a)
➢np.max(a)
➢np.argmin(a)
➢np.argmax(a)
➢np.sort(a)(notinplace)

Numpy
➢np.array
➢Basicarrayoperations
➢a=np.array([[1,2],[3,4]]) [
[1,2],
[3,4]
]
➢np.mean(a) #2.5
➢np.mean(a,axis=0)#array([2.,3.])#columnwise
➢np.mean(a,axis=1)#array([1.5,3.5])#rowwise
➢b=np.array([[11,5,14],[2,5,1]])[
[11,5,14],
[2,5,1]
]
➢np.sort(b) #array([[5,11,14],
[1,2,5]])
➢np.sort(b,axis=1) #array([[5,11,14],
[1,2,5]])
➢np.sort(b,axis=0) #array([[2,5,1],
[11,5,14]])

Numpy
➢np.array
➢Basicarrayoperations

Numpy
➢np.array
➢ComparisonOperators&ValueTesting

Numpy
➢np.array
➢ComparisonOperators&ValueTesting

Numpy
➢np.array
➢WhereFunction

Numpy
➢np.array
➢CheckingforNaNandInf

Numpy
➢np.array
➢ArrayItemSelection&Manipulation

Numpy
➢np.array
➢VectorandMatrixMathematics

Numpy
➢np.array
➢VectorandMatrixMathematics

Numpy
➢np.array
➢Statistics

Numpy
➢np.array
➢RandomNumbers

Numpy
➢np.array
➢RandomNumbers

Saving and Loading NumpyArray
#Singlearraysavingandloading
x=np.arange(10)
#save
np.save(‘outfile’,x)
#load
x=np.load(‘outfile.npy’)
print(x)

Saving and Loading NumpyArray
#Multiplearraysavingandloading
x=np.arange(10)
y=np.random.randint(1,10,(2,3))
#save
np.savez(‘outfile’,x,y)#ornp.savez(‘outfile’,x=x,y=y)
#load
dict=np.load(‘outfile.npz’)
x=dict[‘arr_0’] #orx=dict[‘x’]
y=dict[‘arr_1’] #ory=dict[‘y’]
print(x,y)

Disclaimer
➢Contentofthispresentationisnotoriginalandit
hasbeenpreparedfromvarioussourcesfor
teachingpurpose.
Tags