Python - 1 Year - Unit-2-1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 118

PYTHON PROGRAMMING

by C. RAJEEV
C. RAJEEVAssistant Professor,
Assist. Prof.Department of CSE,
Dept. of. CSE,
MRECW
MRECW.
UNIT II

Data Types in Python, Mutable Vs Immutable, Fundamental Data Types: int, float,

complex, bool, str, Number Data Types: Decimal, Binary, Octal, Hexa Decimal & Number

Conversions, Inbuilt Functions in Python, Data Type Conversions, Priorities of Data Types

in Python, Python Operators, Arithmetic Operators, Comparison (Relational) Operators,

Assignment Operators, Logical Operators, Bitwise Operators, Membership Operators,

Identity Operators, Slicing & Indexing, Forward Direction Slicing with +ve Step, Backward

Direction Slicing with -ve Step, Decision Making Statements, if Statement, if-else

Statement, elif Statement, Looping Statements, Why we use Loops in python?,

Advantages of Loops for Loop, Nested for Loop, Using else Statement with for Loop,

while Loop, Infinite while Loop, Using else with Python while Loop, Conditional

Statements, break Statement, continue Statement, Pass Statement


1. Data Types in Python
2. Mutable Vs Immutable
1. mutable : means that we can change their content without changing their
identity
2. Immutable: no provision to change there assigned value for an index.

https://www.freecodecamp.org/news/
mutable-vs-immutable-objects-python/
3. Fundamental datatypes:
1. Numeric datatypes:
Number or numeric stores numeric values. The integer, float, and complex values
belong to a Python Numbers data-type.
Python supports three types of numeric data.
1. int
2. float
3. complex

i)int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python
has no restriction on the length of an integer. Its value belongs to int
Ex: >>> a=5 >>> a=12345656453345
>>> a >>> a
5 12345656453345
>>> type(a) >>> type(a)
<class 'int'> <class 'int'>
In C,datatypes
ii) Float -
 Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc.
 It is accurate upto 15 decimal points.
Ex:

>>> b=20.55 >>> b=12.987654321234567

>>> b >>> b

20.55 12.987654321234567

>>> type(b) >>> type(b)

<class 'float'> <class 'float'>


iii). Complex Numbers:
Combining a real number with an imaginary number forms a single entity known
as a complex number.


A complex number is any ordered pair of floating point real numbers (x, y)

denoted by x + yj where x is the real part and y is the imaginary part of a complex
number.

complex numbers are used in everyday math, engineering, electronics, etc.


Ex:
64.375+1j 4.23-8.5j 0.23-8.55j 1.23e-045+6.7e+089j
6.23+1.5j -1.23-875J 0+1j 9.80665-8.31441J -.0224+0j

>>> 2+3j
(2+3j)
>>> type(2+3j)
<class 'complex'>
Real Numbers include:
Whole Numbers (like 0, 1, 2, 3, 4, etc)
Rational Numbers (like 3/4, 0.125, 0.333..., 1.1, etc )
Irrational Numbers (like π, √2, etc )

i × i = −1
Complex Number Built-in Attributes:
Complex numbers are one example of objects with data attributes.

The data attributes are the real and imaginary components of the complex
number object they belong to.

 Complex numbers also have a method attribute that can be invoked, returning
the complex conjugate of the object.

Attribute Description
num.real ------------------------------Real component of complex number num
num.imag -----------------------------Imaginary component of complex number num
num.conjugate()--------------------- Returns complex conjugate of num
Ex:

>>> aComplex = -8.333-1.47j

>>> aComplex

(-8.333-1.47j)

>>> aComplex.real

-8.333

>>> aComplex.imag

-1.47

>>> aComplex.conjugate()

(-8.333-1.47j)
2. Boolean
Boolean type provides two built-in values, True and False. These values are used
to determine the given statement true or false.
It denotes by the class bool.
True can be represented by any non-zero value or 'T'
whereas false can be represented by the 0 or 'F‘.

Ex: # Python program to check the boolean type


>>> type(True)
<class 'bool'>

>>> type(False)
<class 'bool'>

>>> type(true)
NameError: name 'true' is not defined
3. Strings:
A string object is one of the sequence data types in Python.
It is an immutable sequence of Unicode characters. Strings are objects of
Python's built-in class 'str'.
 String literals are written by enclosing a sequence of characters in single quotes
('hello'), double quotes ("hello") or triple quotes ('''hello''' or """hello""“)

creating a strings:
EX:
>>> str1='hello'
>>> str1 NOTE: python doesn't support the character data
'hello' type instead a single character written as 'p' is
>>> str2="hello"
>>> str2 treated as the string of length 1.
'hello'
>>> str3='''hello'''
>>> str3
'hello'
>>> str4="""hello"""
>>> str4
'hello'
How to Access Values (Characters and Substrings) in Strings:
We can access individual characters using indexing and a range of characters
using slicing.
Index starts from 0 and ends with length -1. if we try to access a character out of
index range then interpreter will raise an IndexError.
The index must be an integer if we try to access the data with non-integer indexes
values then interpreter raises an TypeError.
By using the slice operator [ ] we can access the individual characters of the string.
However, we can use the : (colon) operator to access the substring.(positive indexing)
Python allows negative indexing for its sequence. The index of -1 refers to
the last item, -2 refers to last 2nd item. This is called backward indexing
h e l l o
-5 -4 -3 -2 -1
Str=‘hello’
>>> str[-1]
'o'
>>> str[-3]
'l‘
>>> str[:-3]
'he'
>>> str[-3:]
'llo‘
>>> str[-3:-2]
'l‘
>>> str[-2:-2] # return empty strings.
‘'
>>> str[2:2] # return empty strings.
‘'
How to Remove Characters and Strings:
strings are immutable, so you cannot remove individual characters from an existing
string. But we can do !! If you want to remove one letter from "Hello World!“ i.e., l

S=‘hello world’
>>> s1=s[:3] + s[4:]
>>> s1
‘helo world!‘

To clear or remove a string, you assign an empty string or use the del statement

>>> str='hello'
>>> str=''
>>> str
‘'
>>> s='hello'
>>> del s
>>> s
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
s
NameError: name 's' is not defined
String Operators:
Arithmetic operators don't operate on strings. However, there are special operators for string
processing.
Python Raw String (r or R operator)
Python raw string is created by prefixing a string literal with ‘r’ or ‘R’.
Python raw string treats backslash (\) as a literal character.
This is useful when we want to have a string that contains backslash
and don’t want it to be treated as an escape character.
Ex:

>>> s='hi' >>> s=r'hi\nhello'


>>> print(s)
>>> s1='hello'
hi\nhello
>>> s='hi\nhello'
>>> s=R'hi\nhello'
>>> print(s)
>>> print(s)
hi hi\nhello
hello
String built in functions:
1.
Capitalize()
2.Title() 16. Cmp()
3.Islower() 17. Zip()
4.Isupper() 18. Enumerate()
5.Lower() 19. Max()
6.Len() 20. Min()
7.Count() 21. isalnum()
8.Find() 22. Join()
9.
Split()
10.Strip()
11.lstrip()
12.rstrip()
13.Swapcase()
14.Reversed()
15.Replace()
1. capitalize()
In Python, the capitalize() method converts first character of a string to uppercase letter
and lowercases all other characters.
The syntax of capitalize() is:
string.capitalize()
Old String: python is AWesome
Capitalized String: Python is awesome

2. title():
The title() method returns a string with first letter of each word capitalized; a title cased
string.
The syntax of title() is:
str.title()
Ex:
Output:
text = 'My favorite number is 25.‘
My Favorite Number Is 25.
print(text.title())
234 K3L2 *43 Fun
text = '234 k3l2 *43 fun‘
3. islower()
The islower() method returns True if all alphabets in a string are lowercase
alphabets. If the string contains at least one uppercase alphabet, it returns False.
The syntax of islower() is:
string.islower( )

4. isupper()
The string isupper() method returns whether or not all characters in a string are
uppercased or not.
The syntax of islower() is:
string.isupper()

5. lower()
The string lower() method converts all uppercase characters in a string into
lowercase characters and returns it.
The syntax of lower() method is:
string.lower()

6. upper()
The string upper() method converts all lowercase characters in a string into
uppercase characters and returns it.
The syntax of upper() method is:
string.upper()
7. len() Method
the len() method returns the length of the string.
syntax for len() method −
len( str )

8. count()
The string count() method returns the number of occurrences of a substring in the given
string.
syntax of count() method is:
string.count(substring, start=..., end=...)
Ex:
string = "Python is awesome, isn't it?“
substring = "is“
count = string.count(substring)
print("The count is:", count)
o/p: The count is: 2
9. find() method
The find() method returns the index of first occurrence of the substring (if found). If not
found, it returns -1.
Syntax:
str.find(str, beg = 0 end = len(string))
str − This specifies the string to be searched.
beg − This is the starting index, by default its 0.
end − This is the ending index, by default its equal to the lenght of the string.
Ex:
str1 = "this is string example....wow!!!“
str2 = "exam";
print (str1.find(str2))
o/p: 15
10. Cmp():
cmp() method compares two integers and returns -1, 0, 1 according to comparison.
Ex:

# when a<b # when a = b # when a>b


a=1 a=2 a=3
b=2 b=2 b=2
print(cmp(a, b)) print(cmp(a, b)) print(cmp(a, b))

Output: Output: Output:


-1 0 0

11. max() and min()


>>> str2 = 'lmn'
>>> str3 = 'xyz'
>>> max(str2)
'n'
>>> min(str3)
'x'
12. Zip():
zip() is to map the similar index of multiple containers so that they can be used
just using as single entity.
Ex:
a = ("John", "Charles", "Mike")
b = ("Jenny", "Christy", "Monica“)
x = zip(a, b)
print(tuple(x))
Output:
('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))

13. enumerate():
The enumerate() method adds counter to an iterable and returns it (the enumerate
object).
Syntax: enumerate(iterable, start=0)
Ex: s=['mrecw','4th year','cse']
>>> print(list(enumerate(s,0)))
14. isalnum():
isalnum() function checks whether all the characters in a given string is
alphanumeric or not.
Ex:
>>> string = "abc123"
>>> print(string.isalnum())
True
>>> string = "abc%123"
>>> print(string.isalnum())
False
15, Join()

The join() method takes all items in an iterable and joins them into one string.
i.e., Join all items in a tuple into a string.

Ex:
>>> a='x‘

}
>>> b='y'
>>> c='z'
>>> st=''.join([a,b,c]) String packing
>>> print(st)
xyz

String unpacking:
extracting all characters of string into different variables automatically

>>> str="python"
>>> a,b,c,d,e,f=str
>>> print(a)
p
>>> type(a)
<class 'str'>
16. split():
The split() method breaks up a string at the specified separator and returns a list of
strings.
Ex:
str="python is powerful programming language"
a=str.split()
print(a)
Output:
['python', 'is', 'powerful', 'programming', 'language']
17. strip():
Remove spaces at the beginning and at the end of the string:
Ex:
str=" wow!!amazing,python is powerful programming language "
a=str.strip()
print(a)
OUTPUT:
wow!!amazing,python is powerful programming language
18. lstrip:
Remove spaces to the left of the string.
Ex:
str=" wow!! amazing, python is powerful programming language "
a=str.lstrip()
print(a)
Output:
wow!!amazing, python is powerful programming language

19. rstrip:
Remove spaces to the end of the string.
Ex:
str=" wow!! amazing, python is powerful programming language "
a=str.rstrip()
print(a)
Output:
wow!!amazing, python is powerful programming language
20. swapcase():
Make the lower case letters upper case and the upper case letters lower case
Ex:
str="Hello python, Iam String"
s=str.swapcase()
print(s)
Output:
hELLO PYTHON, iAM sTRING
21. reversed()
The reversed() function returns the reversed iterator of the given sequence.
This function returns an iterator that accesses the given sequence in the reverse
order.
Ex:
str="Hello python, Iam String"
s=list(reversed(str))
print(s)
Output:
22. replace():
This method returns a copy of the string where all occurrences of a substring is
replaced with another substring.
Ex:
str="hello this is python"
s=str.replace('python','string')
print(s)
Output:
hello this is string
Decimal, Binary, Octal, Hexadecimal number:
The decimal system is the most widely used number system. However, computers
only understand binary.

Binary, octal and hexadecimal number systems are closely related, and we may
require to convert decimal into these systems.

The decimal system is base 10 (ten symbols, 0-9, are used to represent a number)
and similarly, binary is base 2 (0,1), octal is base 8(0 to 7) and hexadecimal is base
16(0-F).

In python, a number with the prefix 0b is considered binary, 0o is considered octal
and 0x as hexadecimal.

For example:
60 = 0b11100 = 0o74 = 0x3c
4.Data Type Conversion in Python:
1.int(a,base) : This function converts any data type to integer. ‘Base’ specifies
the base in which string is if data type is string.
Ex:
s = "10010"
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)
c = int(s)
print ("After converting to integer base 10 : ", end="")
print (c)

o/p: After converting to integer base 2 : 18


After converting to integer base 10 : 10010
2. float() :
This function is used to convert any data type to a floating point number.
Ex:
s=2
e = float(s)
print ("After converting to float : ", end="")
print (e)
o/p:
. After converting to float : 2.0
3. ord() : This function is used to convert a character to integer.
Ex:
s = ‘A'
c = ord(s)
print ("After converting character to integer : ",end="")
print (c)
o/p: After converting character to integer : 65
4. hex() : This function is to convert integer to hexadecimal string.
Ex:
c = hex(56)
print ("After converting 56 to hexadecimal string : ",end="")
print (c)

o/p:
After converting 56 to hexadecimal string : 0x38

5. oct() : This function is to convert integer to octal string.


Ex:
c = oct(56)
print ("After converting 56 to octal string : ",end="")
print (c)
o/p:
After converting 56 to octal string : 0o70
6. str() : Used to convert specified value into a string.
Ex: # printing integer converting to string
c = str(1)
print ("After converting integer to string : ",end="")
print (c)
Output:
After converting specified value to string : ‘1’

7. complex(real,imag) : : This function converts real numbers to complex(real,imag)


number.
Ex:
c = complex(1,2)
print ("After converting integer to complex number : ",end="")
print (c)
Output:
After converting integer to complex number : (1+2j)
8. chr(number) :
This function converts number to its corresponding ASCII character.
Ex:
# Convert ASCII value to characters
a = chr(76)
b = chr(77)
print(a)
print(b)
o/p:
L
M
5. Inbuilt Functions in Python:
1.type():

 To check the data type of specific variable we can use type( )


function.

>>> a,b,c=10, 20.5, 'python'


>>> a,b,c
(10, 20.5, 'python')
>>> type(a)
<class 'int'>
>>> type(b)
<class 'float'>
>>> type(c)
<class 'str‘>
>>> d=[1,2,3] .
>>> e=(1,2,3) >>> import math
>>> f={'a':1,'b':2,'c':3} >>> type(math)
>>> g={1,2,3} <class 'module'>
>>> h=frozenset([1,2,3]) >>> type(type(42))
>>> type(d) <class 'type'>
<class 'list'>
>>> type(e)
Note: the type of all type objects is type
<class 'tuple'>
>>> type(f)
<class 'dict'>
>>> type(g)
<class 'set'>
>>> type(h)
<class 'frozenset'>
2. id( ):
The id() function returns identity (unique integer) of an object.
All objects in Python has its own unique id.
The id is assigned to the object when it is created.
This is an integer that is unique for the given object and remains constant during its
lifetime.
id() function takes a single parameter object.
syntax:
id(object)
Output:
Ex:
id of 5 = 1480025328
print('id of 5 =',id(5))
id of a = 1480025328
a=5
id of b = 1480025328
print('id of a =',id(a))
id of c = 36700352
b=a
print('id of b =',id(b)) Here , integer 5 has a unique id. The id of the integer 5

c = 5.0 remains constant during the lifetime. Similar is the case for
float 5.0 and other objects.
3. print( ):
Print( ) is also called as OUTPUT Statement:
In some languages, such as C, displaying to the screen is accomplished with a
function, e.g., printf(),

while with Python and most interpreted and scripting languages, print is a
statement.
 Many shell script languages use an echo command for program output.
Example:
>>> myString = 'Hello World!'
>>> print (myString)
Hello World!
>>> myString
'Hello World!‘
In python2, print statement, paired with the string format operator ( % ), supports
string substitution, much like the printf() function in C:
Ex:

>>> print "%s is number %d!" % ("Python", 1)


Python is number 1!
>>> p,q=4,3
>>> print "addition of %d and %d is %d" %(p,q,p+q)
addition of 4 and 3 is 7
In python3, The print() function to display output prints the specified message to
the screen, or other standard output device.
1.print( ) function without argument:
Just it prints new line character
Ex: >>> print()
>>>
2. prints the specified message to the screen:
>>> print("hello world!")
hello world!
>>> print("hello\n world!") #you can use escape character also
hello
world!
>>> print(10*"hello") # you can use reptation operator also
hellohellohellohellohellohellohellohellohellohello
>>> print("hello" + "world!") #you can use +operator for concatenation
helloworld!
3. print() with variable number of arguments:
>>> a,b,c=1,2,3
>>> print("values of a,b,c are:",a,b,c)
values of a,b,c are: 1 2 3
 By default, output values are separated by space.

If we want to specify separated by using “sep” attribute.


Ex:
>>> a,b,c=10,20,30
>>> print("values of a,b,c are with seperated:",a,b,c,sep=',')
values of a,b,c are with seperated: 10,20,30

>>> print("values of a,b,c are with seperated:",a,b,c,sep=':')


values of a,b,c are with seperated: 10:20:30
4. print() with end attribute:
 if we want output in the same line with space. Eventhough if we write in multiple
statements

print("hello",end=‘ '); print("python",end=‘ ‘); print("programming“)


o/p:
hello python programming

print("hello"); print("python");print("programming

o/p:
hello
python
Programming

Note: The default value for end attribute is \n ,which is nothing but new line character
5.print(object) statement:
We can pass any object (list,tuple,set..) as an argument to the print() statement.
Ex:
>>> list=[1,2,3,4]
>>> tuple=(10,20,30,40)
>>> print(list)
[1, 2, 3, 4]
>>> print(tuple)
(10, 20, 30, 40)
>>>
6.print(string, varaible list):
We can use print() statement with string and any number of arguments
Ex:
>>>s="python"
>>> s1="Guido van Rossum"
>>> s2=1989
>>> print("Hello",s,"was developed by",s1,"in the year",s2)
Output:
Hello python was developed by Guido van Rossum in the year 1989
7. print(formatted string)
%d--------------------int
%f--------------------float
%s--------------------string

Ex:
>>> a="MRECW"
>>> b=2020
>>> print("hello %s.....year %d”%(a,b))
Output:
hello MRECW.....year 2020
8. print() with replacement operator:
>>> s="python"
>>> s1="Guido van Rossum"
>>> s2=1989
>>> print("Hello {0} was developed by {1} in the year {2}".format(s,s1,s2))

Output:
Hello python was developed by Guido van Rossum in the year 1989
4. input( ):
 input( ) is also called as input statement.
This function is used to read the input from the keyboard.
Here Python2 provides us with two inbuilt functions to read the input from the
keyboard.
1. raw_input ( prompt )
2. input ( prompt )

1. raw_input ( ):
This function takes exactly what is typed from the keyboard, convert it to string
and then return it to the variable in which we want to store.
Ex: >>> a=raw_input("Enter your age:")
>>> key=raw_input("Enter your name") Enter your age:26
Enter your name RAJEEV >>> type(a)
>>> type(key) <type 'str'>
2. input ( ) :
This function first takes the input from the user and then evaluates the expression,
which means Python automatically identifies whether user entered a string or a
number or list.

 If the input provided is not correct then either syntax error or exception is raised by
python

If input is included in quotes ,this function treats the received data as string or
otherwise the data is treated as numbers.
Ex: >>> x=input('enter any value:')
>>> x=input('enter any value:') enter any value:10
enter any value:'10' >>> type(x)
>>> type(x) <type 'int‘>
<type 'str'>
Here we are not required typecasting
In python 3, we have only one function i.e, input() function.
raw_input method is not available.
 input() function behavior exactly same as raw_input() method of python2.
Every input() function of python2 is renamed as input() in python3.
Ex: Whatever you enter as input, input function convert it into a string.
>>> x=input("Enter any value")
Enter any value'10'
>>> x
"'10'"
>>> type(x)
<class 'str‘>

If you enter an integer value still input() function convert it into a string.
>>> x=input("Enter any value")
Enter any value10
>>> type(x)
>>> x
<class 'str‘>
'10'
We need to do the explicit conversion into an integer in your code.
Explicit conversion:
Before input( )you can use your specific conversion type
Ex: 1
>>> x=int(input("Enter a number"))
Enter a number20
>>> x
20
>>> type(x)
<class 'int'>

Ex: 2
>>> x=float(input("Enter a number"))
Enter a number20.5
>>> x
20.5
>>> type(x)
<class 'float'>
eval function :
By using eval function, we can also do explicit conversion without using specific
datatype before input function.
before input function, mention eval function it automatically converts its datatype
based on the input provided by user

Ex: 1
>>> x1=eval(input("Enter a number"))
Enter a number20
>>> x1
20 Ex: 2
>>> type(x1) >>> x1=eval(input("Enter a number"))
<class 'int'> Enter a number20.5
>>> x1
20.5
>>> type(x1)
<class 'float'>
Write a python program to find addition of two numbers With
User Input and using replacement operator, format function in
print function?
# Store input numbers
num1 =float( input('Enter first number: '))
num2 =float( input('Enter second number: '))

# Add two numbers


sum = num1 + num2

# Display the sum


print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Output:

Enter first number: 1.5


Enter second number: 6.3
The sum of 1.5 and 6.3 is 7.8
6. Python Operators:

1. Arithmetic operators

2. Bitwise operators

3. Logical Operators

4. Assignment Operators

5. Comparison Operators

6. Special operators

i. Identity operators

ii. Membership operators


Ex: Arithmetic operators in Python
x = 15
y=4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
1. Bitwise AND operator (& ): Returns 1 if both the bits are 1 else 0
Ex:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary
a & b = 1010 &
0100
= 0000
= 0 (Decimal)
2. Bitwise or operator(|): Returns 1 if either of the bit is 1 else 0.
Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a | b = 1010 |
0100
= 1110
= 14 (Decimal)
3. Bitwise not operator( ~ ): Returns one’s complement of the number.
Example:
a = 10 = 1010 (Binary)
~a = ~1010
= -(1010 + 1)
= -(1011)
= -11 (Decimal)

4. Bitwise xor operator(^): Returns 1 if one of the bit is 1 and other is 0 else
returns false.
Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a ^ b = 1010 ^
0100
= 1110 = 14 (Decimal)
5. Bitwise left shift: Shifts the bits of the number to the left and fills 0 on voids left as a
result. Similar effect as of multiplying the number with some power of two.
Example:
a = 5 = 0000 0101
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20

6. Bitwise right shift: Shifts the bits of the number to the right and fills 0 on voids left
as a result. Similar effect as of dividing the number with some power of two.
Example 1:
a = 10 (0000 1010)
a >> 1= 0000 0101 = 5
a>> 2= 1000 0010 = 2
Python Logical Operators:
Operators are used to perform operations on values and variables.

The value the operator operates on is known as Operand.

There are three logical operators . They are:

1. Logical AND,

2. Logical OR and

3. Logical NOT operations.

These Logical operators are used on conditional statements.


1. Logical AND:
 It is represented as and
 Logical operator returns True if both the operands are True else it returns False.

Ex:
x=5
print(x > 3 and x < 10)
# returns True because 5 is greater than 3 AND 5 is less than 10
2. Logical OR:
 It is represented as or
 Logical or operator Returns True if one of the statements is true

Ex:
x=5
print(x > 3 or x < 4)
# returns True because one of the conditions are true (5 is greater
than 3, but 5 is not less than 4)
3. Logical NOT:
It is represented as not
Logical not operator work with the single boolean value.
If the boolean value is True it returns False and vice-versa.
Ex:
x=5
print(not(x > 3 and x < 10))
# returns False because not is used to reverse the result
Ex: Logical Operators in Python
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)

Output
x and y is False
x or y is True
not x is False
In c-language, logical operators In python, logical operators
Assignment operators :
Example:
x=5
y=4
x+=5
y&=5
print("x+=5---->",x)
print("y&=5---->",y)
x-=5
y|=5
print("x-=5---->",x)
print("y|=5---->",y)
x*=5
y^=5
print("x*=5---->",x)
print("y^=5---->",y)
x/=5
y>>=5
print("x/=5---->",x)
print("y>>=5---->",y)
x%=5
y<<=5
print("x%=5---->",x)
print("y<<=5---->",y
x//=5
print("x//=5---->",x)
x**=5
print("x**=5---->",x)
Output:
x+=5----> 10
x-=5----> 5
x*=5----> 25
x/=5----> 5.0
x%=5----> 0.0
x//=5----> 0.0
x**=5----> 0.0
y&=5----> 4
y|=5----> 5
y^=5----> 0
y>>=5----> 0
y<<=5----> 0
Comparison Operators
Ex: Comparison operators in Python
x = 10
y = 12
# Output: x > y is False
print('x > y is',x>y)
# Output: x < y is True
print('x < y is',x<y)
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
# Output: x >= y is False
print('x >= y is',x>=y)
# Output: x <= y is True
print('x <= y is',x<=y)
Ex: Identity operators in Python
x1 = 5
y1 = 5 Here, we see that x1 and y1 are integers of the same values, so
x2 = 'Hello' they are equal as well as identical. Same is the case
y2 = 'Hello' with x2 and y2 (strings).
x3 = [1,2,3] id(x1)==id(y1)
y3 = [1,2,3] id(x2)==id(y2)
# Output: True
print(x1 is y1) But x3 and y3 are lists. They are equal but not identical. It is
# Output: False because the interpreter locates them separately in memory
print(x1 is not y1) although they are equal.
# Output: True id(x3)!=id(y3)
print(x2 is y2)
# Output: False
print(x3 is y3)
# Output: True
print(x3 is not y3)
Ex:
x = 'Hello world'
y=[1,2,3]
print('H' in x)
print('hello' in x)
print('H' not in x)
print('hello' not in x)
print(1 in y)
print(5 in y)
Output:
True
False
False
True
True
False
Python Operator Precedence

Highest precedence at top, lowest at bottom. Operators in the same box evaluate left to rig
8. Slicing & Indexing:
For example in string, we can access individual character using indexing and a
range of characters using slicing. Index starts from 0 and ends with length -1, and
this index must be an integer.str=“HELLO”

H E L L O
Forward indexing 0 1 2 3 4

In indexing, for accessing the individual character we can use slice operator [ ], inside
that specify index number.
str[0]=‘H’
str[3]=‘L’
str[1]=‘E’
str[4]=‘O’
str[2]=‘L’

if we try to access a character out of index range then interpreter will raise an IndexError.
>>> str[5]
The index must be an integer if we try to
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module> access the data with non-integer indexes
str[5]
IndexError: string index out of range values then interpreter raises an TypeError.
Slicing means taking elements from one given index to another given index.
In slicing, by using the slice operator [ ] we can access the range of characters of the
string.
Inside square bracket[ ] we can use the : operator to access the substring.(positive
indexing).
We pass slice instead of index like this: [start:end].
If we don't pass start its considered 0
str=“HELLO”
If we don't pass end its considered length of string.
H E L L O

Forward indexing 0 1 2 3 4
Python allows negative indexing for its sequence. The index of -1 refers to
the last item, -2 refers to last 2nd item. This is called backward indexing

str=‘hello’
h e l l o
-5 -4 -3 -2 -1
>>> str[-1]
Backward indexing
'o'
>>> str[-3]
'l‘
>>> str[:-3]
'he'
>>> str[-3:]
'llo‘
>>> str[-3:-2]
'l‘
>>> str[-2:-2] # return empty strings.
‘'
>>> str[2:2] # return empty strings.
‘'
8. Forward Direction Slicing with +ve Step:
In slice operator, adding an additional : and a third index designates a stride (also
called a step), which indicates how many characters to jump after retrieving each
character in the slice.
str=“hello cse”

h e l l o c s e

0 1 2 3 4 5 6 7 8
Forward indexing

Ex:
str="hello cse"
str[0:6:2]--------------------------'hlo‘
str[1:6:2]---------------------------'el ‘

For suppose, if the first and second indices can be omitted, then by default it takes first
and last characters respectively.
str[::2]---------------------------'hloce‘ or str[0:9:2]-------------------------hloce'
str[::5]---------------------------'h '
9. Backward Direction Slicing with -ve Step:
You can specify a negative stride value as well, in which case Python steps backward
through the string. In that case, the starting/first index should be greater than the
ending/second index.
str=“hello cse”

h e l l o c s e

-9 -8 -7 -6 -5 -4 -3 -2 -1

Ex: Backward indexing


>>> str="hello cse"
>>>str[-1:-9:-2]
‘ecol’

-1:-9 :-2 means “start at the last character and step backward by 2, up to but not
including the first character.”
If you want to include first character, then
>>>str[-1:-10:-2]
‘ecolh’
When you are stepping backward, if the first and second indices are omitted, the
defaults are reversed in an intuitive way: the first index defaults to the end of the string,
and the second index defaults to the beginning.

Ex:
>>> str[::-2] or >>>str[-1:-10:-2]
'ecolh' ‘ecolh’
10. Decision Making Statements

Decision making statement(Conditional statements) used to control the flow of


execution of program depending upon condition, means if the condition is true then the
block will execute and if the condition is false then block will not execute.

It will decide the execution of a block of code based on the expression/condition.

Python supports 4 types of conditional statements


1. Simple if or if Statement
2. if...else statement
3. if...elif...else Statement
4. Nested if statements
1. Simple if or if Statement:
 An "if statement" is written by using the if keyword.
 In if statement, we have to follow indentation.
 if condition is true, if block executed, otherwise nothing will print /executed

Syntax:
if expression:
statement

Ex:
a = 33
b = 200
if b > a:
print("b is greater than a")
Short Hand if
If you have only one statement to execute, you can put it on the same line as the if
statement.
Example
#One line if statement:
a=3
b=2
if a > b: print("a is greater than b")
2. if-else statement:
In this, if condition is true, if block executed, otherwise else block executed
syntax :
if condition:
#block of statements
else:
#another block of statements (else-block)

Ex:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("a is greater than b")
Short Hand If ... Else
If you have only one statement to execute, one for if, and one for else, you can put
it all on the same line:

Ex: Program to check whether a person is eligible to vote or not

Program:
age=eval(input("Enter your age?"))
print("You are eligible to vote !!") if age >= 18 else print("Sorry! you have to wait !!
“)
Output:
Enter your age? 22
You are eligible to vote !!
3. if...elif...else Statement:
elif keyword means "if the previous conditions were not true, then try this condition".

Syntax:
if expression 1:
# block of statement
s

elif expression 2:
# block of statement
s

elif expression 3:
# block of statement
s

else:
Ex:
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Output:
a and b are equal
4. Nested if statements
You can have if statements inside if statements, this is called nested if statements.

Syntax: ex:
pass Statement in if statements
if statements cannot be empty, but if you for some reason have an if statement
with no content, put in the pass statement to avoid getting an error.
Ex:
a = 33
b = 200
if b > a:
pass
# having an empty if statement like this, would raise an error without the pass
statement
looping statements
In Python, the looping statements are also known as iterative statements or
repetitive statements.

The iterative statements are used to execute a part of the program repeatedly as
long as a given condition is True.

Python provides the following iterative statements.


1. for statement
2. while statement
1. for statement in Python
In Python, the for statement is used to iterate through a sequence like a list, a tuple,
a set, a dictionary, or a string, range.

The for statement is used to repeat the execution of a set of statements for every
element of a sequence.
Syntax of for Loop
for val in sequence:
Body of for

Here, val is the variable that takes the value of the item
inside the sequence on each iteration.

Loop continues until we reach the last item in the


sequence.

The body of for loop is separated from the rest of the


Example:
Python program to find sum of numbers in a list
using for loop
Ex:
range() function in for loop:
We can generate a sequence of numbers using range() function.
range(10) will generate numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as range(start, stop, step size).
step size defaults to 1 if not provided.
This function does not store all the values in memory, it would be inefficient. So
it remembers the start, stop, step size and generates the next number on the go.
To force this function to output all the items, we can use the function list().
 We can use the range() function in for loops to iterate through a sequence of
numbers.

 It ca also n be combined with the len() function to iterate though a sequence using
indexing.

Output:
I like pop
I like rock
I like jazz
Nested for Loop:
A nested loop is a loop inside a loop. The "inner loop" will be executed one time for
each iteration of the "outer loop":
Example
# Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry“]
for x in adj:
for y in fruits:
print(x, y)
Output:
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
Using else Statement with for Loop
A for loop can have an optional else block. The else keyword in a for loop
specifies a block of code to be executed when the loop is finished.
Ex: Print all numbers from 0 to 5, and print a message when the loop has
ended
for x in range(6):
print(x)
else:
print("Finally finished!“)
Output:
0
1
2
3
4
5
break Statement in for loop:
With the break statement we can stop the loop before it has looped through all the
items.
# Exit the loop when x is "banana", but this
Ex: Exit the loop when x is "banana“ time the break comes before the print:
fruits = ["apple", "banana", "cherry"]
for x in fruits: fruits = ["apple", "banana", "cherry"]
print(x) for x in fruits:
if x == "banana": if x == "banana":
break break
Output: print(x)
apple
banana Output:
apple
continue Statement in for loop
With the continue statement we can stop the current iteration of the loop, and
continue with the next:
Example
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)

Output:
apple
cherry
2. while Loop
In Python, the while statement is used to execute a set of statements repeatedly.

The while statement is also known as entry control loop statement because in the
case of the while statement, first, the given condition is verified then the execution
of statements is determined based on the condition result.

The general syntax of while statement in Python is as follows.

SYNTAX:
while expression:
statements
Example: print “Hello” string ,n times based on input() using while loop
infinite while loop
We can create an infinite loop using while statement. If the condition of while loop
is always True, we get an infinite loop.
Example #1: Infinite loop using while
# An example of infinite loop
# press Ctrl + c to exit from the loop
while True:
num = int(input("Enter an integer: "))
print("The double of",num,"is",2 * num) After interupt:
Enter an integer:
Traceback (most recent call last):
Output:
File "C:/Users/ajee/AppData/Local/
Enter an integer: 4
Programs/Python/Python37-32/iloop.py",
The double of 4 is 8
line 2, in <module>
Enter an integer: 5
num = int(input("Enter an integer: "))
The double of 5 is 10
KeyboardInterrupt
While loop with else:
Same as with for loops, while loops can also have an optional else block.
The else part is executed if the condition in the while loop evaluates to False.

Here is an example to illustrate this:


counter = 0
while counter < 3: Here, we use a counter variable to print the
print("Inside loop") string Inside loop three times.
counter = counter + 1
else: On the fourth iteration, the condition in
print("Inside else") while becomes False. Hence, the else part is
executed.
Output:
Inside loop
Inside loop
Inside loop
Inside else
For suppose , if while loop can be terminated with a break statement. In such cases, the
else part is ignored.

Ex:
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
if counter==2:
break
else:
print("Inside else")

Output:
Inside loop
Inside loop
The break Statement in while loop:
With the break statement we can stop the loop even if the while condition is true:

Example
#Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output:
1
2
3
continue Statement in while loop:
With the continue statement we can stop the current iteration, and continue with
the next.
Example: #Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Output:
1
2
4
5
6
pass statement in loops:
In Python programming, pass is a null statement nothing happens when it
executes.
It is used when a statement is required syntactically but you do not want any
command or code to execute.
Suppose we have a loop or a function that is not implemented yet, but we want to
implement it in the future. They cannot have an empty body. The interpreter would
complain. So, we use the pass statement to construct a body that does nothing.
for letter in 'Python': Output:

if letter == 'h': Current Letter : P

pass Current Letter : y

print( 'This is pass block' ) Current Letter : t

print 'Current Letter :', letter) This is pass block

We can do the same thing in an empty function or class. Current Letter : h


Current Letter : o
class example:
def function(args): pass Current Letter : n
Why we use loops in python?
The looping simplifies the complex problems into the easy ones.

 It enables us to alter the flow of the program so that instead of writing the same
code again and again, we can repeat the same code for a finite number of times.

For example,
if we need to print the first 10 natural numbers then, instead of using the print
statement 10 times, we can print inside a loop which runs up to 10 iterations.
Advantages of loops
There are the following advantages of loops in Python.

It provides code re-usability.

Using loops, we do not need to write the same code again and again.

Using loops, we can traverse over the elements of data structures (array or linked

lists).

You might also like