Saturday, June 17, 2023

Python Variable Declaration & Python Operator

 

CHAPTER 2

VARIABLE DECLARATIONS

 

variable declarations (or lack if thereof):

>>>a

traceback(innermost last):
file"<stdin>",line 1 , in ?

name error: a

 

>>>x=4

>>>y='this is a string'

>>>x

4

>>>y

'this is a string'

 

 

Python statement , indentation and comments :

python statement

multiline statement

 

>>> a=10+12+35+40+50+60+70+80+19

>>> a

376

>>> a=(10+12+35+40+50+60+70+80+19)

>>> a

376

 

colors = ['silver'

                   'yellow'

                    'red']

 

>>> a=10;b=20;c=30

>>> a

10

>>> b

20

>>> c

30

PYTHON INDENTION :

 

for i in range (1,10):

   print(i)

   if i==6:

    break

output

>>> 

1

2

3

4

5

6

 

if True :

    print('hello world')

a=5

 

output

>>> 

hello world

 

if True:

   print('hello world');

x=5+7

 

PYTHON COMMENTS

single line comment

#this is a comment

#print out hello world

print('hello world')

 

MULTILINE COMMENTS

"""this is also a

perfect example of

 multi line comments """

 

PYTHON VARIABLES AND DATA TYPES

python variables

a=5

b=3.2

c="HAI"

 

MULTIPLE ASSIGNMENTS

a, b, c = 5,3.2,"hai"

 

a=b=c=100 #this assigns the 100 to all three variables

a=10,20,0     #this assigns the tuple a

 

Data types in python

python numbers

strings

 

>>> str 1 = 'python'

>>>str 2 ='is an easy language !'

>>>str 1 =[2:5]

'tho'

>>>str2[2:]

'is'

>>>str2[3:]

'an easy language !'

>>>str2[-1]

'!'

>>>str1 + str2

'python is an easy language !'

>>>str1 + ' ' + str2

'python is an easy language !'

>>> str1 * 2

'PythonPython'

>>>'-' * 20

'-------------------'

a = 5

print(a, "is of type",type(a))

a = 5.0

print(a, "is of type",type(a))

a = 1 + 2j

print(a, "is complex number?", isinstance(1 + 2j,complex))

Output

(5, 'is of type', <type 'int'>)

(5.0, 'is of type', <type 'float'>)

((1 + 2j), 'is complex number?',True)

Example

>>> a = 1234567890123456789

>>>  a

1234567890123456789

>>> b = 0. 1234567890123456789

>>> b

0. 1234567890123456789

>>> c = 1 + 2j

>>> c

(1 + 2j)

 

Python List

>>> a = [10, 2.2, 'HAI']

a= [5,10,15,20,25,30,35,40]

print("a[2] = ", a[2])

print("a[0:3] = ", a[0:3])

print("a[5:] = ", a[5:])

 

Output

a[2] = 15

a[0:3] = [5, 10, 15]

a[5:] = [30, 35, 40]

In [1]:

>>>  a = [1,2,3]

>>>  a[2]=4

>>> a

[1, 2, 4]

 

Python Tuple

> > > t = (5,'program', 1+3j)

# Generates error

# Tuples are immutable

t[0] = 10

t[1] = program

t[0:3] = (5, 'program', (1+3j))

Traceback (most recent call list):

  File " <stdin>", line 11, in <module>

    t[0] = 10

TypeError: 'tuple' object does not support item assignment

In [1]:

Python strings

> > > s = "This is a string"

> > > s = """a multiline"""

s = 'hello world'

# s[4] = 'o'

print("s[4] = ", s[4])

# s[6:11] = 'world'

print("s[6:11] = ", s[6:11])

# Generates error

# String are immutable in python

s[5] = 'd'

s[4] = 'o'

s[6:11] = 'world'

Traceback (most recent call last):

   File " <stdin>", line 11, in <module>

      s[5] = 'd'

TypeError: 'str' object dose not support item assignment

In [1]:

