SlideShare a Scribd company logo
11
Most read
12
Most read
14
Most read
PYTHON - BASIC OPERATORS
Python language supports following type of operators.
• Arithmetic Operators
• Comparision Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
PYTHON ARITHMETIC
OPERATORS:
Operato
r
Description Example
+ Addition - Adds values on either side of
the operator
a + b will give 30
- Subtraction - Subtracts right hand
operand from left hand operand
a - b will give -10
* Multiplication - Multiplies values on either
side of the operator
a * b will give 200
/ Division - Divides left hand operand by
right hand operand
b / a will give 2
% Modulus - Divides left hand operand by
right hand operand and returns
remainder
b % a will give 0
** Exponent - Performs exponential (power)
calculation on operators
a**b will give 10 to
the power 20
// Floor Division - The division of operands
where the result is the quotient in which
the digits after the decimal point are
removed.
9//2 is equal to 4 and
9.0//2.0 is equal to
4.0
PYTHON COMPARISON
OPERATORS:
Operat
or
Description Example
== Checks if the value of two operands are equal or
not, if yes then condition becomes true.
(a == b) is not true.
!= Checks if the value of two operands are equal or
not, if values are not equal then condition becomes
true.
(a != b) is true.
<> Checks if the value of two operands are equal or
not, if values are not equal then condition becomes
true.
(a <> b) is true. This
is similar to !=
operator.
> Checks if the value of left operand is greater than
the value of right operand, if yes then condition
becomes true.
(a > b) is not true.
< Checks if the value of left operand is less than the
value of right operand, if yes then condition
becomes true.
(a < b) is true.
>= Checks if the value of left operand is greater than or
equal to the value of right operand, if yes then
condition becomes true.
(a >= b) is not true.
<= Checks if the value of left operand is less than or
equal to the value of right operand, if yes then
condition becomes true.
(a <= b) is true.
PYTHON ASSIGNMENT
OPERATORS:
Operator Description Example
= Simple assignment operator, Assigns values from right
side operands to left side operand
c = a + b will
assigne value of a +
b into c
+= Add AND assignment operator, It adds right operand to
the left operand and assign the result to left operand
c += a is equivalent
to c = c + a
-= Subtract AND assignment operator, It subtracts right
operand from the left operand and assign the result to left
operand
c -= a is equivalent
to c = c - a
*= Multiply AND assignment operator, It multiplies right
operand with the left operand and assign the result to left
operand
c *= a is equivalent
to c = c * a
/= Divide AND assignment operator, It divides left operand
with the right operand and assign the result to left
operand
c /= a is equivalent
to c = c / a
%= Modulus AND assignment operator, It takes modulus
using two operands and assign the result to left operand
c %= a is equivalent
to c = c % a
**= Exponent AND assignment operator, Performs exponential
(power) calculation on operators and assign value to the
left operand
c **= a is
equivalent to c = c
** a
//= Floor Division and assigns a value, Performs floor division
on operators and assign value to the left operand
c //= a is equivalent
to c = c // a
PYTHON BITWISE OPERATORS:
Operat
or
Description Example
& Binary AND Operator copies a bit to the
result if it exists in both operands.
(a & b) will give 12
which is 0000 1100
| Binary OR Operator copies a bit if it
exists in either operand.
(a | b) will give 61
which is 0011 1101
^ Binary XOR Operator copies the bit if it is
set in one operand but not both.
(a ^ b) will give 49
which is 0011 0001
~ Binary Ones Complement Operator is
unary and has the effect of 'flipping' bits.
(~a ) will give -60
which is 1100 0011
<< Binary Left Shift Operator. The left
operands value is moved left by the
number of bits specified by the right
operand.
a << 2 will give 240
which is 1111 0000
>> Binary Right Shift Operator. The left
operands value is moved right by the
number of bits specified by the right
operand.
a >> 2 will give 15
which is 0000 1111
PYTHON LOGICAL OPERATORS:
Opera
tor
Description Example
and Called Logical AND operator. If both the
operands are true then then condition
becomes true.
(a and b) is true.
or Called Logical OR Operator. If any of the
two operands are non zero then then
condition becomes true.
(a or b) is true.
not Called Logical NOT Operator. Use to
reverses the logical state of its operand. If
a condition is true then Logical NOT
operator will make false.
not(a and b) is false.
PYTHON MEMBERSHIP
OPERATORS:
In addition to the operators discussed previously, Python has
membership operators, which test for membership in a sequence,
such as strings, lists, or tuples.
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 in Evaluates 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 a
member of sequence y.
PYTHON OPERATORS
PRECEDENCE
Operator Description
** Exponentiation (raise to the power)
~ + - Ccomplement, unary plus and minus (method names for
the last two are +@ and -@)
* / % // 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
PYTHON - IF...ELIF...ELSE
STATEMENT
• The syntax of the if statement is:
if expression:
statement(s)
Example:
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
print "Good bye!"
if expression:
statement(s)
else:
statement(s)
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
else:
print "2 - Got a false expression value"
print var2
print "Good bye!"
THE NESTED IF...ELIF...ELSE
CONSTRUCT
Example:
var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
elif var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"
print "Good bye!"
SINGLE STATEMENT SUITES:
If the suite of an if clause consists only of a single line, it may go on
the same line as the header statement:
if ( expression == 1 ) : print "Value of expression is 1"
5. PYTHON - WHILE LOOP
STATEMENTS
• The while loop is one of the looping constructs available in Python. The while loop continues
until the expression becomes false. The expression has to be a logical expression and must
return either a true or a false value
The syntax of the while loop is:
while expression:
statement(s)
Example:
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
THE INFINITE LOOPS:
• You must use caution when using while loops because of the
possibility that this condition never resolves to a false value. This
results in a loop that never ends. Such a loop is called an infinite
loop.
• An infinite loop might be useful in client/server programming where
the server needs to run continuously so that client programs can
communicate with it as and when required.
Following loop will continue till you enter CTRL+C :
while var == 1 : # This constructs an infinite loop
num = raw_input("Enter a number :")
print "You entered: ", num
print "Good bye!"
SINGLE STATEMENT SUITES:
• Similar to the if statement syntax, if your while clause consists
only of a single statement, it may be placed on the same line as
the while header.
• Here is the syntax of a one-line while clause:
while expression : statement
6. PYTHON - FOR LOOP STATEMENTS
• The for loop in Python has the ability to iterate over the items of any sequence,
such as a list or a string.
• The syntax of the loop look is:
for iterating_var in sequence:
statements(s)
Example:
for letter in 'Python': # First Example
print 'Current Letter :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print 'Current fruit :', fruit
print "Good bye!"
Iterating by Sequence Index:
• An alternative way of iterating through each item is by index offset into the
sequence itself:
• Example:
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]
print "Good bye!"
7. PYTHON BREAK,CONTINUE AND PASS
STATEMENTS
The break Statement:
• The break statement in Python terminates the current loop and resumes execution at the
next statement, just like the traditional break found in C.
Example:
for letter in 'Python': # First Example
if letter == 'h':
break
print 'Current Letter :', letter
var = 10 # Second Example
while var > 0:
print 'Current variable value :', var
var = var -1
if var == 5:
break
print "Good bye!"
The continue Statement:
• The continue statement in Python returns the control to the beginning of the
while loop. The continue statement rejects all the remaining statements in the
current iteration of the loop and moves the control back to the top of the loop.
Example:
for letter in 'Python': # First Example
if letter == 'h':
continue
print 'Current Letter :', letter
var = 10 # Second Example
while var > 0:
var = var -1
if var == 5:
continue
print 'Current variable value :', var
print "Good bye!"
THE ELSE STATEMENT USED WITH LOOPS
Python supports to have an else statement associated with a loop statements.
• If the else statement is used with a for loop, the else statement is executed when the loop
has exhausted iterating the list.
• If the else statement is used with a while loop, the else statement is executed when the
condition becomes false.
Example:
for num in range(10,20): #to iterate between 10 to 20
for i in range(2,num): #to iterate on the factors of the number
if num%i == 0: #to determine the first factor
j=num/i #to calculate the second factor
print '%d equals %d * %d' % (num,i,j)
break #to move to the next number, the #first FOR
else: # else part of the loop
print num, 'is a prime number'
THE PASS STATEMENT:
• The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to execute.
• The pass statement is a null operation; nothing happens when it
executes. The pass is also useful in places where your code will
eventually go, but has not been written yet (e.g., in stubs for
example):
Example:
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter
print "Good bye!"

