Roshan Book

My Tech Notebook

Python tutorial 7–Calculations


5//3 – floor division – 1 (integer only)

5/3 – 1.6666

5%2 –2

2**3 -8

divmod(5,3) – division with integer result and mod –(1,2) – result as tuple

python supports x+=1 with other opertaors like *, /, –,//

printing binary values

def b(n): print (‘{:08b}’.format(n))

now calling this function b(5) – would output binary value of 5 i.e. 00000101

Operators

x is y – id is compared

x is not y-id is compared

and  –  comparing boolean conditions

or- comparing boolean conditions

Slice operator

list = [1,2,3,4]

list[0:2] – gives slice of first 2 items, i.e. index 0, 1

for i in range(0,10)  :  print(i)

gives 0-9, last item is always non inclusive in a range

list [:]= range() – this gives 100 items in our list starting from 0 – 0to 99

list[27:42] – slice of from 27 index to 41 index (42 is non inclusive)

list[27:42:3] – list of 27 to 41 index with every 3rd item

list[27:43:3]=[99,99,99,99,99,99]- it replaces third element from 27 to 42 is replaced to 99

Operator precedence

Python follows bodmas rule

* and / is upper than +-. * and / has same preferably thus, when * and / both are there, then in the order of occurrence from left calculation happens.

For comparison operator like <==,in,not,is,isnot,!= etc , associativity is from right to left

Use parentheses

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: