SlideShare a Scribd company logo
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=' ')
Ad

More Related Content

Similar to Python programming language introduction unit (20)

C++ revision add on till now
C++ revision add on till nowC++ revision add on till now
C++ revision add on till now
AmAn Singh
 
Operators in Python Arithmetic Operators
Operators in Python Arithmetic OperatorsOperators in Python Arithmetic Operators
Operators in Python Arithmetic Operators
ramireddyobulakondar
 
Python Lec-6 Operatorguijjjjuugggggs.pptx
Python Lec-6 Operatorguijjjjuugggggs.pptxPython Lec-6 Operatorguijjjjuugggggs.pptx
Python Lec-6 Operatorguijjjjuugggggs.pptx
ks812227
 
OPERATORS OF C++
OPERATORS OF C++OPERATORS OF C++
OPERATORS OF C++
ANANT VYAS
 
Types of Operators in C
Types of Operators in CTypes of Operators in C
Types of Operators in C
Thesis Scientist Private Limited
 
Coper in C
Coper in CCoper in C
Coper in C
thirumalaikumar3
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001
Ralph Weber
 
SPL 6 | Operators in C
SPL 6 | Operators in CSPL 6 | Operators in C
SPL 6 | Operators in C
Mohammad Imam Hossain
 
Java basic operators
Java basic operatorsJava basic operators
Java basic operators
Emmanuel Alimpolos
 
Java basic operators
Java basic operatorsJava basic operators
Java basic operators
Emmanuel Alimpolos
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
Jasleen Kaur (Chandigarh University)
 
Grade XI - Computer science Data Handling in Python
Grade XI - Computer science Data Handling in PythonGrade XI - Computer science Data Handling in Python
Grade XI - Computer science Data Handling in Python
vidyuthno1
 
Operator 04 (js)
Operator 04 (js)Operator 04 (js)
Operator 04 (js)
AbhishekMondal42
 
Operators and it's type
Operators and it's type Operators and it's type
Operators and it's type
Asheesh kushwaha
 
btwggggggggggggggggggggggggggggggisop correct (1).pptx
btwggggggggggggggggggggggggggggggisop correct (1).pptxbtwggggggggggggggggggggggggggggggisop correct (1).pptx
btwggggggggggggggggggggggggggggggisop correct (1).pptx
Orin18
 
itft-Operators in java
itft-Operators in javaitft-Operators in java
itft-Operators in java
Atul Sehdev
 
Unit - 2 CAP.pptx
Unit - 2 CAP.pptxUnit - 2 CAP.pptx
Unit - 2 CAP.pptx
malekaanjum1
 
Python_Module_3_AFkkkkV_Operators-1.pptx
Python_Module_3_AFkkkkV_Operators-1.pptxPython_Module_3_AFkkkkV_Operators-1.pptx
Python_Module_3_AFkkkkV_Operators-1.pptx
tissot723
 
UNIT II_python Programming_aditya College
UNIT II_python Programming_aditya CollegeUNIT II_python Programming_aditya College
UNIT II_python Programming_aditya College
Ramanamurthy 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 la
LEOFAKE
 
C++ revision add on till now
C++ revision add on till nowC++ revision add on till now
C++ revision add on till now
AmAn Singh
 
Operators in Python Arithmetic Operators
Operators in Python Arithmetic OperatorsOperators in Python Arithmetic Operators
Operators in Python Arithmetic Operators
ramireddyobulakondar
 
Python Lec-6 Operatorguijjjjuugggggs.pptx
Python Lec-6 Operatorguijjjjuugggggs.pptxPython Lec-6 Operatorguijjjjuugggggs.pptx
Python Lec-6 Operatorguijjjjuugggggs.pptx
ks812227
 
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 001
Ralph Weber
 
Grade XI - Computer science Data Handling in Python
Grade XI - Computer science Data Handling in PythonGrade XI - Computer science Data Handling in Python
Grade XI - Computer science Data Handling in Python
vidyuthno1
 
btwggggggggggggggggggggggggggggggisop correct (1).pptx
btwggggggggggggggggggggggggggggggisop correct (1).pptxbtwggggggggggggggggggggggggggggggisop correct (1).pptx
btwggggggggggggggggggggggggggggggisop correct (1).pptx
Orin18
 
itft-Operators in java
itft-Operators in javaitft-Operators in java
itft-Operators in java
Atul Sehdev
 
Python_Module_3_AFkkkkV_Operators-1.pptx
Python_Module_3_AFkkkkV_Operators-1.pptxPython_Module_3_AFkkkkV_Operators-1.pptx
Python_Module_3_AFkkkkV_Operators-1.pptx
tissot723
 
UNIT II_python Programming_aditya College
UNIT II_python Programming_aditya CollegeUNIT II_python Programming_aditya College
UNIT II_python Programming_aditya College
Ramanamurthy 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 la
LEOFAKE
 