More Related Content

PPTX
Python programming
Ashwin Kumar Ramasamy
 
PPT
Modular programming
Mohanlal Sukhadia University (MLSU)
 
PPT
Intro automata theory
Rajendran
 
PPTX
C Programming: Control Structure
Sokngim Sa
 
PPT
Boolean Algebra
blaircomp2003
 
PPTX
Object Oriented Programming Using C++
Muhammad Waqas
 
PPTX
Operator.ppt
Darshan Patel
 
PPTX
Python-Functions.pptx
Karudaiyar Ganapathy
 
Python programming
Ashwin Kumar Ramasamy
 
Intro automata theory
Rajendran
 
C Programming: Control Structure
Sokngim Sa
 
Boolean Algebra
blaircomp2003
 
Object Oriented Programming Using C++
Muhammad Waqas
 
Operator.ppt
Darshan Patel
 
Python-Functions.pptx
Karudaiyar Ganapathy
 

What's hot (20)

PPTX
Python-Inheritance.pptx
Karudaiyar Ganapathy
 
PPTX
Union in c language
tanmaymodi4
 
PPT
Functions in C++
Mohammed Sikander
 
ODP
Function
jayesh30sikchi
 
PPTX
Tokens in C++
Mahender Boda
 
PPTX
Recursive Function
Harsh Pathak
 