Python set (Collection of Unique Items)

a = {5,2,3,1,4}

# printing set variable

print("a = ", a)

# data type of variable a

print(type(a))


Output

a = {1,2,3,4,5}

<class 'set'>

In [1]:

> > > a ={1,2,3,3,3}

> > > a

{1, 2, 3}

> > > a = {1,2,3}

> > > a[1]

Traceback (most recent call last):

    File " <string> ", line 301, in runcode

    File " <interactive input> ", line 1 in <module>

TypeError: 'set' object dose not support indexing

 

Python Dictionary

> > > d = {1:'ONE','key':2}

> > > type(d)

< class 'dict'>

d = {1:'ONE','key':2}

print(type(d))

print("d[1] = ", d[1]);

print("d['key'] = ", d['key']);

# Generates error

print('d[2] = ", d[2]);

 

 

Output

<class 'dict'>

d[1] = ONE

d['key'] = 2

Traceback (most recent call last):

   File "<stdin>", line 9, in <module>

   print("d[2] = ", d[2]);

KeyError: 2

In [1]:

Conversion Between data types

> > > float(5)

5.0

conversion from float to int will truncate the value (make it closer to zero)

> > > int(100.6)

100

> > > int(-1.6)

-1

> > >  float('2.5')

2.5

> > > str(25)

'25'

> > > int('TN 10')

Traceback (most recent call last):

  File " <string> ", line 301, in runcode

  File "<interactive input> ", line 1, in <module>

ValueError: invalid literal for int() with base 10: 'TN10'

> > > set([1,2,3])

{1, 2, 3}

> > > tuple({5,6,7})

{5, 6, 7}

> > > list ('Hello Chennai')

['H', 'e', 'l', 'l','o', ' ' ,'c', 'h', 'e', 'n', 'n''a', 'i']

> > > dict([[1,2],[3,4]])

{1: 2, 3: 4}

> > > dict([[1,2],[3,4]])

{1: 2, 3: 4}

> > > dict([(101, 'HDCA'),(102,'ADJP')])

{101: 'HDCA', 102: 'ADJP'}

Python Input , Output and Import

Python Output Using print() function

> > > print('This is my first python program')

output:

This is my first python program

 

a = 5

> > > print('the value of a is', a)

output:

The value of a is 5

The actual syntax of the print() function is

print(1,2,3,4)

print(1,2,3,4,sep= ' * ')

print(1,3,5,7,sep= '#', end = '&')

output

1 2 3 4

1*2*3*4

1#3#5#7&

Output formatting

> > > x = 5; y = 10

> > > print('The value of x is {} and y is {}'.format(x,y))

The value of x is 5 and y is 10

>>print('l would like eat {0} and {1}'.format('pizza','burger'))

>>print('I had visited {1} and {0}'.format('Delhi','Mumbai'))

output

I Would like eat Pizza and Burger

I had visited Mumbai and Delhi

 

> > > print('Hello {name}, ,{greeting}',format(greeting='Good morning', name='Ramesh'))

output:

Hello Ramesh, Good morning

Python Input()

 variable = input([prompt])

> > > num = input('Enter a number: ')

Enter a number: 10

> > > num

'10'

> > > print type(num)

<type 'str')>

> > > int('10') or num = int (input("Enter a number:"))

10

> > >float('10')

10.0                     

>> >int('2+3')                                                                          

valueError: invalid literal for int() with base 10;'2+3'

>>>eval('2+3')

5

 

PYTHON MODULE

import math

print(math.pi)

>>>from math import pi

>>>pi

3.141592653589793

 

>>> import sys

>>> sys.path

['', 'C:\\Python27\\Lib\\idlelib', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages']

Python Operator

6 Type Of Operators In Python 

¨    Arithmetic Operator

¨    Comparison (Relational) Operator

¨    Logical Operator

¨    Bitwise Operator

¨    Assignment Operator

¨    Special Operator

Arithmetic Operator

arithmetic operator are used to perform mathematical operation like addition, subtraction, multiplication etc.

Operator

Meaning

Example

+

Add two operands

X+y+2

-

Subtract right operand from the left

x-y-2

*

Multiply two operands

X*y

/

Divide left operand by the right one

x/y

%

Modulus-remainder of the division of left operand to the right

X%y

//

Floor divison-division that result into whole number adjusted to the left in the number line

x//y

**

Exponent-left operand raised to the power of right

X**y

 

Example:

x = 15

y = 4

print('x + y = ',x+y)

print('x - y = ',x-y)

print('x * y =',x*y)

print('x / y =',x/y)

print('x % y =',x%y)

print('x // y =',x//y)

print('x ** y =',x**y)

 

output :

x + y =  19

x - y =  11

x * y = 60

x / y = 3.75

x % y = 3

x // y = 3

x ** y = 50625

 

Comparison Operator:

comparison operators are used to compare values. it either returns true or false according to the condition.

 

Operator

Meaning

example

Greater than-true if left operand is greater than the right

X > y

Less than - true if left operand is less than the right

X < y

==

Equal to - true if both operands are equal

X == y

!=

Not equal to-true if operands are not equal

X!=Y

 

>=

Greater than or equal to-true if left operand is greater than or equal to the right

X>=Y

<=

Less than or equal to-true if left operand is less than or equal to the right

X <= y

 

 

 

 

 

Example:

x=10

y=12

print('x>y is', x>y)

print('x<y is', x<y)

print('x==y is', x==y)

print('x!=y is' ,x!=y)

print('x>=y is', x>=y)

print('x<=y is', x<=y)

OUTPUT

x>y is false

x<y is true

x==y is false

x!=y is true

x>=y is false

LOGICAL OPERATORS

Operator

Meaning

Example

and

True if both the operands are true

X and Y

or

True if either of the operands is true

X or Y

not

True if operands is falce(complements the operand)

not X

EXAMPLE:

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

 

 

BITWISE OPERATORS

Operator

Meaning

Example

&

Bitwise AND

X&Y=0(0000 0000)

|

Bitwise Or

X/Y=14 (0000 0000)

~

Bitwise NOT

~X=-11 (1111 0101)

^

Bitwise XOR

X^ y= 14 (0000 1110)

>> 

Bitwise right shift

X>>2=2(0000 0010)

<< 

Bitwise left side

X<<2= 40 (0010 1000)

Example:

x =2

y = 3

print('x & y = ',x&y)

print('x | y = ',x|y)

print('x ^ y =',x^y)

print('~x  =',~x)

print('x <<2 =',x<<2)

print('x >> y =',x>>y)

output

x & y =  2

x | y =  3

x ^ y = 1

~x  = -3

x <<2 = 8

x >> y = 0

 

ASSIGNMENT OPERATORS:

Operator

Example

Equivalent to

+=

X+=5

X=X+5

-=

X-=5

X=X-5

*=

X*=5

X=X*5

/=

X/=5

X=X/5

 

>>> a=6

>>> a+=3

>>> a

9

>>> a-=2

>>> a

7

>>> a*=3

>>> a

21

>>> a/=3

>>> a

7.0

 

SPECIAL OPERATORS

Identity Operators

OPERATOR

MEANING

EXAMPLE

is

True if the operands are identical

X is true

is not

True if the operands are  not  identical

X is not true

 

example

x1=5

y1=5

x2='Hello'

y2='Hello'

x3=[1,2,3]

y3=[1,2,3]

print(x1 is not y1)

print(x2 is y2)

print(x3 is y3)

output

False

True

False

 

Membership Operator

OPERATOR

MEANING

EXAMPLE

in

True if value/variable is found in the sequence

5 in x

not in

True if value/variable is not found in the sequence

5 not in x

 

x="Hello world"

y={1:'a',2:'b'}

print('H' in x)

print('hello' not in x)

print(1 in y)

print('a' in y)

 

output

True

True

True

False

 

 


0 comments:

Post a Comment