Python Core Concepts with Practical Knowledge's
bsramar
78 views
35 slides
Jun 20, 2018
Slide 1 of 35
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
About This Presentation
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language ...
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.
Size: 886.77 KB
Language: en
Added: Jun 20, 2018
Slides: 35 pages
Slide Content
Python Core Concepts with Practical Knowledge's
DAY 1
Date : 20-06 –2018 Time : 08.00 PM to 09.00 PM Zoom Link : https://zoom.us/j/9491992120
Python Core Concepts with Practical Knowledge's
DAY 1
Date : 20-06 -2018& 08.00 PM to 09.00 PM
3 DAYS 1 Hour Online Training
DAY 2
Date : 21 -06 -2018& 08.00 PM to 09.00 PM
DAY 3
Date : 22 -06 -2018& 08.00 PM to 09.00 PM
Files
Python Object & Class
Functions
Data types
Introduction & Data Type
Flow Control
To Solve the 30 Challenges programs during online class
Contact For Payment Details +91 9498 4032 506
FEE : 300/-ONLY
Registration Link
https://docs.google.com/forms/d/e/1FAIpQLSeu5cxgATy9-mJldU5uqcRxeAclAPIDtiCKapvGchTmpJs9tg/viewform?usp=sf_link
Python core concepts
I.Introduction
II.Flow Control
III.Functions
IV.Files
V.Python Object & Class
I.I Python Keywords & Identifiers
Keywords are the reserved words in Python.
Falseclassfinally is return
Nonecontinuefor lambda try
True def fromnonlocalwhile
and del global not with
as elif if or yield
assertelse import pass
breakexcept in raise
There are 33 keywords in Python
Identifiers
Identifier is the name given to entities like class, functions, variables etc. in
Python. It helps differentiating one entity from another.
Rules for writing identifiers
1.Identifierscanbeacombinationoflettersinlowercase(atoz)oruppercase(AtoZ)ordigits
(0to9)oranunderscore(_).NameslikemyClass,var_1andprint_this_to_screen,allarevalid
example.
2.Anidentifiercannotstartwithadigit.1variableisinvalid,butvariable1isperfectlyfine.
3.Keywordscannotbeusedasidentifiers.
4.Wecannotusespecialsymbolslike!,@,#,$,%etc.inouridentifier.
5.Identifiercanbeofanylength.
Things to care about
Python is a case-sensitive language. This means, Variable and variable are not the same. Always
name identifiers that make sense.
I.II Statements & Comments
I.Python Statement
I.Multi-line statement
II.Python Indentation
III.Python Comments
I.Multi-line Comments
II.Docstringin Python
Python Comments
Commentsareveryimportantwhilewritingaprogram.Itdescribeswhat's
goingoninsideaprogramsothatapersonlookingatthesourcecodedoes
nothaveahardtimefiguringitout.
weusethehash(#)symboltostartwritingacomment.
#This is a comment
#print out Hello
print('Hello')
Multi-line comments
"""This is also a perfect
example of multi-line
comments"""
#This is a long comment
#and it extends
#to multiple lines
Docstringin Python
defdouble(num):
"""Function to double the value"""
return 2*num
Itisastringthatoccursasthefirststatementina
module,function,class,ormethoddefinition.Wemust
writewhatafunction/classdoesinthedocstring.
I.III Variables
I.Variable
I.Declaring
Variables
II.Assigning value
to a Variable
II.Constants
I.Assigning value
to a constant
Variable
In most of the programming languages a variable is a named location used to
store data in the memory. Each variable must have a unique name called
identifier. It is helpful to think ofvariables ascontainer that hold data which
can be changed later throughout programming.
Non technically, you can suppose variable as a bag to store books in it and
those books can be replaced at anytime.
Note: In Python we don't assign values to the variables, whereas Python
gives the reference of the object (value) to the variable.
III. Variables
I.Variable
I.Declaring
Variables
II.Assigning value to
a Variable
II.Constants
I.Assigning value to
a constant
Declaring Variables in Python
InPython,variablesdonotneeddeclarationtoreservememoryspace.The"variable
declaration"or"variableinitialization"happensautomaticallywhenweassigna
valuetoavariable.
Assigning value to a Variable in Python
You can use the assignment operator = to assign the value to a variable.
website = "Apple.com" Changing value of a variable
print(website) website = "Apple.com"
# assigning a new variable to website
website = "Programiz.com"
print(website)
III. Variables
I.Variable
I.Declaring
Variables
II.Assigning value to
a Variable
II.Constants
I.Assigning value to
a constant
Assigning multiple values to multiple variables
a, b, c = 5, 3.2, "Hello“
print (a)
print (b)
print (c)
Constants
InPython, constants are usually declared and assigned on a module. Here, the
module means a new file containing variables, functions etcwhich is imported to
main file. Inside the module, constants are written in all capital letters and
underscores separating the words
constant.py main.py
PI = 3.14 import constant
GRAVITY = 9.8 print(constant.PI)
print(constant.GRAVITY)
I.IV Data types
Numbers
Integers,floatingpointnumbersandcomplexnumbersfallsunderPython
numberscategory.Theyaredefinedasint,floatandcomplexclassin
Python.Numbers
List
Tuple
Strings
Set
Dictionary
Conversion between data types
a = 5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True
I.IV Data types
List
Listis an ordered sequence of items. It is one of the most used datatypein
Python and is very flexible. All the items in a list do not need to be of the
same type.Numbers
List
Tuple
Strings
Set
Dictionary
Conversion between data types
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])
# a[0:3] = [5, 10, 15]
print("a[0:3] = ", a[0:3])
# a[5:] = [30, 35, 40]
print("a[5:] = ", a[5:])
a[2] = 15
a[0:3] = [5, 10, 15]
a[5:] = [30, 35, 40]
I. IV Data types
Tuple
•Tupleisanorderedsequenceofitemssameaslist.Theonlydifferenceisthattuplesare
immutable.Tuplesoncecreatedcannotbemodified.
•Tuplesareusedtowrite-protectdataandareusuallyfasterthanlistasitcannotchange
dynamically.
Numbers
List
Tuple
Strings
Set
Dictionary
Conversion between data types
t = (5,'program', 1+3j)
# t[1] = 'program‘
print("t[1] = ", t[1])
# t[0:3] = (5, 'program', (1+3j))
print("t[0:3] = ", t[0:3])
# Generateserror
# Tuplesare immutable
t[0] = 10
t[1] = program
[0:3] = (5, 'program', (1+3j))
Traceback(most recent call last): File "<stdin>",
line 11, in <module> t[0] = 10TypeError: 'tuple'
object does not support item assignment
I.IV Data types
Strings
StringissequenceofUnicodecharacters.Wecanusesinglequotesordoublequotesto
representstrings.Multi-linestringscanbedenotedusingtriplequotes,'''or""".
Numbers
List
Tuple
Strings
Set
Dictionary
Conversion between data types
>>>s = "This is a string“
>>> s = '''a multiline
Set
Setisanunorderedcollectionofuniqueitems.Setisdefinedbyvaluesseparatedbycomma
insidebraces{}.Itemsinasetarenotordered.
a = {5,2,3,1,4}
# printing set variable
print("a = ", a)
# data type of variable a
print(type(a))
a = {1, 2, 3, 4, 5}
<class 'set'>
I.IV Data types
Dictionary
Dictionaryis an unordered collection of key-value pairs.
It is generally used when we have a huge amount of data. Dictionaries are optimized for
retrieving data. We must know the key to retrieve the value.
Numbers
List
Tuple
Strings
Set
Dictionary
Conversion between data types
d = {1:'value','key':2}
print(type(d))
print("d[1] = ", d[1]);
print("d['key'] = ", d['key']);
# Generates error
print("d[2] = ", d[2]);
<class 'dict'>
d[1] = valued['key'] = 2
Traceback(most recent call last):
File "<stdin>", line 9, in <module> print("d[2] = ",
d[2]);KeyError: 2
I.IV Data types
Conversion between data types
We can convert between different data types by using different type conversion functions like
int(), float(), str() etc.
Numbers
List
Tuple
Strings
Set
Dictionary
Conversion between data types
>>> set([1,2,3]) {1, 2, 3}
>>> tuple({5,6,7}) (5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
I.V Operators
Arithmetic
Arithmetic Operators
Comparison (Relational) Operators
Logical (Boolean) Operators
Bitwise Operators
Assignment Operators
Special Operators
IndentityOperator
Membership Operator
OperatorMeaning Example
+ Add two operands or unary plus
x + y
+2
- Subtract right operand from the left or unary minus
x -y
-2
* Multiply two operands x * y
/
Divide left operand by the right one (always results
into float)
x / y
%
Modulus -remainder of the division of left operand
by the right
x % y (remainder of x/y)
//
Floor division -division that results into whole
number adjusted to the left in the number line
x // y
** Exponent -left operand raised to the power of rightx**y (x to the power y)
I.V Operators
Arithmetic
Arithmetic Operators
Comparison (Relational) Operators
Logical (Boolean) Operators
Bitwise Operators
Assignment Operators
Special Operators
IndentityOperator
Membership Operator
x = 15
y = 4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x -y = 11
print('x -y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
x + y = 19
x -y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625
I.V Operators
Relational
Arithmetic Operators
Comparison (Relational) Operators
Logical (Boolean) Operators
Bitwise Operators
Assignment Operators
Special Operators
IndentityOperator
Membership Operator
Operator Meaning Example
> Greater that -True if left operand is greater than the rightx > y
< Less that -True if left operand is less than the rightx < y
== Equal to -True if both operands are equal x == y
!= Not equal to -True if operands are not equal x != y
>=
Greater than or equal to -True if left operand is greater
than or equal to the right
x >= y
<=
Less than or equal to -True if left operand is less than or
equal to the right
x <= y
I.V Operators
Relational
Arithmetic Operators
Comparison (Relational) Operators
Logical (Boolean) Operators
Bitwise Operators
Assignment Operators
Special Operators
IndentityOperator
Membership Operator
x = 10y = 12
# Output: x > y is False
print('x > y is',x>y)
#Output: x < y is True
print('x < y is',x<y)
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
# Output: x >= y is False
print('x >= y is',x>=y)
# Output: x <= y is True
print('x <= y is',x<=y)
x > y is False
x < y is True
x == y is False
x != y is True
x >= y is False
x <= y is True
I.V Operators
Logical
Arithmetic Operators
Comparison (Relational) Operators
Logical (Boolean) Operators
Bitwise Operators
Assignment Operators
Special Operators
IndentityOperator
Membership Operator
OperatorMeaning Example
and True if both the operands are true x and y
or True if either of the operands is truex or y
not
True if operand is false (complements the
operand)
not x
I.V Operators
Logical
Arithmetic Operators
Comparison (Relational) Operators
Logical (Boolean) Operators
Bitwise Operators
Assignment Operators
Special Operators
IndentityOperator
Membership Operator
x = Truey= False
# Output: x and y is False
print('x and y is',xand y)
# Output: x or y is True
print('x or y is',xor y)
# Output: not x is False
print('not x is',notx)
x and y is False
x or y is True
not x is False
I.V Operators
Bitwise
Arithmetic Operators
Comparison (Relational) Operators
Logical (Boolean) Operators
Bitwise Operators
Assignment Operators
Special Operators
IndentityOperator
Membership Operator
OperatorMeaning Example
& Bitwise AND x& y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shiftx>> 2 = 2 (0000 0010)
<< Bitwise left shiftx<< 2 = 40 (0010 1000)
Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit,
hence the name.
Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
I.V Operators
Bitwise
Arithmetic Operators
Comparison (Relational) Operators
Logical (Boolean) Operators
Bitwise Operators
Assignment Operators
Special Operators
IndentityOperator
Membership Operator
OperatorMeaning Example
& Bitwise AND x& y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shiftx>> 2 = 2 (0000 0010)
<< Bitwise left shiftx<< 2 = 40 (0010 1000)
Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit,
hence the name.
Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
II. Flow Control
i.if...else
ii.for Loop
iii.while Loop
iv.break and continue
v.Pass
II Flow Control
if Statement
if Statement
Flowchart
Syntax
if test expression:
statement(s)
# If the number is positive, we print an appropriate message
num= 3
if num> 0:
print(num, "is a positive number.")
print("This is always printed.")
num= -1if num> 0:
print(num, "is a positive number.")
print("This is also always printed.")
II Flow Control
if...else Statement
if...else Statement
Flowchart
Syntax
num= 3
if num>= 0:
print("Positive or Zero")
else:
print("Negative number")
if test expression:
Body of if
else:
Body of else
II Flow Control
if...elif...else Statement
if...elif...else Statement
Flowchart
Syntax
if num> 0:
print("Positive number")
elifnum== 0:
print("Zero")
else:
print("Negative number")
if test expression:
Body of if
eliftest expression:
Body of elif
else:
Body of else
II Flow Control
if...elif...else Statement
Nested if
Flowchart
Syntax
num= float(input("Enter a number: "))
if num>= 0:
if num== 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
II Flow Control
What is for loop in Python?
for loop
TheforloopinPythonisusedto
iterateoverasequence
(list,tuple,string)orotheriterable
objects.Iteratingoverasequence
iscalledtraversal.
Syntax
for valin sequence:
Body of for
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for valin numbers:
sum = sum+val
# Output: The sum is 48print("The sum is", sum)
II Flow Control
while Loop in Python
while Loop
ThewhileloopinPythonisusedto
iterateoverablockofcodeaslong
asthetestexpression(condition)
istrue.
Syntax
while test_expression:
Body of while
# Program to add natural
# numbers upto
# sum = 1+2+3+...+n
# To take input from the user,
# n = int(input("Enter n: "))n = 10
# initialize sum and counter
sum = 0
i= 1
while i<= n:
sum = sum + i
i= i+1
# update counter
# print the sum
print("The sum is", sum)
II Flow Control
break
break
Thebreakstatementterminates
theloopcontainingit.Controlof
theprogramflowstothe
statementimmediatelyafterthe
bodyoftheloop.
II Flow Control
continue
break and continue
Thecontinuestatementisusedto
skiptherestofthecodeinsidea
loopforthecurrentiterationonly.
Loopdoesnotterminatebut
continuesonwiththenext
iteration.
Thank you
Contact:
Mr. RamarB (PhD)
+91 9498402506