0% found this document useful (0 votes)
38 views54 pages

Unit 1 (Second)

The document provides an overview of various operators in Python, including arithmetic, relational, assignment, logical, identity, membership, and bitwise operators, along with examples for each. It also covers data types such as lists, tuples, sets, and dictionaries, explaining their characteristics and usage. Additionally, the document discusses dynamic and static typing, input/output functions, and control flow statements in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views54 pages

Unit 1 (Second)

The document provides an overview of various operators in Python, including arithmetic, relational, assignment, logical, identity, membership, and bitwise operators, along with examples for each. It also covers data types such as lists, tuples, sets, and dictionaries, explaining their characteristics and usage. Additionally, the document discusses dynamic and static typing, input/output functions, and control flow statements in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Unit – 1

(Second)
Operators
• An operator is used to perform specific mathematical or logical
operation on values. The values that the operators work on are
called operands. Python supports several kinds of operators.
• Arithmetic Operators : Python supports arithmetic operators that
are used to perform the four basic arithmetic operations as well as
modular division, floor division and exponentiation.
• Floor Division : returns the quotient by removing the decimal part.
It is sometimes also called integer division.
• Eg : >>> num1 = 13
• >>> num2 = 4
• >>> num1 // num2
• 3
• Exponent : Performs exponential (power) calculation on operands.
• Eg : >>> num1 = 3
• >>> num2 = 4
• >>> num1 ** num2 = 81
• Relational Operators
• Relational operator compares the values of the
operands on its either side and determines the
relationship among them.
• Operator are : ==, 1=,>,<,>=,<=.
• Assignment Operators
• Assignment operator assigns or changes the value
of the variable on its left.
• Operators are : =, +=,.=,*=,/=,%=,//=,**=
• Logical Operators
• There are three logical operators supported by Python.
• These operators (and, or, not) are to be written in
lower case only. The logical operator evaluates to
either True or False based on the logical operands on
either side. Every value is logically either True or False.
By default, all values are True except None, False, 0
(zero), empty collections "", (), [], {}, and few other
special values.
• Operators are : and, or, not
• Eg : num1 = 10, num2 = -20, then both num1 and
num2 are logically True.
• Eg : >>> num1 = 10
• >>> num2 = -20
• >>> bool(num1 and num2)
• True
• identity Operators
• Identity operators are used to determine whether the value of a
variable is of a certain type or not. Identity operators can also be
used to determine whether two variables are referring to the
same object or not. There are two identity operators.
• is : Evaluates True if the variables on either side of the operator
point towards the same memory location and False otherwise.
• var1 is var2 results to True if id(var1) is equal to id(var2)
• Eg : >>> num1 = 5
• >>> type(num1) is int
• True
• >>> num2 = num1
• >>> id(num1)
• 1433920576
• >>> id(num2)
• 1433920576
• >>> num1 is num2 = True
• Is not : Evaluates to False if the variables on either side of the
operator point to the same memory location and True otherwise.
• Var1 is not var2 results to True if id(var1) is not equal to id(var2)
• a = 10
• b = 10
• print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))
• if ( a is b ):
• print ("Line 2 -a and b have same identity")
• else:
• print ("Line 2 -a and b do not have same identity")
• Membership Operators :
• Membership operators are used to check if a value is a member of
the given sequence or not.
• in : Returns True if the variable/value is found in the specified
sequence and False otherwise.
• Eg : >>> a = [1,2,3]
• >>> 2 in a
• True
• >>> '1' in a : False
• not in : Returns True if the variable/value is not found in
• the specified sequence and False otherwise.
• Eg : >>> 10 not in a : True
• >>> 1 not in a : False
• b = 10
• list = [1, 2, 3, 4, 5 ]
• if ( a in list ):
• print ("Line 1 -a is available in the given list")
• else:
• print ("Line 1 -a is not available in the given list")
• if ( b not in list ):
• print ("Line 2 -b is not available in the given list")
• else:
• print ("Line 2 -b is available in the given list")
• Bitwise : bitwise operators are used to
perform bitwise calculations on integers. The
integers are first converted into binary and
then operations are performed on each bit or
corresponding pair of bits

