Python_Programming_PPT Basics of python programming language
earningmoney9595
53 views
68 slides
Sep 13, 2024
Slide 1 of 68
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
About This Presentation
Basics of python programming language
Size: 614.31 KB
Language: en
Added: Sep 13, 2024
Slides: 68 pages
Slide Content
•PYTHON AS A PROGRAMMING LANGUAGE
•PYTHON DATA TYPES
•STRINGS: BASIC OPERATION, OPERATORS, PRECEDENCE AND ASSOCIATIVITY
•INDEXING AND SLICING
•STRING METHODS, STRING FORMATTING EXPRESSIONS, STRING FORMATTING
METHOD CALLS
•COMMENTS
•EXPRESSIONS
•VARIABLES,ASSIGNMENTS
•CONTROL STRUCTURES
•LOOPING AND BRANCHING STATEMENTS
PYTHON PROGRAMMING
UNIT-I:
Python Introduction
•Pythonisadynamic,highlevel,freeopensourceandinterpreted
programminglanguage.Itsupportsobject-orientedprogramming
aswellasproceduralorientedprogramming.
•PythonisaprogramminglanguagethatincludesfeaturesofCand
Java.ItprovidesthestyleofwritinganelegantcodelikeC,andfor
object-orientedprogramming,itoffersclassesandobjectslike
Java.
•ItwascreatedbyGuidovanRossum,andreleasedin1991.
•Python is commonly used fordeveloping websites and software,
game development, data analysis, and data visualization.
2
Features of Python
1.FreeandOpenSource:
•Pythonlanguageisfreelyavailableattheofficialwebsiteandyou
candownloadit.Sinceitisopen-source,thismeansthatsource
codeisalsoavailabletothepublic.Soyoucandownloadit,useit
aswellasshareit.
2.Easytocode:
•Pythonisahigh-levelprogramminglanguage.Pythonisveryeasy
tolearnthelanguageascomparedtootherlanguageslikeC,C#,
Javascript,Java,etc.ItisveryeasytocodeinthePython
languageandanybodycanlearnPythonbasicsinafewhoursor
days.Itisalsoadeveloper-friendlylanguage.
4
Features of Python
3.EasytoRead:
•Python’ssyntaxisstraightforward.Thecodeblockisdefinedbythe
indentationsratherthanbysemicolonsorbrackets.
4.Object-OrientedLanguage:
•OneofthekeyfeaturesofPythonisObject-Orientedprogramming.
Pythonsupportsobject-orientedlanguageandconceptsofclasses,
objectencapsulation,etc.
5.GUIProgrammingSupport:
•GraphicalUserinterfacescanbemadeusingamodulesuch
asPyQt5,PyQt4,wxPython,orTkinPython.PyQt5isthemost
popularoptionforcreatinggraphicalappswithPython.
5
Features of Python
6.High-LevelLanguage:
•Pythonisahigh-levellanguage.Whenwewriteprogramsin
Python,wedonotneedtorememberthesystemarchitecture,nor
doweneedtomanagethememory.
7.LargeCommunitySupport:
•Pythonhasgainedpopularityovertheyears.Ourquestionsare
constantlyansweredbytheenormousStackOverflowcommunity.
8.EasytoDebug:
•Excellentinformationformistaketracing.Youwillbeabletoquickly
identifyandcorrectthemajorityofyourprogram’sissuesonceyou
understandhowtointerpretPython’serrortraces.
6
Features of Python
9.PythonisaPortablelanguage:
•IfwehavePythoncodeforWindowsandifwewanttorunthiscode
onotherplatformssuchasLinux,Unix,andMacthenwedonotneed
tochangeit,wecanrunthiscodeonanyplatform.
10.PythonisanIntegratedlanguage:
•PythonisalsoanIntegratedlanguagebecausewecaneasilyintegrate
PythonwithotherlanguageslikeC,C++,etc.
11.InterpretedLanguage:
•PythonisanInterpretedLanguagebecausePythoncodeisexecuted
linebylineatatime.likeotherlanguagesC,C++,Java,etc.thereisno
needtocompilePythoncodethismakesiteasiertodebugourcode.
ThesourcecodeofPythonisconvertedintoanimmediateform
calledbytecode. 7
Features of Python
12. Large Standard Library:
•Python has a largestandard librarythat provides a rich set of modules
and functions so you do not have to write your own code for every
single thing. There are many libraries present in Python such asregular
expressions,unit-testing, web browsers, etc.
13. Dynamically Typed Language:
•Python is a dynamically-typed language. That means the type for a
variable is decided at run time not in advance because of this feature
we don’t need to specify the type of variable.
15. Allocating Memory Dynamically:
•In Python, the variable data type does not need to be specified. The
memory is automatically allocated to a variable at runtime when it is
given a value. 8
Python Installation
•Download Python Executable Installer from www.python.org
9
First Python Program Execution
1) Interactive Mode Programming
•Invokingtheinterpreterwithoutpassingascriptfileasa
parameterbringsupthefollowingprompt
10
First Python Program Execution
2) Script Mode Programming
•Invokingtheinterpreterwithascriptparameterbeginsexecution
ofthescriptandcontinuesuntilthescriptisfinished.Whenthe
scriptisfinished,theinterpreterisnolongeractive.
•LetuswriteasimplePythonprograminascript.Pythonfiles
haveextension.py.Typethefollowingsourcecodeinatest.py
file−
•print("Hello,Python!“)
11
Python Indentation
•Indentationreferstothespacesatthebeginningofacodeline.
•Whereinotherprogramminglanguagestheindentationincode
isforreadabilityonly,theindentationinPythonisvery
important.
•Pythonusesindentationtoindicateablockofcode.
•Example
•if 5>2:
print("Five is greater than two!")
12
Python Comment
•Comments can be used to explain Python code.
•Comments can be used to make the code more readable.
•Comments can be used to prevent execution when testing code.
•Creating a Comment: Comments starts with a #, and Python will
ignore them.
•Example
•#This is a comment
print("Hello, World!")
13
Python Multi Line Comment
•To add a multiline comment:
1.insert a # for each line.
2.you can add a multiline string (triple quotes) in your code, and
place your comment inside it
•Example
•"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
14
Python Variables
•Variablesarecontainersforstoringdatavalues.
•Unlikeotherprogramminglanguages,Pythonhasnocommand
fordeclaringavariable.
•Avariableiscreatedthemomentyoufirstassignavaluetoit.
•Variablesdonotneedtobedeclaredwithanyparticulartypeand
canevenchangetypeaftertheyhavebeenset.
•Example: Assign Value to Variable
•x = 5
y = "John"
print(x)
print(y)
15
Python Operators
•Operators in general are used to perform operations on values
and variables. These are standard symbols used for the purpose
of logical and arithmetic operations.
•OPERATORS: These are the special symbols. Eg-+ , * , /, etc.
•OPERAND: It is the value on which the operator is applied.
•Types of Operators in Python
1.Arithmetic Operators
2.Comparison Operators
3.Logical Operators
4.Bitwise Operators
5.Assignment Operators
6.Identity Operators and Membership Operators
19
Python Arithmetic Operators
20
Operator Description Syntax
+ Addition: adds two operands x + y
– Subtraction: subtracts two operands x –y
* Multiplication: multiplies two operandsx * y
/
Division (float): divides the first operand by
the second
x / y
//
Division (floor): divides the first operand by
the second
x // y
%
Modulus: returns the remainder when the
first operand is divided by the second
x % y
** Power: Returns first raised to power secondx ** y
Python Comparison Operators
21
Operator Description Syntax
>
Greater than: True if the left operand is greater than the
right
x > y
< Less than: True if the 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 the left operand is greater
than or equal to the right
x >= y
<=
Less than or equal to True if the left operand is less than or
equal to the right
x <= y
Python Logical Operators
22
Operator Description Syntax
and Logical AND: True if both the operands are truex and y
Or Logical OR: True if either of the operands is truex or y
not Logical NOT: True if the operand is falsenot x
Python Bitwise Operators
23
Operator Description Syntax
& Bitwise AND x & y
| Bitwise OR x | y
~ Bitwise NOT ~x
^ Bitwise XOR x ^ y
>> Bitwise right shift x>>
<< Bitwise left shift x<<
Python Assignment Operators
24
Operator Description Syntax
= Assign the value of the right side of the expression to the left side operandx = y + z
+=
Add AND: Add right-side operand with left-side operand and then assign to left
operand
a+=b a=a+b
-=
Subtract AND: Subtract right operand from left operand and then assign to left
operand
a-=b a=a-b
*=
Multiply AND: Multiply right operand with left operand and then assign to left
operand
a*=b a=a*b
/= Divide AND: Divide left operand with right operand and then assign to left operanda/=b a=a/b
%=
Modulus AND: Takes modulus using left and right operands and assign the result to
left operand
a%=b a=a%b
//=
Divide(floor) AND: Divide left operand with right operand and then assign the
value(floor) to left operand
a//=b a=a//b
**=
Exponent AND: Calculate exponent(raise power) value using operands and assign
value to left operand
a**=b a=a**b
Python Identity Operators
•In Python,isandis notare theidentity operatorsboth are used to
check if two values are located on the same part of the memory.
•Two variables that are equal do not imply that they are identical.
•is :True if the operands are identical
•is not: True if the operands are not identical
25
Python Membership Operators
•In Python,inandnot inare themembership operatorsthat are used
to test whether a value or variable is in a sequence.
•in:True if value is found in the sequence
•not in:True if value is not found in the sequence
26
Python Operator Precedence
27
Operator Description Operator Description
** Exponentiation I Bitwise OR
+x, -x Positive, negative <, , >=, !=, ==Comparison operators
*, /, //, %
Multiplication, division, floor
division, modulo
is, is not Identity operators
+, – Addition, subtraction in, not in Membership operators
<> Bitwise shift operators not Logical NOT
& Bitwise AND and Logical AND
^ Bitwise XOR or Logical OR
Python Data Types
•Variables can store data of different types, and different types can do
different things.
•Python has the following data types built-in by default, in these
categories:
1.Text Type: str
2.Numeric Types: int, float,complex
3.Sequence Types: list,tuple,range
4.Mapping Type: dict
5.Set Types: set,frozenset
6.Boolean Type: bool
29
Python Data Types
•Getting the Data Type:
•You can get the data type of any object by using thetype()function:
•Example: Print the data type of the variable x:
x =5
print(type(x))
Output:
<class 'int'>
30
Python Data Types
31
Example DataTypes
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
Python Strings
Creating a String in Python:
•Strings in Pythoncan be created using single quotes or double
quotes or even triple quotes.Let us see how we can define a string in
Python.
Example:
String1 = 'Welcome to DSU‘
print(String1)
Output:
Welcome to DSU
33
Python String Indexing
•Accessing characters in Python String (String Indexing)
•In Python, individual characters of a String can be accessed by using
the method of Indexing.
•Indexing allows negative address references to access characters
from the back of the String, e.g. -1 refers to the last character, -2
refers to the second last character, and so on.
•While accessing an index out of the range will cause anIndexError.
•Only Integers are allowed to be passed as an index, float or other
types that will cause aTypeError.
34
Python String Indexing
35
Python String Indexing
36
Example:
String1="GeeksForGeeks"
print("InitialString:")
print(String1)
print("\nFirstcharacterofStringis:")
print(String1[0])
print("\nLastcharacterofStringis:")
print(String1[-1])
Output:
Initial String:
GeeksForGeeks
First character of String is:
G
Last character of String is:
s
Python String Indexing
•Reversing a Python String:
•By accessing characters from a string, we can alsoreverse strings in
Python.
•We can Reverse a string by using String slicing method.
37
Example:
str= "geeksforgeeks"
print(str[::-1])
Output:
skeegrofskeeg
Python String Slicing
39
Example:
String1="GeeksForGeeks"
print("InitialString:")
print(String1)
print("\nSlicingcharactersfrom3-12:")
print(String1[3:12])
print("\nSlicingcharactersbetween"+
"3rdand2ndlastcharacter:")
print(String1[3:-2])
Output:
Initial String:
GeeksForGeeks
Slicing characters from 3-12:
ksForGeek
Slicing characters between 3rd and 2nd
last character:
ksForGee
Python String
•Deleting from a String:
•In Python, the Updationor deletion of characters from a String is not
allowed.
•This will cause an error because item assignment or item deletion
from a String is not supported.
•Although deletion of the entire String is possible with the use of a
built-in del keyword.
•This is because Strings are immutable, hence elements of a String
cannot be changed once assigned. Only new strings can be
reassigned to the same name.
40
Python String
•Updating a character
•A character of a string can be updated in Python by first converting
the string into aPython Listand then updating the element in the
list.
•As lists are mutable in nature, we can update the character and then
convert the list back into the String.
•Another method is using the string slicing method. Slice the string
before the character you want to update, then add the new
character and finally add the other part of the string again by string
slicing.
41
Python String
42
#PythonProgramtoUpdatecharacterofaString
String1="Hello,I'maGeek"
print("InitialString:")
print(String1)
list1=list(String1)
list1[2]='p'
String2=''.join(list1)
print("\nUpdatingcharacterat2ndIndex:")
print(String2)
String3=String1[0:2]+'p'+String1[3:]
print(String3)
Output:
Initial String:
Hello, I'm a Geek
Updating character at 2nd Index:
Heplo, I'm a Geek
Heplo, I'm a Geek
Python String
•Updating Entire String:
•As Python strings are immutable in nature, we cannot update the
existing string. We can only assign a completely new value to the
variable with the same name.
43
String1="Hello,I'maGeek"
print("InitialString:")
print(String1)
String1="WelcometotheGeekWorld"
print("\nUpdatedString:")
print(String1)
Output:
Initial String:
Hello, I'm a Geek
Updated String:
Welcome to the Geek World
Python String
•Deleting a character
•Python strings are immutable, that means we cannot delete a
character from it. When we try to delete the character using
thedelkeyword, it will generate an error.
•So we will first slice the string up to the character that we want to
delete and then concatenate the remaining string next from the
deleted character.
44
Python String
45
Example:
String1="Hello,I'maGeek"
print("InitialString:")
print(String1)
String2=String1[0:2]+String1[3:]
print("\nDeletingcharacterat2nd
Index:")
print(String2)
Output:
Initial String:
Hello, I'm a Geek
Deleting character at 2nd Index:
Helo, I'm a Geek
Python String Escape Sequences
47
String1 = '''I'm a "Geek"'''
print("Initial String with use of Triple Quotes: ")
print(String1)
# Escaping Single Quote
String1 = 'I\'m a "Geek"'
print("\nEscapingSingle Quote: ")
print(String1)
# Escaping Double Quotes
String1 = "I'm a \"Geek\""
print("\nEscapingDouble Quotes: ")
print(String1)
# Printing Paths with the use of Escape Sequences
String1 = "C:\\Python\\Geeks\\"
print("\nEscapingBackslashes: ")
print(String1)
# Printing Paths with the use of Tab
String1 = "Hi\tGeeks"
print("\nTab: ")
print(String1)
# Printing Paths with theuse of New Line
String1 = "Python\nGeeks"
print("\nNewLine: ")
print(String1)
Output:
Initial String with use of Triple Quotes:
I'm a "Geek"
Escaping Single Quote:
I'm a "Geek"
Escaping Double Quotes:
I'm a "Geek"
Escaping Backslashes:
C:\Python\Geeks\
Tab:
Hi Geeks
New Line:
Python
Geeks
Python String Escape Sequences
48
String1 = '''I'm a "Geek"'''
print("Initial String with use of Triple Quotes: ")
print(String1)
# Escaping Single Quote
String1 = 'I\'m a "Geek"'
print("\nEscapingSingle Quote: ")
print(String1)
# Escaping Double Quotes
String1 = "I'm a \"Geek\""
print("\nEscapingDouble Quotes: ")
print(String1)
# Printing Paths with the use of Escape Sequences
String1 = "C:\\Python\\Geeks\\"
print("\nEscapingBackslashes: ")
print(String1)
# Printing Paths with the use of Tab
String1 = "Hi\tGeeks"
print("\nTab: ")
print(String1)
# Printing Paths with theuse of New Line
String1 = "Python\nGeeks"
print("\nNewLine: ")
print(String1)
Output:
Initial String with use of Triple Quotes:
I'm a "Geek"
Escaping Single Quote:
I'm a "Geek"
Escaping Double Quotes:
I'm a "Geek"
Escaping Backslashes:
C:\Python\Geeks\
Tab:
Hi Geeks
New Line:
Python
Geeks
Python Conditionals
•Pythonsupportstheusuallogicalconditionsfrommathematics:
Theseconditionscanbeusedinseveralways,mostcommonlyin"if
statements"andloops.
•Equals:a == b
•Not Equals:a != b
•Less than:a < b
•Less than or equal to:a <= b
•Greater than:a > b
•Greater than or equal to:a >= b
49
Python If Condition
•An "if statement" is written by using theifkeyword.
•Example of If statement:
•a =33
b =200
ifb > a:
print("b is greater than a")
•Output:
•b is greater than a
50
Python ElifCondition
•TheelifkeywordisPython'swayofsaying"iftheprevious
conditionswerenottrue,thentrythiscondition".
•Example
•a =33
b =33
ifb > a:
print("b is greater than a")
elifa == b:
print("a and b are equal")
51
Python Else Condition
•Theelsekeywordcatchesanythingwhichisn'tcaughtbythe
precedingconditions.
•Example
•a =200
b =33
ifb > a:
print("b is greater than a")
elifa == b:
print("a and b are equal")
else:
print("a is greater than b")
52
Python And Condition
•Theandkeywordisalogicaloperator,andisusedtocombine
conditionalstatements:
•Example
•Test ifais greater thanb, AND ifcis greater thana:
•a =200
b =33
c =500
ifa > b and c > a:
print("Both conditions are True")
•Output:
•Both conditions are True
53
Python Or Condition
•Theorkeyword is a logical operator, and is used to combine
conditional statements:
•Example
•Test ifais greater thanb, OR ifais greater thanc:
•a =200
b =33
c =500
ifa > b or a > c:
print("At least one of the conditions is True")
•Output:
•At least one of the conditions is True
54
Python not Condition
•Thenotkeyword is a logical operator, and is used to reverse the
result of the conditional statement:
•Example
•Test ifais NOT greater thanb:
•a =33
b =200
ifnot a > b:
print("a is NOT greater than b")
•Output:
•a is NOT greater than b
55
Python Nested if Condition
•You can haveifstatements insideifstatements, this is called nested
if statements.
•Example
•x =41
ifx >10:
print("Above ten,")
ifx >20:
print("and also above 20!")
else:
print("but not above 20.")
•Output:
•Above ten,
and also above 20!
56
While Loop
•Thewhileloopisusedtoexecuteasetofstatementsaslongasa
conditionistrue.
58
While Loop
•WhileLoopSyntax:
while expression:
statement(s)
59
Example:
count = 0
while (count < 3):
count = count + 1
print("Hello GM")
Output:
Hello GM
Hello GM
Hello GM
For Loop
•AforloopinPythonisusedtoiterateoverasequence(list,tuple,
set,dictionary,andstring).
60
For Loop
•For Loop Syntax:
for iterator_varin sequence:
statements(s)
61
Example:
n = 4
for iin range(0, n):
print(i)
Output:
0 1 2 3
Nested Loop
•Python programming language allows to use one loop inside another
loop which is callednested loop.
•Nested Loops Syntax:
for iterator_varin sequence:
for iterator_varin sequence:
statements(s)
statements(s)
62
Continue Statement
•Thecontinue statementin Python returns the control to the
beginning of the loop.
64
Example:
for letter in 'geeksfor':
if letter == 'e' or letter == 's':
continue
print('Current Letter :', letter)
Output:
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Break Statement
•Thebreak statementin Python brings control out of the loop.
65
Example:
for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
break
print('Current Letter :', letter)
Output:
Current Letter : e
Pass Statement
•WeusepassstatementinPythontowriteemptyloops.Passisalso
usedforemptycontrolstatements,functionsandclasses.
•Example:ThisPythoncodeiteratesthroughthecharactersofthe
string‘geeksforgeeks’usinga‘for'loop.However,itdoesn’tperform
anyspecificactionwithintheloop,andthe‘pass'statementisused.
Aftertheloop,itprints“LastLetter:”followedbythelastcharacter
inthestring,whichis‘s’.
66
Example:
for letter in 'geeksforgeeks':
pass
print('Last Letter :', letter)
Output:
Last Letter : s
Questions From Unit-1
1)Explain Features of Python Programming Language.
2)Explain different types of comments in Python.
3)What is Variable? How to assign Value to variable in python?
4)What is Python identifier? Write rules for naming the identifiers. Give some examples
of legal names of identifiers.
5)What are Python Operators? Explain Types of operators in detail with example.
6)What is difference between == and ‘is’ operator in python?
7)Explain Built-in data types of python.
8)What is string in python? Explain String Indexing and slicing with example.
9)Explain Escape Sequences in python.
10)Explain if, elifand else with example.
11)Explain while loop and for loop with syntax and example.
12)Explain usage of continue, break and pass keyword in python.
67