Python_Programming_PPT Basics of python programming language

earningmoney9595 53 views 68 slides Sep 13, 2024
Slide 1
Slide 1 of 68
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

About This Presentation

Basics of python programming language


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

Python Interpreter
•Machinesonlyunderstandmachinecodeormachinelanguage,a
languagerepresentedbystringsofbits—1sand0s.
•Apythoninterpreterisacomputerprogramthatconvertseach
high-levelprogramstatementintomachinecode.
•Aninterpretertranslatesthecommandthatyouwriteoutinto
codethatthecomputercanunderstand.
•Pythonisthemostfamousexampleofahigh-levellanguage.
3

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 Identifiers
•Identifierisauser-definednamegiventoavariable,function,
class,module,etc.
•Theidentifierisacombinationofcharacterdigitsandan
underscore.
•Theyarecase-sensitivei.e.,‘num’and‘Num’and‘NUM’are
threedifferentidentifiers.
16

Python Identifiers
•Rules for Naming Python Identifiers
1.Itcannotbeareservedpythonkeyword.
2.Itshouldnotcontainwhitespace.
3.ItcanbeacombinationofA-Z,a-z,0-9,orunderscore.
4.Itshouldstartwithanalphabetcharacteroranunderscore(_).
5.Itshouldnotcontainanyspecialcharacterotherthanan
underscore(_).
17

Python Examples of Python Identifiers
•Example
•#Legal names:
myvar= "John"
my_var= "John"
_my_var= "John"
myVar= "John"
MYVAR = "John"
myvar2 = "John“
•#Illegal names:
2myvar = "John"
my-var= "John"
my var= "John"
18

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 Operator Precedence
1) x = 7 + 3 * 2
Ans: 13
2) x = 5 + 3 * 2 ** 2 // 4
Ans: 8
3) x = 6 + 3 * 2 –1
Ans:?
28

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
•AStringisadatastructureinPythonthatrepresentsasequenceof
characters.
•Itisanimmutabledatatype,meaningthatonceyouhavecreateda
string,youcannotchangeit.
•Stringsareusedwidelyinmanydifferentapplications,suchasstoring
andmanipulatingtextdata,representingnames,addresses,and
othertypesofdatathatcanberepresentedastext.
•Pythondoesnothaveacharacterdatatype,asinglecharacteris
simplyastringwithalengthof1.
32

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
•StringSlicing:
•InPython,theStringSlicingmethodisusedtoaccessarangeof
charactersintheString.
•SlicinginaStringisdonebyusingaSlicingoperator,i.e.,acolon(:).
•Stringreturnedafterslicingincludesthecharacteratthestartindex
butnotthecharacteratthelastindex.
•Inthisexample,wewillusethestring-slicingmethodtoextracta
substringoftheoriginalstring.The[3:12]indicatesthatthestring
slicingwillstartfromthe3rdindexofthestringtothe12thindex,
(12thcharacternotincluding).Wecanalsousenegativeindexingin
stringslicing.
38

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
•EscapeSequencinginPython:
•WhileprintingStringswithsingleanddoublequotesinit
causesSyntaxErrorbecauseStringalreadycontainsSingleand
DoubleQuotesandhencecannotbeprintedwiththeuseofeitherof
these.
•Hence,toprintsuchaStringeitherTripleQuotesareusedorEscape
sequencesareusedtoprintStrings.
•Escapesequencesstartwithabackslashandcanbeinterpreted
differently.
•Ifsinglequotesareusedtorepresentastring,thenallthesingle
quotespresentinthestringmustbeescapedandthesameisdone
forDoubleQuotes.
46

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

Python Loops
•Aloopisaninstructionthatrepeatsmultipletimesaslongassome
conditionismet.
•Types of Python Loops:
•While Loop
•For Loop
•Break Statement
57

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

Nested Loop
63
Example:
#outer loop
for iin range(1, 11):
# nested loop
# to iterate from 1 to 10
for j in range(1, 11):
# print multiplication
print(i* j, end=' ')
print()
Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

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

68
The End
Tags