Operator Meaning Example


& Bitwise AND X&y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR X^y
>> Bitwise right shift X>>2
<< Bitwise left shift X<<2
– A=10
– B=4
• # Print bitwise AND operation
• print("a & b =", a & b)

• # Print bitwise OR operation
• print("a | b =", a | b)

• # Print bitwise NOT operation
• print("~a =", ~a)

• # print bitwise XOR operation
• print("a ^ b =", a ^ b)
• a=6
• b=3
• print ('a=',a,':',bin(a),'b=',b,':',bin(b))
• c=0
• c = a & b;
• print ("result of AND is ", c,':',bin(c))
• c = a | b;
• print ("result of OR is ", c,':',bin(c))
• c = a ^ b;
• print ("result of EXOR is ", c,':',bin(c))
• c = ~a;
• print ("result of COMPLEMENT is ", c,':',bin(c))
• c = a << 2;
• print ("result of LEFT SHIFT is ", c,':',bin(c))
• c = a >> 2;

• print ("result of RIGHT SHIFT is ", c,':',bin(c))


Punctuators

• Punctuators are symbols that are used in


programming languages to organize sentence
structure and indicate the rhythm and
emphasis of expressions, statements and
program structures.
• Most common punctuators are :
– ‘, “,#,\,(),[],{},@,:,. Etc.
Dynamic typing
• Dynamic typing means that the type of the variable is determined
only during runtime. Due to strong typing, types need to be
compatible with respect to the operand when performing
operations.
– For example Python allows one to add an integer and a floating point
number, but adding an integer to a string produces error.
• Due to dynamic typing, in Python the same variable can have a
different type at different times during the execution. Dynamic
typing allows for flexibility in programming.
• Eg : x=10
• Print(x)
• X=“helloworld”
• Print(x)
• Note : A variable pointing to a value of a certain type, can be made
to point to a value /object of different type. This is called Dynamic
Typing.
Static Typing

• In static typing, a data type is attached with a


variable when it is defined first it is fixed i.e.
data type of a variable cannot be changed in
static typing whereas there is no such
restriction in dynamic typing which is
supported by python.
• Eg:
Simple input / Output
• In python, to get input from user you we can use built
in function input(). The function input() is used in
following way:
• Var=input(‘prompt to be displayed’)
• Eg :
• Name=input(‘what is your name’)
• The input() function always returns a value of string
type. Python offers two functions int() and float() to be
used with input() to convert the values received
through input() into int and float type.
• Syntax : varname=int(input(‘prompt strings>))
varname=flaot((input(‘prompt strings>))
Eg : x=int(input('Enter Age'))
print('My age is',x)
• Separator : you can change the value of seprator
character with sep argument of print() like :
– print("my","name","is","Amit",sep='...')
– o/p : my.....name.....is.....Amit
• If you explicitly give an end argument with a print()
function then the print() will print the line and end it
with the string specified with the end argument and
not the newline character.
• Eg : print("my name is harjender.",end='$')
print(" i am 18 year old.")
o/p : my name is harjender.$ i am 18 year old.

Example : WAP to input a number and print its cube.


WAP to input a number and print its square root
Lists
• A list in python represents a group of comma
separated values of any data type b/w square
brackets.
• List are extremely similar to tuples. List are
modifiable(or mutable) i.e. the values can be changed.
Most of the time we use lists not tuples because we
want to easily change the values
• Eg : cats=['Tom', 'Snappy','Kitty','Jassie','Chester']
• print(cats[2])
• cats.append('Billllllli')
• print(cats)
• #remove the 2nd cat
• del cats[1]
• print(cats)
• Examples :

• #creating a blank list


• list=[]
• print("Blank List ")
• print (list)
• #creating a list of numbers
• list=[10,20,30]
• print("\n list of numbers : ")
• print(list)
• #creating a list of strings and accessing using index
• list=["shubham","kartik","Utkarsh"]
• print("\nlist items are : ")
• print(list[0])
• print(list[1])
• Example :

• #creating a blank list


• list=[]
• print("Blank List ")
• print (list)
• ## addition of element in the list
• list.append(1)
• list.append(2)
• list.append(4)
• print("\n list after addition are : ")
• print(list)
• # Adding element to the list using iterator
• for i in range(1,4):
• list.append(i)
• print("\n list after addition of elements from 1-3: ")
• print(list)
Tuples
• Tuples are used to store multiple items in a single
variable.
• A tuple is a collection which is ordered (it means that
the items have a defined order, and that order will not
change.), unchangeable and allow duplicate values.
• Tuple is one of 4 built-in data types in Python used to
store collections of data, the other 3 are List, Set,
and Dictionary, all with different qualities and usage.
• Eg : thistuple = ("apple", "banana", "cherry")
• print(thistuple)
• #Duplicate Items
• thistuple =
("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
• To determine how many items a tuple has, use
the len() function.
• Eg : thistuple = ("apple", "banana", "cherry")
– print(len(thistuple))
• To create a tuple with only one item, you have to add a
comma after the item, otherwise Python will not
recognize it as a tuple.
• Eg : thistuple = ("apple“,)
– print(type(thistuple))
• Tuple items can be of any data type.
• Eg : tuple1 = ("apple", "banana", "cherry")
• print(type(tuple1))
• tuple2 = (1, 5, 7, 9, 3)
• print(type(tuple2))
• tuple3 = (True, False, False)
• print(type(tuple3))
• A tuple with strings, integers and boolean
values.
• Eg : tuple1 = ("abc", 34, True, 40, "male")
– print(type(tuple1))
Set
• Sets are used to store multiple items in a single variable.
• It is a collection of unordered, unchangeable, and unindexed but
No duplicate members.
• Once a set is created, you cannot change its items, but you can
remove items and add new items.

• Eg : #create a Set
• thisset = {"apple", "banana", cherry","Banana"}
• print(thisset)

• Note: The values True and 1 are considered the same value in sets,
and are treated as duplicates.

• Eg : thisset = {"apple", "banana", "cherry", True, 1, 2}

• print(thisset)
• Datatype of Set :

• myset = {"apple", "banana", "cherry"}


• print(type(myset))

• A set with strings, integers and boolean


values.
• set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
Mutable and Immutable Type
• The python data objects can be broadly
categorized into two:
• Mutable and immutable type i.e changeable
and non modifiable types.
• The immutable types are those that can never
change their value in place. In python
following types are immutable : integer,
floating point members, Boolean, strings,
tuples
• #immutable datatype tuple
• tuple1=("hello",1,1.2,"delhi")
• print(id(tuple1))
• tuple1[0]="dinesh"
• print(tuple1)
• print("*****************")
Mutable Types
• Mutability means that in the same memory
address, new value can be stored as and when
you want. The types that do not support this
property are immutable types.
• The mutable types are those whose values can
be changed in place. Only three types are
mutable in python.
• These are Lists, Dictionaries and sets.
• #mutable example of list
• list1=["hello",1,1.2,"delhi"]
• print(id(list1))
• list1[0]="dinesh"
• print(id(list1))
• print(list1)
• print("*****************")
• Dictionary
– Dictionaries are used to store data values in key:value pairs.
– A dictionary is a collection which is ordered*, changeable
and do not allow duplicates(Dictionaries cannot have two
items with the same key)
– Dictionaries are written with curly brackets, and have keys
and values
Eg : thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Ex: Duplicates Not Allowed

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 1964
}
print(thisdict)
• To determine how many items a dictionary has, use the len() function
– print(len(thisdict))
• The values in dictionary items can be of any data type.
– thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
• The dict() Constructor
– It is also possible to use the dict() constructor to make a dictionary.
• Ex : thisdict = dict(name = "John", age = 36, country = "Norway")
• print(thisdict)
control flow statements

• A program’s control flow is the order in which


the program’s code executes.
• There are 03 control flow statements :
– Sequential - default mode
– Selection - used for decisions and branching
– Repetition - used for looping, i.e., repeating a
piece of code multiple times.

Sequential

• Sequential statements are a set of statements


whose execution process is in a sequence.
• The problem with sequential statements is that if
the logic has broken in any one of the lines, then
the complete source code execution will break.
• Eg :
– ## This is a Sequential statement
– a=20
– b=10
– c=a-b
– print("Subtraction is : ",c)
Selection/Decision control statements

• the selection statements are also known


as Decision control statements or branching
statements.
• The selection statement allows a program to test
several conditions and execute instructions based
on which condition is true.
• Some decision control statements are:
– if
– if-else
– nested if
– if-elif-else
• if – It help us to run a particular code, but only
when a certain condition is met or satisfied.
• Eg :
n = 10
if n % 2 == 0:
print("n is an even number")
• if-else – The if-else statement evaluates the
condition and will execute the body of if.
• Eg :
n=5
if n % 2 == 0:
print("n is even")
else:
print("n is odd")
• Nested if: Nested if statements are
an if statement inside another if statement.
• Eg :
a = 20
b = 10
c = 15
if a > b:
if a > c:
print("a value is big")
else:
print("c value is big")
elif b > c:
print("b value is big")
else:
print("c is big")
• if-elif-else: The if-elif-else statement is used to
conditionally execute a statement or a block of
statements.
• Eg :
x = 15
y = 12
if x == y:
print("Both are Equal")
elif x > y:
print("x is greater than y")
else:
print("x is smaller than y")
Repetition
• A repetition statement is used to repeat a
group(block) of programming instructions.
• In Python, we generally have two
loops/repetitive statements:
– for loop
– while loop
• for loop – A for loop is used to iterate over a
sequence that is either a list, tuple, dictionary,
or a set. We can execute a set of statements
once for each item in a list, tuple, or
dictionary.
• Eg :
print("2nd example")

for j in range(0,5):
print(j, end = " \n")
• Eg :
print("2nd example")
for j in range(0,5):
print(j, end = " \n")
Eg :
#use a for loop over a collection
Months = ["Jan","Feb","Mar","April","May","June"]
for m in Months:
print(m)
# use the break and continue statements
for x in range (10,20):
#if (x == 15): break
if (x % 5 == 0) : continue
print(x)
• names = ["Bill Gates", "Billie Eilish", "Mark
Zuckerberg", "Hussain"]
• namesWithB = []
• for name in names:
• if "B" in name:
• namesWithB.append(name) # add this
element to this array.
• print(namesWithB)
• while loop: In Python, while loops are used to execute a block of
statements repeatedly until a given condition is satisfied. Then, the
expression is checked again and, if it is still true, the body is
executed again. This continues until the expression becomes false.
• Eg :
m=5
i=0
while i < m:
print(i, end = " ")
i=i+1
print("End")
Eg :
numbers = [0, 5, 10, 6, 3]
length = len(numbers) # get length of array.
n=0
while n < length: # loop condition
print(numbers[n])
n += 1
• # program to calculate the sum of numbers until
the user enters zero.
• WAP to Create the multiplication table of any
number.
• Write a nested for loop program to print
multiplication table in Python
• Wap to print various pattern
• Print a rectangle Pattern with 5 rows and 3
columns of stars
• Wap to print all perfect numbers from 1 to 100
'Show Perfect number from 1 to 100')
Perfect number, a positive integer that is equal to the sum of its proper divisors.

• print('Show Perfect number fom 1 to 100')


• n=2
• # outer while loop
• while n <= 100:
• x_sum = 0
• # inner for loop
• for i in range(1, n):
• if n % i == 0:
• x_sum += i
• if x_sum == n:
• print('Perfect number:', n)
• n += 1
Python String
• A String is a data structure that represents a
sequence of characters. It is an immutable
data type.
• Strings are used widely in many different
applications, such as storing and manipulating
text data, representing names, addresses, and
other types of data that can be represented as
text.
• Note : Python does not have a character data
type, a single character is simply a string with
a length of 1.
• Strings in Python can be created using single
quotes or double quotes or even triple quotes(The
triple quotes can be used to declare multiline
strings in Python)
• Eg : # Creating a String with triple Quotes
• String1 = '''I'm a Geek and I live in a world of
"Geeks"'''
• print("\nString with the use of Triple Quotes: ")
• print(String1)
• Accessing characters in Python String
– In Python, individual characters of a String can be accessed by
using the method of Indexing.
– Indexing allows negative address references to access characters
from the back of the String
– e.g. -1 refers to the last character, -2 refers to the second last
character, and so on.
• Eg :
– # Python Program to Access characters of String

– String1 = "GeeksForGeeks"
– print("Initial String: ")
– print(String1)
– # Printing First character
– print("\nFirst character of String is: ")
– print(String1[0])
– # Printing Last character
– print("\nLast character of String is: ")
– print(String1[-1])
String Slicing

• the String Slicing method is used to access a


range of characters in the String.
• Slicing in a String is done by using a Slicing
operator i.e. a colon (:)
• slicing includes the character at the start index
but not the character at the last index.
• We can also use negative indexing in string
slicing.
• Syntax : lst[initial:End:IndexJump]
• Eg :
# Python Program to # demonstrate String slicing
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)

# Printing 3rd to 12th character


print("\nSlicing characters from 3-12: ")
print(String1[3:12])

# Printing characters between 3rd and 2nd last character


print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])
Reversing a Python String