More from michaelaaron25322 (14)

computer-system-architecture-morris-mano-220720124304-fefd641d.ppt
computer-system-architecture-morris-mano-220720124304-fefd641d.pptcomputer-system-architecture-morris-mano-220720124304-fefd641d.ppt
computer-system-architecture-morris-mano-220720124304-fefd641d.ppt
michaelaaron25322
 
memory Organization in computer organization
memory Organization in computer organizationmemory Organization in computer organization
memory Organization in computer organization
michaelaaron25322
 
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 applications
michaelaaron25322
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unit
michaelaaron25322
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
michaelaaron25322
 
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
michaelaaron25322
 
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
michaelaaron25322
 
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
michaelaaron25322
 
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
 
mean stack
mean stackmean stack
mean stack
michaelaaron25322
 
karnaughmaprev1-130728135103-phpapp01.ppt
karnaughmaprev1-130728135103-phpapp01.pptkarnaughmaprev1-130728135103-phpapp01.ppt
karnaughmaprev1-130728135103-phpapp01.ppt
michaelaaron25322
 
booleanalgebra-140914001141-phpapp01 (1).ppt
booleanalgebra-140914001141-phpapp01 (1).pptbooleanalgebra-140914001141-phpapp01 (1).ppt
booleanalgebra-140914001141-phpapp01 (1).ppt
michaelaaron25322
 
mst_unit1.pptx
mst_unit1.pptxmst_unit1.pptx
mst_unit1.pptx
michaelaaron25322
 
computer-system-architecture-morris-mano-220720124304-fefd641d.ppt
computer-system-architecture-morris-mano-220720124304-fefd641d.pptcomputer-system-architecture-morris-mano-220720124304-fefd641d.ppt
computer-system-architecture-morris-mano-220720124304-fefd641d.ppt
michaelaaron25322
 
memory Organization in computer organization
memory Organization in computer organizationmemory Organization in computer organization
memory Organization in computer organization
michaelaaron25322
 
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 applications
michaelaaron25322
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unit
michaelaaron25322
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
michaelaaron25322
 
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
michaelaaron25322
 
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
michaelaaron25322
 
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
michaelaaron25322
 
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.ppt
michaelaaron25322
 
booleanalgebra-140914001141-phpapp01 (1).ppt
booleanalgebra-140914001141-phpapp01 (1).pptbooleanalgebra-140914001141-phpapp01 (1).ppt
booleanalgebra-140914001141-phpapp01 (1).ppt
michaelaaron25322
 
Ad

Recently uploaded (20)

Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
AI Publications
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
DED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedungDED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedung
nabilarizqifadhilah1
 
2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt
rakshaiya16
 
introduction technology technology tec.pptx
introduction technology technology tec.pptxintroduction technology technology tec.pptx
introduction technology technology tec.pptx
Iftikhar70
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
Working with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to ImplementationWorking with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to Implementation
Alabama Transportation Assistance Program
 
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Journal of Soft Computing in Civil Engineering
 
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
Reflections on Morality, Philosophy, and History
 
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic AlgorithmDesign Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Design Optimization of Reinforced Concrete Waffle Slab Using Genetic Algorithm
Journal of Soft Computing in Civil Engineering
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Construction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil EngineeringConstruction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil Engineering
Lavish Kashyap
 
Applications of Centroid in Structural Engineering
Applications of Centroid in Structural EngineeringApplications of Centroid in Structural Engineering
Applications of Centroid in Structural Engineering
suvrojyotihalder2006
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
Nanometer Metal-Organic-Framework Literature Comparison
Nanometer Metal-Organic-Framework  Literature ComparisonNanometer Metal-Organic-Framework  Literature Comparison
Nanometer Metal-Organic-Framework Literature Comparison
Chris Harding
 
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Automatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and BeyondAutomatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and Beyond
NU_I_TODALAB
 
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
AI Publications
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
DED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedungDED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedung
nabilarizqifadhilah1
 
2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt
rakshaiya16
 
introduction technology technology tec.pptx
introduction technology technology tec.pptxintroduction technology technology tec.pptx
introduction technology technology tec.pptx
Iftikhar70
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Construction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil EngineeringConstruction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil Engineering
Lavish Kashyap
 
Applications of Centroid in Structural Engineering
Applications of Centroid in Structural EngineeringApplications of Centroid in Structural Engineering
Applications of Centroid in Structural Engineering
suvrojyotihalder2006
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
Nanometer Metal-Organic-Framework Literature Comparison
Nanometer Metal-Organic-Framework  Literature ComparisonNanometer Metal-Organic-Framework  Literature Comparison
Nanometer Metal-Organic-Framework Literature Comparison
Chris Harding
 
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Automatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and BeyondAutomatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and Beyond
NU_I_TODALAB
 
Ad

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=' ')
  翻译: