0% found this document useful (0 votes)
4 views16 pages

Python Notes

The document provides an overview of various operators and control structures in Python, including arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators. It also covers conditional statements, loops, data types such as lists, tuples, sets, and dictionaries, along with their methods and functionalities. Additionally, it introduces the math and random modules for mathematical operations and random number generation.

Uploaded by

salmansks44
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views16 pages

Python Notes

The document provides an overview of various operators and control structures in Python, including arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators. It also covers conditional statements, loops, data types such as lists, tuples, sets, and dictionaries, along with their methods and functionalities. Additionally, it introduces the math and random modules for mathematical operations and random number generation.

Uploaded by

salmansks44
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Operators

• Arithmetic Operators

• Comparison (i.e., Relational) Operators

• Assignment Operators

• Logical Operators

• Bitwise Operators

• Membership Operators

• Identity Operators

Arithmetic Operators

• a = 31 b = 9 c = 0

• c=a+b

• c=a-b

• c=a*b

• c=a/b

• c=a%b

• c = a**b

• c = a//b

Comparison Operators

!= , <>

<,>

<= , >=
if ( a == b ):

print (" a is equal to b",a)

else:

print (" a is not equal to b",b)

Assignment Operators

=,+=,-=,*=,/=,%=,**=,//=

Bitwise Operators

• a = 50

• b = 10

• c=0

• c = a & b and

• c=a|b or

• c=a^b xor

• c = ~a one’s compliment

• c = a << 2 Binary Left Shift Operator

• c = a >> 2 Binary Right Shift Operator

Logical Operators

 if (a == 10 or b < 20.0):
 if (a == 10 and b < 20.0):

if not(a == 10 and b < 20.0):

print (" Either a is not true or b is not true“)

else:

print (" a and b are true“)


Membership Operator

a = 10

b = 25

list = [10, 23, 34, 46, 58 ];

if ( a in list ):

print ("a is available in list“)

else:

print ("a is not available in list“)

• if ( b not in list ):

Identity operators

• Identity operators compare the memory locations of two objects

• if ( a is b ) :

• if ( id(a) == id(b) ):

• if ( a is not b ):

Conditional statements

If statement

If else statement

Nested if statement

x=5

if (x == 5):

print ("Wow, X is EXACTLY five!”)

elif (x > 5):

print ("X is now MORE than five!“)

else:
print( "X is now LESS than five!“)

Loops

while loop

While – else condition

for loop

For – else condition

While

count = 10

while (count < 20):

print ('count value is:',count)

count = count + 1

print('hi')

Infinite loop

c=1

while (c == 1) : # infinite loop

n = input("Enter a value :")

print("You entered: ", n)

print ("Good bye!") #ctrl+c to break loop


While with else

v=0

while v < 10:

print (v, " is less than 10")

v=v+1

else:

print (v, " is not less than 10")

For loop

for c in 'Piyush':

print( 'Current charactor :', c)

bikes = ['honda','bajaj','tvs']

for bike in bikes:

print ('current bike :', bike)

For and Range( )

>>>range(10)

a = ['Mary', 'had', 'a', 'little', 'lamb']

for i in range(len(a)):

print( i, a[i])

Range()

range(start, stop, step)

Program1-
x = range(3, 9)
for n in x:
print(n)

Program2-

x = range(3, 10, 2)
for n in x:
print(n)

For with else

for num in range(10,20):

for i in range(2,num):

if num%i == 0:

j=num/i

print ('%d equals %d * %d' % (num,i,j))

break

else:

print (num, 'is a prime number')

elif(switch)

t = input("What is the time?")

x=int(t)

if x < 10:

print ("Good morning")

elif x<12:

print ("Soon time for lunch")

elif x<18:

print ("Good day")


elif x<22:

print ("Good evening")

else:

print ("Good night")

break

for char in 'Piyush':

if char == 's':

break

print ('Current charactor :', char)

n = 20

while n > 0:

print ('Current variable value :', n)

n = n -1

if n == 15:

break

print ("end")

continue

for char in 'Piyush':

if char == 's':

continue

print ('Current charactor :', char)

n = 20

while n > 0:
n = n -1

if n == 15:

continue

print ('Current variable value :', n)

pass

Pass –any loop,function or class that is not implemented yet, but we want to implement it in the
future. So we will use pass for interpreter to understand the code execution.

seq = {‘a', ‘b', ‘c'}

for val in seq:

pass

def xyz(arg):

pass

class abc:

pass

standard data types

• Numbers

• String

• List

• Tuple

• Dictionary

• Sets

List

list1 = ['piyush', 34.7, ‘192’, 500];

list2 = [1, 3, 4, 8, 7 ];

print (“Third position ", list1[3])


print (“first to fourth position ", list2[1:5])

#Updating a list

Print( list1[2]);

list1[2] = 256;

len(list1)

list1 + list2

list1*5

4 in list1

For( y in list1):

print (y)

list1[-1]

List1[:5]

del list1[0]

del list1

List function

Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the
specified value
extend() Add the elements of a list (or any iterable),
to the end of the current list
index() Returns the index of the first element with
the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified
position
remove() Removes the first item with the specified
value
reverse() Reverses the order of the list
sort() Sorts the list

Tuple

tup1 = ();

tup1 = (28,);

# Following action is not valid for tuples

# tup1[0] = 20;

# So let's create a new tuple as follows

tup3 = tup1 + tup2;

print (tup3);

A = 'piyush', -4.24e93, 18+6.6j, 'goal'

print(A)

x, y = 45, 46

print ("Value of x , y : ", x,y)

a=12;b=10;c=a+b;print(c)

difference between list and tuple

In List,we can update and delete particular data members in list

but in tuple it is not posible.

>>> t1=(1,2,3)
>>> t1

(1, 2, 3)

>>> t1[0]=2

Traceback (most recent call last):

File "<pyshell#10>", line 1, in <module>

t1[0]=2

TypeError: 'tuple' object does not support item assignment

>>> del t1[0]

Traceback (most recent call last):

File "<pyshell#11>", line 1, in <module>

del t1[0]

TypeError: 'tuple' object doesn't support item deletion

>>>

Sets

Python also includes a data type for sets. A set is an unordered collection with no duplicate
elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also
support mathematical operations like union, intersection, difference, and symmetric difference

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

>>> print(basket) # show that duplicates have been removed

{'orange', 'banana', 'pear', 'apple'}

>>> 'orange' in basket # fast membership testing

True

>>> 'crabgrass' in basket

False

>>> fib={1,1,2,3,5,8,13}

>>> prime={2,3,5,7,11,13}
>>> fib

{1, 2, 3, 5, 8, 13}

>>> prime

{2, 3, 5, 7, 11, 13}

>>> fib | prime #Union

{1, 2, 3, 5, 7, 8, 11, 13}

>>> fib & prime #intersection

{2, 3, 5, 13}

>>> fib – prime #differene

{8, 1}

>>> fib ^ prime #symmetric diffrence

Dictionary

It is an unordered collection of key and value.

dict = {‘name': 'piyush', 'work': 12, 'subject': 'computer'}

dict[‘age'] = 25;

print(dict)

del dict[‘name']

dict.clear() # remove all entries in dict

print(dict)

del dict # delete entire dictionary

dict = {‘name': ‘piyush', 'Age': 43, 'Name': 'Majid'}

print ("dict[‘name']: ", dict[‘name'])

you can use strings, numbers or tuples as dictionary keys but list can’t

dict = {(1,2): ‘piyush', 'Age': 43, 'Name': 'Majid'}


formkeys()

x = ('key1', 'key2', 'key3')

y=0

thisdict = dict.fromkeys(x, y)

print(thisdict)

Output

['key1': 0, 'key2': 0, 'key3': 0]

Get()

car = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

x = car.get("model")

print(x)

Items

car = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

x = car.items()

print(x)

keys()
car = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

x = car.keys()

print(x)

values()

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.values()

print(x)

update()

car = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

car.update({"color": "White"})

print(car)

Math Module

>>>import math

>>> math.e #math module constant


2.718281828459045

>>> math.pi

3.141592653589793

Math Function

• math.ceil(x)-Return the ceiling of x, the smallest integer greater than or equal to x. I

• math.fabs(x)Return the absolute value of x.

• math.factorial(x)Return x factorial.

• math.floor(x)Return the floor of x, the largest integer less than or equal to x.

Random Module

random.choice([1, 2, 3, 5, 9])

random.randrange(100, 1000, 2)

• start -- Start point of the range. This would be included in the range. .

• stop -- Stop point of the range. This would be excluded from the range..

• step -- Steps to be added in a number to decide a random number..

random.uniform(5, 10)

print ("random() : ", random.random())

>>>list1=[1,2,3,4]

>>>random.shuffle(list1)

>>>random.shuffle(list1)

You might also like