PPTX
Abstract Data Types
karthikeyanC40
 
PPTX
Functions in c language
tanmaymodi4
 
PPTX
Python Functions
Mohammed Sikander
 
PPTX
Java Tokens
Madishetty Prathibha
 
PPTX
Compare between pop and oop
Md Ibrahim Khalil
 
PPTX
Operators in Python
Anusuya123
 
PPTX
Datatype in c++ unit 3 -topic 2
MOHIT TOMAR
 
PPT
Control statements
raksharao
 
PPTX
Function in c program
umesh patil
 
PPTX
Python Programming | JNTUA | UNIT 2 | Fruitful Functions |
FabMinds
 
PPTX
Control statements in c
Sathish Narayanan
 
PPTX
Decision Making & Loops
Akhil Kaushik
 
PPTX
Preprocessor directives in c language
tanmaymodi4
 
Python-Inheritance.pptx
Karudaiyar Ganapathy
 
Union in c language
tanmaymodi4
 
Functions in C++
Mohammed Sikander
 
Function
jayesh30sikchi
 
Tokens in C++
Mahender Boda
 
Recursive Function
Harsh Pathak
 
Abstract Data Types
karthikeyanC40
 
Functions in c language
tanmaymodi4
 
Python Functions
Mohammed Sikander
 
Compare between pop and oop
Md Ibrahim Khalil
 
Operators in Python
Anusuya123
 
Datatype in c++ unit 3 -topic 2
MOHIT TOMAR
 
Control statements
raksharao
 
Function in c program
umesh patil
 
Python Programming | JNTUA | UNIT 2 | Fruitful Functions |
FabMinds
 
Control statements in c
Sathish Narayanan
 
Decision Making & Loops
Akhil Kaushik
 
Preprocessor directives in c language
tanmaymodi4
 
Ad

Similar to python operators.ppt (20)

PPT
Py-Slides-2 (1).ppt
KalaiVani395886
 
PPT
Py-Slides-2.ppt
TejaValmiki
 
PPT
Py-Slides-2.ppt
AllanGuevarra1
 
PPT
hlukj6;lukm,t.mnjhgjukryopkiu;lyk y2.ppt
PraveenaFppt
 
PPTX
btwggggggggggggggggggggggggggggggisop correct (1).pptx
Orin18
 
PPTX
Python programming language introduction unit
michaelaaron25322
 
PDF
Java basic operators
Emmanuel Alimpolos
 
PDF
Java basic operators
Emmanuel Alimpolos
 
PDF
Coper in C
thirumalaikumar3
 
PPT
C Sharp Jn (2)
jahanullah
 
PPT
C Sharp Jn (2)
guest58c84c
 
PPT
Operators and Expressions in C++
Praveen M Jigajinni
 
PDF
04. Ruby Operators Slides - Ruby Core Teaching
quanhoangd129
 
PPTX
Python notes for students to develop and learn
kavithaadhilakshmi
 
PPTX
Opeartor &amp; expression
V.V.Vanniapermal College for Women
 
PPT
operators and expressions in c++
sanya6900
 
PDF
Types of Operators in C
Thesis Scientist Private Limited
 
PDF
itft-Operators in java
Atul Sehdev
 
PPTX
Lecture 2 C++ | Variable Scope, Operators in c++
Himanshu Kaushik
 
PPT
4_A1208223655_21789_2_2018_04. Operators.ppt
RithwikRanjan
 
Py-Slides-2 (1).ppt
KalaiVani395886
 
Py-Slides-2.ppt
TejaValmiki
 
Py-Slides-2.ppt
AllanGuevarra1
 
hlukj6;lukm,t.mnjhgjukryopkiu;lyk y2.ppt
PraveenaFppt
 
