SlideShare a Scribd company logo
1 of 40
Python Programming
UNIT II
• Types, Operators and Expressions: Types -
Integers, Strings, Booleans; Operators- Arithmetic
Operators, Comparison (Relational) Operators,
Assignment Operators, Logical Operators, Bitwise
Operators, Membership Operators, Identity
Operators
• Expressions and order of evaluations Control
Flow- if, if-elif-else, for, while, break, continue,
pass
Standard Data Types
The data stored in memory can be of many types. For example, a person's age is
stored as a numeric value and his or her address is stored as alphanumeric
characters. Python has various standard data types that are used to define the
operations possible on them and the storage method for each of them.
Python supports following standard data types:
• Numbers
• String
• Boolean
Numbers
Python number can be
• int
• float
• complex
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows for either pairs of single or double quotes. Subsets
of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0
in the beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator.
For example:
Program:
str ="WELCOME"
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 4th print str[2:] # Prints string
starting from 3rd character print str * 2 # Prints string two times
print str + "CSE" # Prints concatenated string
Exercise
• In this challenge, the user enters a string and a substring. You have
to print the number of times that the substring occurs in the given
string. String traversal will take place from left to right, not from
right to left.
• NOTE: String letters are case-sensitive.
• Input Format
• The first line of input contains the original string. The next line
contains the substring.
• Constraints
Each character in the string is an ascii character.
• Output Format
• Output the integer number indicating the total number of
occurrences of the substring in the original string.
• Sample Input
• ABCDCDC CDC Sample Output
• 2
Booleans are identified by True or False.
Example:
Program:
a = True
b = False
print(a)
print(b)
Output:
True False
Python Boolean
Python - Basic Operators
Python language supports following type of operators.
• Arithmetic Operators
• Relational(Comparision) Operators
• Logical Operators
• Assignment Operators
• Bitwise operators
• Membership operators
• Identity operstors
Python Arithmetic Operators:
Operator 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:
Operato
r
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:
Operat
or
Description Example
and Called Logical AND operator. If both the
operands are true then then condition
becomes true.
(a and b)
or Called Logical OR Operator. If any of the two
operands are non zero then then condition
becomes true.
(a or b)
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)
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 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
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).
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
Expression
• An expression is a combination of variables
constants and operators written according to
the syntax of Python language. In Python
every expression evaluates to a value i.e.,
every expression results in some value of a
certain type that can be assigned to a variable.
Some examples of Python expressions are
shown in the table given below.
Algebraic Expression Python Expression
a x b – c a * b – c
(m + n) (x + y) (m + n) * (x + y)
(ab / c) a * b / c
3x2 +2x + 1 3*x*x+2*x+1
(x / y) + c x / y + c
Evaluation of Expressions
• Expressions are evaluated using an assignment statement of the form
• Variable = expression
• Variable is any valid C variable name. When the statement is encountered, the
expression is evaluated first and then replaces the previous value of the variable
on the left hand side. All variables used in the expression must be assigned values
before evaluation is attempted.
• Example:
• a=10 b=22 c=34
• x=a*b+c
• y=a-b*c
• z=a+b+c*c-a
• print "x=",x
• print "y=",y
• print "z=",z
• Output:
• x= 254
• y= -738
• z= 1178
Control Flow statements
(Decision making statements)
• Decision making is anticipation of
conditions occurring while execution of
the program and specifying actions
taken according to the conditions.
• Decision structures evaluate multiple
expressions which produce TRUE or
FALSE as outcome. You need to
determine which action to take and
which statements to execute if outcome
is TRUE or FALSE otherwise.
Control Flow statements
(Decision making statements)
• Python programming language
provides following types of
decision making statements
I. Simple if
II. If-else
III. If-elif
Python Simple If
if statement consists of a boolean expression followed by
one or more statements.
Syntax:
If(condition):
statement1
……………..
statement n
Example:
x=10
if(x==10):
print(' x is 10')
print(”simple if”)
if (expression):
statement(s)
If –else
Syntax:
if(condition):
statement1
statement2
……………..
statement n
else:
statement1
statement2
……………..
statement n
Example:
x=10
if(x==10):
print(' x is 10')
else:
print(' x is not 10')
Exercise
Syntax:
if(condition):
statement1
……………..
statement n
elif(condition):
statement1
……………..
statement n
else:
statement1
……………..
statement n
Example:
x=10
if(x==10):
print(' x is 10')
elif(x==5):
print(' x is 5')
else:
print(“x is not 5
or 10”)
If-elif
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"
Loops
Looping statements are used for repitition of group of statements
Python - Loop Statements
Loop Type Description
while loop Repeats a statement or group of statements while a given
condition is TRUE. It tests the condition before executing
the loop body.
for loop Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
nested
loops
You can use one or more loop inside any another while, for
loop.
5. Python - while Loop Statements
• 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 (count,end=‘ ‘)
count = count + 1
print "Good bye!"
Output: 0 1 2 3 4 5 6 7 8
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(1):
print(“while loop”)
(Or)
while(True):
print(“while loop”)
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
We can also write multiple statements with semicolon
while expression : statement1;statement2;….stmtn
range
“range” creates a list of numbers in a specified range
range([start,] stop[, step]) -> list of integers
When step is given, it specifies the increment (or
decrement).
*range(5) means [0, 1, 2, 3, 4]
*range(5, 10) means[5, 6, 7, 8, 9]
* range(0, 10, 2) means[0, 2, 4, 6, 8]
Loops
Looping statements are used for repitition of group of statements
for loop
Example1: (prints upto n-1)
n=5
for i in range(n):
print(i)
Example2:
for i in range(1,4):
print(i)
Example3:
for i in range(1,10,2):
print(i)
Example 4:
for i in range(50,10,-3):
print(i)
Syntax:
for i in range(start,end,step)
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!"
Exercises
Programs for following outputs?
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 2:
for i in range(1,6)':
if (i == 3):
break
print (i)
Output:1 2
Example 1:
for letter in 'Python':
if letter == 'h':
break
print (letter)
Output: pyt
• The continue statement in Python returns the control to the beginning of
the for/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 2:
for i in range(1,6)':
if (i == 3):
continue
print (i)
Output:1 2 4 5
Example 1:
for letter in 'Python':
if letter == 'h':
continue
print (letter)
Output: pyton
Continue Statement:
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 2:
for i in range(1,6)':
if (i == 3):
pass
print (i)
Output:1 2 3 4 5
Example 1:
for letter in 'Python':
if letter == 'h':
pass
print (letter)
Output: python
break,continue,pass
n=10
for i in range(n):
print(i,end=' ')
if(i==5):
break
n=10
for i in range(n):
if(i==5):
continue
print(i,end=' ')
n=10
for i in range(n):
if(i==5):
pass
print(i,end=' ')

