Data Type Conversion
a) int(55.89)
b) float(36)
my_string=str(9500)
Tuple
>>> tuple(“This is a string.”)
(‘T’, ‘h’, ‘i’, ‘s’, ‘ ‘, ‘i’, ‘s’, ‘ ‘, ‘a’, ‘ ‘, ‘s’, ‘t’, ‘r’, ‘i’, ‘n’, ‘g’, ‘.’)
>>>
list(“This will be a list”)
>>> list(“This will be a list”)
[‘T’, ‘h’, ‘i’, ‘s’, ‘ ‘, ‘w’, ‘i’, ‘l’, ‘l’, ‘ ‘, ‘b’, ‘e’, ‘ ‘, ‘a’, ‘ ‘, ‘l’, ‘i’, ‘s’, ‘t’]
chr(65)
ord(‘a’)
hex(4500)
bin(42)
================================================================================
Arithmetic & Comparison Operators
7 kind of operators
Arithmetic = + , – , / , % , **
a=10
b=15
a+b
>>> a=10
>>> b=10
>>> a+b
20
a*b
comparison operator = a==b check a equal to b
a!=b , a>b , a<b , a<=b , a>=b
>>> a=10
>>> b=10
>>> a+b
20
>>>
>>> a==b
True
>>>
>>> a=15
>>> b=10
>>> a==b
False
>>>
Bitwise & Logical Operators
>>> a=15
>>> b=20
>>> bin(a)
‘0b1111’
>>> bin(b)
‘0b10100’
>>> bin(a&b)
>>> bin(a&b)
‘0b100’
>>> bin(a|b)
‘0b11111’
>>> bin(a^b)
‘0b11011’
AND Operation
a=True
b=False
a and b
False
a or b
True
not a
False
not b
True
===============================================================================
Membership & Identity Operators
Membership Operators
str1=”I have a lazy dog”
>>> str1=”I have a lazy dog”
>>> str1
‘I have a lazy dog’
>>> “dog” in str1
True
>>> mylist=[1,3,19,32,48,77]
>>> 65 in mylist
False
>>>
>>> 19 in mylist
True
>>>
Identity Operators
>>> a = 43
>>> b= ’43’
>>> a is b
False
>>>
>>> c=42
>>> a is c
False
>>> c=43
>>> a is c
True
>>>
===============================================================================
Operator Precedence
Multiple operator proceeds first
>>>5+4*2
13
>>>
>>> (5+4)*2
18
>>>
=====================================================================================
The IF statement
>>> myvar=50
>>> if myvar<100:
print(“You are 100 %”)
You are 100 %
>>>
>>> myvar=150
>>> if myvar<100:
print(“You are 100 %”)
>>>
=====================================================================================
The ELSE Statement
>>> myvar=50
>>> if myvar<100:
print(“your are short of 100 %”)
else:
print (“your in 100 %”)
print (“thank you”)
your are short of 100 %
>>>
============================================================================
The ELIF Statement
>>> sp=1500
>>> cp=1200
>>> if (sp>cp):
print(“congrats!”)
print(“You’ve made profit of “, sp-cp,”bucks”)
elif (cp>sp):
print(“oops!”)
print(“You ve made a loss of “, cp-sp,”bucks”)
else:
print(“You did or lose money”)
congrats!
You’ve made profit of 300 bucks
>>> sp=1500
>>> cp=1500
>>> if (sp>cp):
print(“congrats!”)
print(“You’ve made profit of “, sp-cp,”bucks”)
elif (cp>sp):
print(“oops!”)
print(“You ve made a loss of “, cp-sp,”bucks”)
else:
print(“You did or lose money”)
You did or lose money
============================================================================
Nested IF-ELSE
>>> char=input()
if ord(char)>=65 and ord(char)<=90:
print(“You entered an uper case alpabet.”)
if char in [‘A’,’E’,’I’,’O’,’U’]:
print(“You entered a Vowel.”)
else:
print(“You entered a consonant.”)
elif ord(char)>=97 and ord(char)<=122:
print(“You entered a lower case alaphabet.”)
if char in [‘a’,’e’,’i’,’o’,’u’]:
print(“you entered a vowel.”)
else:
print(“You entered a consonant.”)
else:
print(“you did not enter an alphabet.”)
============================================================================
The WHILE Loop
>>> var=1
>>> while(var<=10):
print(“Hi! i am”, var)
var=var+1
print(“good bye!”)
var=1
>>> while(var<=10):
print(“Hi! i am”, var)
var=var+1
print(“hello”)
print(“good bye!”)
============================================================================
The FOR Loop
>>> count=0
>>> print(“Enter your name:”)
Enter your name:
>>> name=input()
>>> for letter in name:
if (letter in [‘A’,’E’,’I’,’O’,’U’,’a’,’e’,’i’,’o’,’u’]):
count=count+1
print(“You have”,count, “Vowels in your name.”)
You have 1 Vowels in your name.
You have 2 Vowels in your name.
You have 3 Vowels in your name.
You have 4 Vowels in your name.
You have 5 Vowels in your name.
You have 6 Vowels in your name.
You have 7 Vowels in your name.
You have 8 Vowels in your name.
You have 9 Vowels in your name.
>>>
============================================================================
The Break Statement
var=1
while(var<=15):
print(var)
var=var+1
print(“Good bye”)
1
Good bye
2
Good bye
3
Good bye
4
Good bye
5
Good bye
6
Good bye
7
Good bye
8
Good bye
9
Good bye
10
Good bye
11
Good bye
12
Good bye
13
Good bye
14
Good bye
15
Good bye
>>>
>>> var=1
>>> while(var<=15):
if(var==10):
break
print(var)
var=var+1
print(“Good bye”)
1
Good bye
2
Good bye
3
Good bye
4
Good bye
5
Good bye
6
Good bye
7
Good bye
8
Good bye
9
Good bye
============================================================================
Application of Break Statement
while True:
print(“Enter a digit:”)
num=input()
var=str(num)
if(ord(var) in range(48,58)):
break
print(“You are very obedient!”)
============================================================================
Nested Loops
for var1 in range(2,101):
flag=True
for var2 in range(2,var1-1):
if(var1%var2==0):
print(var1,”is not a prime number”)
flag=False
break
if flag:
print(var1, “is a prime number.”)
============================================================================
The Continue Statement
for var in range(1,16):
if(var in range(9,14)):
continue
else:
print(var)
print(“Enter a string:”)
Enter a string:
var=input()
for letter in var:
if(leter==’ ‘):
continue
else:
print(letter)
========================================================================
Numeric Functions
abs(5)
abs(-5)
import math
math.ceil(35.74)
>>> import math
>>> math.ceil(35.74)
36
>>> math.e
2.718281828459045
>>> math.exp(7)
1096.6331584284585
>>> math.e**7
1096.6331584284583
>>> math.floor(16.94)
16
>>> math.floor(-16.94)
-17
>>>
>>> math.sqrt(25)
5.0
>>>
>>> math.log(5)
1.6094379124341003
>>> math.log(math.e)
1.0
>>> >>> math.log10(10)
1.0
>>>
>>> max(10,15,20,45-18)
27
>>> max(10,15,20,45-18)
27
>>> min(11,19,17,6-213)
-207
>>>
>>> round(17.234234)
17
>>> math.modf(11.971)
(0.9710000000000001, 11.0)
>>> math.pow(4,2)
16.0
>>>
>>> math.hypot(5,12)
13.0
>>> math.hypot(3,14)
14.317821063276352
>>>
>>> math.degrees(math.pi)
180.0
>>> math.degrees(-4)
-229.1831180523293
>>> math.radians(-229.18311)
-3.9999998594603414
>>>
========================================================================
String Functions
>>> str1=”hey, how are you?”
>>> str1.capitalize()
‘Hey, how are you?’
>>> str1=”””tom is a good guy
tom is hard working
tom is honest
tom is team player
tom work out”””
>>> str1
‘tom is a good guy\ntom is hard working\ntom is honest\ntom is team player\ntom work out’
>>>
>>> str1.count(‘tom’)
5
>>> str1=”rmohan.com”
>>> str1.endswith(‘.org’)
False
>>> str1.endswith(‘.com’)
True
>>>
>>> str1=”catch me if you can”
>>> str1.find(‘you’)
12
>>>
>>> str1=”hey, how are you?”
>>> str1=”””tom is a good guy
tom is hard working
tom is honest
tom is team player
tom work out”””
>>> str1.count(‘tom’)
5
>>>
>>>
>>> str1=”rmohan.com”
>>> str1.endswith(‘.org’)
False
>>> str1.endswith(‘.com’)
True
>>> str1.endswith(‘.com’)
True
>>> str1=”Hello World”
>>> str1.islower()
False
>>> str1=”hello world”
>>> str1.islower()
True
>>>
>>> str1=”!!!!!!what’s up dudes?”
>>> str1.lstrip(‘!’)
“what’s up dudes?”
>>> str1=”!!!!!!what’s up dudes?”
>>> str1.lstrip(‘!’)
“what’s up dudes?”
>>> str1=”This is so cool!!!!!!”
>
>>> str1.rstrip(‘!’)
‘This is so cool’
>>> str1=”This is so cool!!!!!!”
>>> str1.rstrip(‘!’)
‘This is so cool’
>>> str1.upper()
‘THIS IS SO COOL!!!!!!’
>>> str=”I once had a fox”
>>> str1.replace(‘fox’,’lion’)
‘This is so cool!!!!!!’
>>> str1
‘This is so cool!!!!!!’
>>> str1=”I once had a fox”
>>> str1.replace(‘fox’,’lion’)
‘I once had a lion’
>>> str1=”I once had a fox”
>>> str1.replace(‘fox’,’lion’)
‘I once had a lion’
>>> str1
‘I once had a fox’
>>> str1=”Tom cuise”
>>> str1.split()
[‘Tom’, ‘cuise’]
>>>
>>> str1=”########GOOD MORNING########”
>>> str1.strip(‘#’)
‘GOOD MORNING’
>>>
>>>
>>> str1=”I LOVE python”
>>> str1.swapcase()
‘i love PYTHON’
>>> str1.swapcase()
‘i love PYTHON’
>>> str1.title()
‘I Love Python’
>>>
List Functions
>>> mylist=[1,3,5,9,4]
>>> len(mylist)
5
>>> max(mylist)
9
>>> min(mylist)
1
>>> mylist=[3,3,3,3,3,1,1,5,5,5,7,7,7,7,9,9]
>>> mylist.count(7)
4
>>> mylist.append(8)
>>> mylist
[3, 3, 3, 3, 3, 1, 1, 5, 5, 5, 7, 7, 7, 7, 9, 9, 8]
>>> mylist.append(8)
>>> mylist
[3, 3, 3, 3, 3, 1, 1, 5, 5, 5, 7, 7, 7, 7, 9, 9, 8, 8]
>>>
>>> mylist=[4,1,9,3,7,2]
>>> mylist.insert(5,6)
>>> mylist
[4, 1, 9, 3, 7, 6, 2]
>>>
>>> mylist=[4,1,9,3,7,2]
>>> mylist.insert(5,6)
>>> mylist
[4, 1, 9, 3, 7, 6, 2]
>>> mylist.remove(9)
>>> mylist
[4, 1, 3, 7, 6, 2]
>>> mylist.reverse()
>>> mylist
[2, 6, 7, 3, 1, 4]
>>> mylist.sort()
>>> mylist
[1, 2, 3, 4, 6, 7]
>>>
===========================================================================
Reading Specific Lines Text File
cat file.txt
line 1
line 2
line 3
line 4
line 5
#!/usr/bin/env python
f = open(“file.txt”)
for x, line in enumerate(f):
if x==3:
print line
f.close()
#!/usr/bin/env python
f = open(“file.txt”)
for x, line in enumerate(f):
if x==3:
print line
elif x ==2:
print line
f.close()
Reading from a text file
>>> infile = open(“test.txt”)
>>> dataline = infile.read()
>>> dataline
‘Hello world\nTest1’
>>> dataline.split()
[‘Hello’, ‘world’, ‘Test1’]
>>>
======================================================================
Tuple Functions
>>> mytuple=(1,2,’lamb’,’apple’,7)
>>> len(mytuple)
5
>>> mytuple=(78,84,112,-91,43,221)
>>> max(mytuple)
221
>>> min(mytuple)
-91
~
Dictionary Functions
>> movies={1994: ‘Pulp Fiction’ , 1997: ‘Seven’,2000: ‘Cast Away’ ,2006: ‘Blood Diamond’}
>>> movies.keys()
dict_keys([2000, 1994, 1997, 2006])
>>> movies.values()
dict_values([‘Cast Away’, ‘Pulp Fiction’, ‘Seven’, ‘Blood Diamond’])
>>> new={1972:”The GodFather”,1980:”Raging Bull”,2004:”The Aviator”}
>>> new
{1980: ‘Raging Bull’, 1972: ‘The GodFather’, 2004: ‘The Aviator’}
>>>
>>> movies.update(new)
>>> movies
{2000: ‘Cast Away’, 1972: ‘The GodFather’, 2006: ‘Blood Diamond’, 2004: ‘The Aviator’, 1994: ‘Pulp Fiction’, 1980: ‘Raging Bull’, 1997: ‘Seven’}
>>> movies.clear()
>>> movies
{}
>>>
Recent Comments