btwggggggggggggggggggggggggggggggisop correct (1).pptx
Orin18
 
Python programming language introduction unit
michaelaaron25322
 
Java basic operators
Emmanuel Alimpolos
 
Java basic operators
Emmanuel Alimpolos
 
Coper in C
thirumalaikumar3
 
C Sharp Jn (2)
jahanullah
 
C Sharp Jn (2)
guest58c84c
 
Operators and Expressions in C++
Praveen M Jigajinni
 
04. Ruby Operators Slides - Ruby Core Teaching
quanhoangd129
 
Python notes for students to develop and learn
kavithaadhilakshmi
 
Opeartor &amp; expression
V.V.Vanniapermal College for Women
 
operators and expressions in c++
sanya6900
 
Types of Operators in C
Thesis Scientist Private Limited
 
itft-Operators in java
Atul Sehdev
 
Lecture 2 C++ | Variable Scope, Operators in c++
Himanshu Kaushik
 
4_A1208223655_21789_2_2018_04. Operators.ppt
RithwikRanjan
 
Ad

Recently uploaded (20)

PDF
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
PDF
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PPTX
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
PDF
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PDF
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
DOCX
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
PDF
Become an Agentblazer Champion Challenge
Dele Amefo
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PDF
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
PPTX
Services offered by Dynamic Solutions in Pakistan
DaniyaalAdeemShibli1
 
PDF
How to Seamlessly Integrate Salesforce Data Cloud with Marketing Cloud.pdf
NSIQINFOTECH
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PDF
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
PPTX
Presentation of Computer CLASS 2 .pptx
darshilchaudhary558
 
PDF
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
PDF
Bandai Playdia The Book - David Glotz
BluePanther6
 
PPTX
TestNG for Java Testing and Automation testing
ssuser0213cb
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
PPTX
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
Become an Agentblazer Champion Challenge
Dele Amefo
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
Services offered by Dynamic Solutions in Pakistan
DaniyaalAdeemShibli1
 
How to Seamlessly Integrate Salesforce Data Cloud with Marketing Cloud.pdf
NSIQINFOTECH
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
Presentation of Computer CLASS 2 .pptx
darshilchaudhary558
 
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
Bandai Playdia The Book - David Glotz
BluePanther6
 
TestNG for Java Testing and Automation testing
ssuser0213cb
 
Presentation about variables and constant.pptx
kr2589474
 
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 