More Related Content

Similar to Python programming language introduction unit

OPERATORS OF C++
OPERATORS OF C++OPERATORS OF C++
OPERATORS OF C++ANANT VYAS
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001Ralph Weber
 
itft-Operators in java
itft-Operators in javaitft-Operators in java
itft-Operators in javaAtul Sehdev
 
UNIT II_python Programming_aditya College
UNIT II_python Programming_aditya CollegeUNIT II_python Programming_aditya College
UNIT II_python Programming_aditya CollegeRamanamurthy Banda
 
data type.pptxddddswwyertr hai na ki extend kr de la
data type.pptxddddswwyertr hai na ki extend kr de ladata type.pptxddddswwyertr hai na ki extend kr de la
data type.pptxddddswwyertr hai na ki extend kr de laLEOFAKE
 
modul-python-all.pptx
modul-python-all.pptxmodul-python-all.pptx
modul-python-all.pptxYusuf Ayuba
 
4_A1208223655_21789_2_2018_04. Operators.ppt
4_A1208223655_21789_2_2018_04. Operators.ppt4_A1208223655_21789_2_2018_04. Operators.ppt
4_A1208223655_21789_2_2018_04. Operators.pptRithwikRanjan
 
Python Training in Bangalore | Python Operators | Learnbay.in
Python Training in Bangalore | Python Operators | Learnbay.inPython Training in Bangalore | Python Operators | Learnbay.in
Python Training in Bangalore | Python Operators | Learnbay.inLearnbayin
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++bajiajugal
 
Operators in java presentation
Operators in java presentationOperators in java presentation
Operators in java presentationkunal kishore
 
