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
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)
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"
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]
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=' ')