python operators.ppt

  • 1. PYTHON - BASIC OPERATORS Python language supports following type of operators. • Arithmetic Operators • Comparision Operators • Logical (or Relational) Operators • Assignment Operators • Conditional (or ternary) Operators
  • 2. PYTHON ARITHMETIC OPERATORS: Operato r Description Example + Addition - Adds values on either side of the operator a + b will give 30 - Subtraction - Subtracts right hand operand from left hand operand a - b will give -10 * Multiplication - Multiplies values on either side of the operator a * b will give 200 / Division - Divides left hand operand by right hand operand b / a will give 2 % Modulus - Divides left hand operand by right hand operand and returns remainder b % a will give 0 ** Exponent - Performs exponential (power) calculation on operators a**b will give 10 to the power 20 // Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. 9//2 is equal to 4 and 9.0//2.0 is equal to 4.0
  • 3. PYTHON COMPARISON OPERATORS: Operat or Description Example == Checks if the value of two operands are equal or not, if yes then condition becomes true. (a == b) is not true. != Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (a != b) is true. <> Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (a <> b) is true. This is similar to != operator. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (a > b) is not true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (a < b) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (a >= b) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (a <= b) is true.
  • 4. PYTHON ASSIGNMENT OPERATORS: Operator Description Example = Simple assignment operator, Assigns values from right side operands to left side operand c = a + b will assigne value of a + b into c += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a -= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a *= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a /= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / a %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a **= Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a //= Floor Division and assigns a value, Performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c // a
  • 5. PYTHON BITWISE OPERATORS: Operat or Description Example & Binary AND Operator copies a bit to the result if it exists in both operands. (a & b) will give 12 which is 0000 1100 | Binary OR Operator copies a bit if it exists in either operand. (a | b) will give 61 which is 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (a ^ b) will give 49 which is 0011 0001 ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~a ) will give -60 which is 1100 0011 << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. a << 2 will give 240 which is 1111 0000 >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. a >> 2 will give 15 which is 0000 1111
  • 6. PYTHON LOGICAL OPERATORS: Opera tor Description Example and Called Logical AND operator. If both the operands are true then then condition becomes true. (a and b) is true. or Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. (a or b) is true. not Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. not(a and b) is false.
  • 7. PYTHON MEMBERSHIP OPERATORS: In addition to the operators discussed previously, Python has membership operators, which test for membership in a sequence, such as strings, lists, or tuples. 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 in Evaluates 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 a member of sequence y.
  • 8. PYTHON OPERATORS PRECEDENCE Operator Description ** Exponentiation (raise to the power) ~ + - Ccomplement, unary plus and minus (method names for the last two are +@ and -@) * / % // 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
  • 9. PYTHON - IF...ELIF...ELSE STATEMENT • The syntax of the if statement is: if expression: statement(s) Example: var1 = 100 if var1: print "1 - Got a true expression value" print var1 var2 = 0 if var2: print "2 - Got a true expression value" print var2 print "Good bye!" if expression: statement(s) else: statement(s)
  • 10. var1 = 100 if var1: print "1 - Got a true expression value" print var1 else: print "1 - Got a false expression value" print var1 var2 = 0 if var2: print "2 - Got a true expression value" print var2 else: print "2 - Got a false expression value" print var2 print "Good bye!"
  • 11. THE NESTED IF...ELIF...ELSE CONSTRUCT Example: var = 100 if var < 200: print "Expression value is less than 200" if var == 150: print "Which is 150" elif var == 100: print "Which is 100" elif var == 50: print "Which is 50" elif var < 50: print "Expression value is less than 50" else: print "Could not find true expression" print "Good bye!"
  • 12. SINGLE STATEMENT SUITES: If the suite of an if clause consists only of a single line, it may go on the same line as the header statement: if ( expression == 1 ) : print "Value of expression is 1"
  • 13. 5. PYTHON - WHILE LOOP STATEMENTS • The while loop is one of the looping constructs available in Python. The while loop continues until the expression becomes false. The expression has to be a logical expression and must return either a true or a false value The syntax of the while loop is: while expression: statement(s) Example: count = 0 while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!"
  • 14. THE INFINITE LOOPS: • You must use caution when using while loops because of the possibility that this condition never resolves to a false value. This results in a loop that never ends. Such a loop is called an infinite loop. • An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required. Following loop will continue till you enter CTRL+C : while var == 1 : # This constructs an infinite loop num = raw_input("Enter a number :") print "You entered: ", num print "Good bye!"
  • 15. SINGLE STATEMENT SUITES: • Similar to the if statement syntax, if your while clause consists only of a single statement, it may be placed on the same line as the while header. • Here is the syntax of a one-line while clause: while expression : statement
  • 16. 6. PYTHON - FOR LOOP STATEMENTS • The for loop in Python has the ability to iterate over the items of any sequence, such as a list or a string. • The syntax of the loop look is: for iterating_var in sequence: statements(s) Example: for letter in 'Python': # First Example print 'Current Letter :', letter fruits = ['banana', 'apple', 'mango'] for fruit in fruits: # Second Example print 'Current fruit :', fruit print "Good bye!"
  • 17. Iterating by Sequence Index: • An alternative way of iterating through each item is by index offset into the sequence itself: • Example: fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)): print 'Current fruit :', fruits[index] print "Good bye!"
  • 18. 7. PYTHON BREAK,CONTINUE AND PASS STATEMENTS The break Statement: • The break statement in Python terminates the current loop and resumes execution at the next statement, just like the traditional break found in C. Example: for letter in 'Python': # First Example if letter == 'h': break print 'Current Letter :', letter var = 10 # Second Example while var > 0: print 'Current variable value :', var var = var -1 if var == 5: break print "Good bye!"
  • 19. The continue Statement: • The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. Example: for letter in 'Python': # First Example if letter == 'h': continue print 'Current Letter :', letter var = 10 # Second Example while var > 0: var = var -1 if var == 5: continue print 'Current variable value :', var print "Good bye!"
  • 20. THE ELSE STATEMENT USED WITH LOOPS Python supports to have an else statement associated with a loop statements. • If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list. • If the else statement is used with a while loop, the else statement is executed when the condition becomes false. Example: for num in range(10,20): #to iterate between 10 to 20 for i in range(2,num): #to iterate on the factors of the number if num%i == 0: #to determine the first factor j=num/i #to calculate the second factor print '%d equals %d * %d' % (num,i,j) break #to move to the next number, the #first FOR else: # else part of the loop print num, 'is a prime number'
  • 21. THE PASS STATEMENT: • The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. • The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example): Example: for letter in 'Python': if letter == 'h': pass print 'This is pass block' print 'Current Letter :', letter print "Good bye!"