Python Programming | JNTUK | UNIT 1 | Lecture 5
Python Programming | JNTUK | UNIT 1 | Lecture 5Python Programming | JNTUK | UNIT 1 | Lecture 5
Python Programming | JNTUK | UNIT 1 | Lecture 5FabMinds
 

Similar to Python programming language introduction unit (20)

OPERATORS OF C++
OPERATORS OF C++OPERATORS OF C++
OPERATORS OF C++
 
Types of Operators in C
Types of Operators in CTypes of Operators in C
Types of Operators in C
 
Coper in C
Coper in CCoper in C
Coper in C
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001
 
SPL 6 | Operators in C
SPL 6 | Operators in CSPL 6 | Operators in C
SPL 6 | Operators in C
 
Java basic operators
Java basic operatorsJava basic operators
Java basic operators
 
Java basic operators
Java basic operatorsJava basic operators
Java basic operators
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
 
Operator 04 (js)
Operator 04 (js)Operator 04 (js)
Operator 04 (js)
 
Operators and it's type
Operators and it's type Operators and it's type
Operators and it's type
 
itft-Operators in java
itft-Operators in javaitft-Operators in java
itft-Operators in java
 
Unit - 2 CAP.pptx
Unit - 2 CAP.pptxUnit - 2 CAP.pptx
Unit - 2 CAP.pptx
 
UNIT II_python Programming_aditya College
UNIT II_python Programming_aditya CollegeUNIT II_python Programming_aditya College
UNIT II_python Programming_aditya College
 
data type.pptxddddswwyertr hai na ki extend kr de la
data type.pptxddddswwyertr hai na ki extend kr de ladata type.pptxddddswwyertr hai na ki extend kr de la
data type.pptxddddswwyertr hai na ki extend kr de la
 
modul-python-all.pptx
modul-python-all.pptxmodul-python-all.pptx
modul-python-all.pptx
 
4_A1208223655_21789_2_2018_04. Operators.ppt
4_A1208223655_21789_2_2018_04. Operators.ppt4_A1208223655_21789_2_2018_04. Operators.ppt
4_A1208223655_21789_2_2018_04. Operators.ppt
 
Python Training in Bangalore | Python Operators | Learnbay.in
Python Training in Bangalore | Python Operators | Learnbay.inPython Training in Bangalore | Python Operators | Learnbay.in
Python Training in Bangalore | Python Operators | Learnbay.in
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
 
Operators in java presentation
Operators in java presentationOperators in java presentation
Operators in java presentation
 
Python Programming | JNTUK | UNIT 1 | Lecture 5
Python Programming | JNTUK | UNIT 1 | Lecture 5Python Programming | JNTUK | UNIT 1 | Lecture 5
Python Programming | JNTUK | UNIT 1 | Lecture 5
 

More from michaelaaron25322

memory Organization in computer organization
memory Organization in computer organizationmemory Organization in computer organization
memory Organization in computer organizationmichaelaaron25322
 
EST is a software architectural style that was created to guide the design an...
EST is a software architectural style that was created to guide the design an...EST is a software architectural style that was created to guide the design an...
EST is a software architectural style that was created to guide the design an...michaelaaron25322
 
Spring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsSpring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsmichaelaaron25322
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unitmichaelaaron25322
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java scriptmichaelaaron25322
 
Unit-II AES Algorithm which is used machine learning
Unit-II AES Algorithm which is used machine learningUnit-II AES Algorithm which is used machine learning
Unit-II AES Algorithm which is used machine learningmichaelaaron25322
 
UNIT2_NaiveBayes algorithms used in machine learning
UNIT2_NaiveBayes algorithms used in machine learningUNIT2_NaiveBayes algorithms used in machine learning
UNIT2_NaiveBayes algorithms used in machine learningmichaelaaron25322
 
Spring Data JPA USE FOR CREATING DATA JPA
Spring Data JPA USE FOR CREATING DATA  JPASpring Data JPA USE FOR CREATING DATA  JPA
Spring Data JPA USE FOR CREATING DATA JPAmichaelaaron25322
 
Computer organization algorithms like addition and subtraction and multiplica...
Computer organization algorithms like addition and subtraction and multiplica...Computer organization algorithms like addition and subtraction and multiplica...
Computer organization algorithms like addition and subtraction and multiplica...michaelaaron25322
 
karnaughmaprev1-130728135103-phpapp01.ppt
karnaughmaprev1-130728135103-phpapp01.pptkarnaughmaprev1-130728135103-phpapp01.ppt
karnaughmaprev1-130728135103-phpapp01.pptmichaelaaron25322
 
booleanalgebra-140914001141-phpapp01 (1).ppt
booleanalgebra-140914001141-phpapp01 (1).pptbooleanalgebra-140914001141-phpapp01 (1).ppt
booleanalgebra-140914001141-phpapp01 (1).pptmichaelaaron25322
 

More from michaelaaron25322 (13)

memory Organization in computer organization
memory Organization in computer organizationmemory Organization in computer organization
memory Organization in computer organization
 
EST is a software architectural style that was created to guide the design an...
EST is a software architectural style that was created to guide the design an...EST is a software architectural style that was created to guide the design an...
EST is a software architectural style that was created to guide the design an...
 
Spring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsSpring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applications
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unit
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
 
Unit-II AES Algorithm which is used machine learning
Unit-II AES Algorithm which is used machine learningUnit-II AES Algorithm which is used machine learning
Unit-II AES Algorithm which is used machine learning
 
UNIT2_NaiveBayes algorithms used in machine learning
UNIT2_NaiveBayes algorithms used in machine learningUNIT2_NaiveBayes algorithms used in machine learning
UNIT2_NaiveBayes algorithms used in machine learning
 
Spring Data JPA USE FOR CREATING DATA JPA
Spring Data JPA USE FOR CREATING DATA  JPASpring Data JPA USE FOR CREATING DATA  JPA
Spring Data JPA USE FOR CREATING DATA JPA
 
Computer organization algorithms like addition and subtraction and multiplica...
Computer organization algorithms like addition and subtraction and multiplica...Computer organization algorithms like addition and subtraction and multiplica...
Computer organization algorithms like addition and subtraction and multiplica...
 
mean stack
mean stackmean stack
mean stack
 
karnaughmaprev1-130728135103-phpapp01.ppt
karnaughmaprev1-130728135103-phpapp01.pptkarnaughmaprev1-130728135103-phpapp01.ppt
karnaughmaprev1-130728135103-phpapp01.ppt
 
booleanalgebra-140914001141-phpapp01 (1).ppt
booleanalgebra-140914001141-phpapp01 (1).pptbooleanalgebra-140914001141-phpapp01 (1).ppt
booleanalgebra-140914001141-phpapp01 (1).ppt
 
mst_unit1.pptx
mst_unit1.pptxmst_unit1.pptx
mst_unit1.pptx
 

Recently uploaded

KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Christo Ananth
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spaintimesproduction05
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLManishPatel169454
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 

Recently uploaded (20)

KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spain
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 

Python programming language introduction unit

  • 1. Python Programming UNIT II • Types, Operators and Expressions: Types - Integers, Strings, Booleans; Operators- Arithmetic Operators, Comparison (Relational) Operators, Assignment Operators, Logical Operators, Bitwise Operators, Membership Operators, Identity Operators • Expressions and order of evaluations Control Flow- if, if-elif-else, for, while, break, continue, pass
  • 2. Standard Data Types The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them. Python supports following standard data types: • Numbers • String • Boolean
  • 3. Numbers Python number can be • int • float • complex
  • 4. Python Strings Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end. The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example: Program: str ="WELCOME" print str # Prints complete string print str[0] # Prints first character of the string print str[2:5] # Prints characters starting from 3rd to 4th print str[2:] # Prints string starting from 3rd character print str * 2 # Prints string two times print str + "CSE" # Prints concatenated string
  • 5. Exercise • In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left. • NOTE: String letters are case-sensitive. • Input Format • The first line of input contains the original string. The next line contains the substring. • Constraints Each character in the string is an ascii character. • Output Format • Output the integer number indicating the total number of occurrences of the substring in the original string. • Sample Input • ABCDCDC CDC Sample Output • 2
  • 6. Booleans are identified by True or False. Example: Program: a = True b = False print(a) print(b) Output: True False Python Boolean
  • 7. Python - Basic Operators Python language supports following type of operators. • Arithmetic Operators • Relational(Comparision) Operators • Logical Operators • Assignment Operators • Bitwise operators • Membership operators • Identity operstors
  • 8. Python Arithmetic Operators: Operator 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
  • 9. Python Comparison Operators: Operato r 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.
  • 10. 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
  • 11. 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
  • 12. Python Logical Operators: Operat or Description Example and Called Logical AND operator. If both the operands are true then then condition becomes true. (a and b) or Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. (a or b) 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)
  • 13. 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.
  • 14. 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 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).
  • 15. 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
  • 16. Expression • An expression is a combination of variables constants and operators written according to the syntax of Python language. In Python every expression evaluates to a value i.e., every expression results in some value of a certain type that can be assigned to a variable. Some examples of Python expressions are shown in the table given below. Algebraic Expression Python Expression a x b – c a * b – c (m + n) (x + y) (m + n) * (x + y) (ab / c) a * b / c 3x2 +2x + 1 3*x*x+2*x+1 (x / y) + c x / y + c
  • 17. Evaluation of Expressions • Expressions are evaluated using an assignment statement of the form • Variable = expression • Variable is any valid C variable name. When the statement is encountered, the expression is evaluated first and then replaces the previous value of the variable on the left hand side. All variables used in the expression must be assigned values before evaluation is attempted. • Example: • a=10 b=22 c=34 • x=a*b+c • y=a-b*c • z=a+b+c*c-a • print "x=",x • print "y=",y • print "z=",z • Output: • x= 254 • y= -738 • z= 1178
  • 18. Control Flow statements (Decision making statements) • Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions. • Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise.
  • 19. Control Flow statements (Decision making statements) • Python programming language provides following types of decision making statements I. Simple if II. If-else III. If-elif
  • 20. Python Simple If if statement consists of a boolean expression followed by one or more statements. Syntax: If(condition): statement1 …………….. statement n Example: x=10 if(x==10): print(' x is 10') print(”simple if”) if (expression): statement(s)
  • 23. Syntax: if(condition): statement1 …………….. statement n elif(condition): statement1 …………….. statement n else: statement1 …………….. statement n Example: x=10 if(x==10): print(' x is 10') elif(x==5): print(' x is 5') else: print(“x is not 5 or 10”) If-elif
  • 24. 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!"
  • 25. 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"
  • 26. Loops Looping statements are used for repitition of group of statements
  • 27. Python - Loop Statements Loop Type Description while loop Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body. for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. nested loops You can use one or more loop inside any another while, for loop.
  • 28. 5. Python - while Loop Statements • 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 (count,end=‘ ‘) count = count + 1 print "Good bye!" Output: 0 1 2 3 4 5 6 7 8
  • 29. 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(1): print(“while loop”) (Or) while(True): print(“while loop”)
  • 30. 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 We can also write multiple statements with semicolon while expression : statement1;statement2;….stmtn
  • 31. range “range” creates a list of numbers in a specified range range([start,] stop[, step]) -> list of integers When step is given, it specifies the increment (or decrement). *range(5) means [0, 1, 2, 3, 4] *range(5, 10) means[5, 6, 7, 8, 9] * range(0, 10, 2) means[0, 2, 4, 6, 8]
  • 32. Loops Looping statements are used for repitition of group of statements
  • 33. for loop Example1: (prints upto n-1) n=5 for i in range(n): print(i) Example2: for i in range(1,4): print(i) Example3: for i in range(1,10,2): print(i) Example 4: for i in range(50,10,-3): print(i) Syntax: for i in range(start,end,step)
  • 34. 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!"
  • 35. 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!"
  • 37. 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 2: for i in range(1,6)': if (i == 3): break print (i) Output:1 2 Example 1: for letter in 'Python': if letter == 'h': break print (letter) Output: pyt
  • 38. • The continue statement in Python returns the control to the beginning of the for/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 2: for i in range(1,6)': if (i == 3): continue print (i) Output:1 2 4 5 Example 1: for letter in 'Python': if letter == 'h': continue print (letter) Output: pyton Continue Statement:
  • 39. 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 2: for i in range(1,6)': if (i == 3): pass print (i) Output:1 2 3 4 5 Example 1: for letter in 'Python': if letter == 'h': pass print (letter) Output: python
  • 40. break,continue,pass n=10 for i in range(n): print(i,end=' ') if(i==5): break n=10 for i in range(n): if(i==5): continue print(i,end=' ') n=10 for i in range(n): if(i==5): pass print(i,end=' ')