• Python string library doesn’t support the


in-built reverse() method. We can Reverse a
string by using String slicing method.
• Eg :
– x = "surajmalinstitutejanakpuri"
– print(x[::-1])
– Print(x[-1::-1])
Deleting/Updating from a String
• the Updation or deletion of characters from a
String is not allowed.
• This will cause an error because item assignment
or item deletion from a String is not supported.
• Although deletion of the entire String is possible
with the use of a built-in del keyword.
• Updating a character
– A character of a string can be updated in Python by
first converting the string into a List and then updating
the element in the list. As lists are mutable in nature.
– Another method is using the string slicing method.
Slice the string before the character you want to
update, then add the new character and finally add
the other part of the string again by string slicing.
• Eg:
– # Python Program to Updadate character of a String

– String1 = "Hello, I'm a Programmer"
– print("Initial String: ")
– print(String1)
– # Updating a character of the String
– list1 = list(String1)
– list1[2] = 'p'
– String2 = ''.join(list1)
– print("\nUpdating character at 2nd Index: ")
– print(String2)
• In the string-slicing method, we sliced the
string up to the character we want to update,
concatenated the new character, and finally
concatenate the remaining part of the string.
• Eg :
– String3 = String1[0:2] + 'prt' + String1[3:]
– print(String3)
• Deleting a character
• Python strings are immutable, that means we cannot delete
a character from it.
• When we try to delete the character using the del keyword,
it will generate an error.
• But using slicing we can remove the character from the
original string and store the result in a new string.
• Eg :
– # Python Program to Delete characters from a String

– String1 = "Hello, I'm a learner"
– print("Initial String: ")
– print(String1)

– # Deleting a character of the String
– String2 = String1[0:2] + String1[3:]
– print("\nDeleting character at 2nd Index: ")
– print(String2)
Formatting of Strings
• Strings in Python can be formatted with the use
of format() method which is a very versatile and powerful tool for
formatting Strings.
• Format method in String contains curly braces {} as placeholders
which can hold arguments according to position or keyword to
specify the order.
• Eg :
– # Default order
– String1 = "{} {} {}".format(‘MSI', 'For', 'Life')
– print("Print String in default order: ")
– print(String1)

– # Positional Formatting
– String1 = "{1} {0} {2}".format('Geeks', 'For', 'Life')
– print("\nPrint String in Positional order: ")
– print(String1)
• # Keyword Formatting
• String1 = "{l} {f} {m}".format(m=‘msi', f='For', l='Life')
• print("\nPrint String in order of Keywords: ")
• print(String1)
What is String Iteration in Python
• iterate over a string means accessing each of its characters
of a string one by one.
• Eg :
– w="welocme to scubetech company"
– t=len(w)
– print(t)
– for a in range(t) :
– print(w[a])
• #reverse the string
• w="welocme to scubetech company"
• t=len(w)
• print(t)
• for a in range(t-1,-1,-1) : # total len 21
• print(w[a])

You might also like